View.java revision 67c360f3d52e705258182dbc448ef528599482fa
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.view; 18 19import android.animation.AnimatorInflater; 20import android.animation.RevealAnimator; 21import android.animation.StateListAnimator; 22import android.animation.ValueAnimator; 23import android.annotation.IntDef; 24import android.annotation.NonNull; 25import android.annotation.Nullable; 26import android.content.ClipData; 27import android.content.Context; 28import android.content.res.Configuration; 29import android.content.res.Resources; 30import android.content.res.TypedArray; 31import android.graphics.Bitmap; 32import android.graphics.Canvas; 33import android.graphics.Insets; 34import android.graphics.Interpolator; 35import android.graphics.LinearGradient; 36import android.graphics.Matrix; 37import android.graphics.Outline; 38import android.graphics.Paint; 39import android.graphics.PixelFormat; 40import android.graphics.Point; 41import android.graphics.PorterDuff; 42import android.graphics.PorterDuffXfermode; 43import android.graphics.Rect; 44import android.graphics.RectF; 45import android.graphics.Region; 46import android.graphics.Shader; 47import android.graphics.drawable.ColorDrawable; 48import android.graphics.drawable.Drawable; 49import android.hardware.display.DisplayManagerGlobal; 50import android.os.Bundle; 51import android.os.Handler; 52import android.os.IBinder; 53import android.os.Parcel; 54import android.os.Parcelable; 55import android.os.RemoteException; 56import android.os.SystemClock; 57import android.os.SystemProperties; 58import android.text.TextUtils; 59import android.util.AttributeSet; 60import android.util.FloatProperty; 61import android.util.LayoutDirection; 62import android.util.Log; 63import android.util.LongSparseLongArray; 64import android.util.Pools.SynchronizedPool; 65import android.util.Property; 66import android.util.SparseArray; 67import android.util.SuperNotCalledException; 68import android.util.TypedValue; 69import android.view.ContextMenu.ContextMenuInfo; 70import android.view.AccessibilityIterators.TextSegmentIterator; 71import android.view.AccessibilityIterators.CharacterTextSegmentIterator; 72import android.view.AccessibilityIterators.WordTextSegmentIterator; 73import android.view.AccessibilityIterators.ParagraphTextSegmentIterator; 74import android.view.accessibility.AccessibilityEvent; 75import android.view.accessibility.AccessibilityEventSource; 76import android.view.accessibility.AccessibilityManager; 77import android.view.accessibility.AccessibilityNodeInfo; 78import android.view.accessibility.AccessibilityNodeProvider; 79import android.view.animation.Animation; 80import android.view.animation.AnimationUtils; 81import android.view.animation.Transformation; 82import android.view.inputmethod.EditorInfo; 83import android.view.inputmethod.InputConnection; 84import android.view.inputmethod.InputMethodManager; 85import android.widget.ScrollBarDrawable; 86 87import static android.os.Build.VERSION_CODES.*; 88import static java.lang.Math.max; 89 90import com.android.internal.R; 91import com.android.internal.util.Predicate; 92import com.android.internal.view.menu.MenuBuilder; 93import com.google.android.collect.Lists; 94import com.google.android.collect.Maps; 95 96import java.lang.annotation.Retention; 97import java.lang.annotation.RetentionPolicy; 98import java.lang.ref.WeakReference; 99import java.lang.reflect.Field; 100import java.lang.reflect.InvocationTargetException; 101import java.lang.reflect.Method; 102import java.lang.reflect.Modifier; 103import java.util.ArrayList; 104import java.util.Arrays; 105import java.util.Collections; 106import java.util.HashMap; 107import java.util.List; 108import java.util.Locale; 109import java.util.Map; 110import java.util.concurrent.CopyOnWriteArrayList; 111import java.util.concurrent.atomic.AtomicInteger; 112 113/** 114 * <p> 115 * This class represents the basic building block for user interface components. A View 116 * occupies a rectangular area on the screen and is responsible for drawing and 117 * event handling. View is the base class for <em>widgets</em>, which are 118 * used to create interactive UI components (buttons, text fields, etc.). The 119 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which 120 * are invisible containers that hold other Views (or other ViewGroups) and define 121 * their layout properties. 122 * </p> 123 * 124 * <div class="special reference"> 125 * <h3>Developer Guides</h3> 126 * <p>For information about using this class to develop your application's user interface, 127 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide. 128 * </div> 129 * 130 * <a name="Using"></a> 131 * <h3>Using Views</h3> 132 * <p> 133 * All of the views in a window are arranged in a single tree. You can add views 134 * either from code or by specifying a tree of views in one or more XML layout 135 * files. There are many specialized subclasses of views that act as controls or 136 * are capable of displaying text, images, or other content. 137 * </p> 138 * <p> 139 * Once you have created a tree of views, there are typically a few types of 140 * common operations you may wish to perform: 141 * <ul> 142 * <li><strong>Set properties:</strong> for example setting the text of a 143 * {@link android.widget.TextView}. The available properties and the methods 144 * that set them will vary among the different subclasses of views. Note that 145 * properties that are known at build time can be set in the XML layout 146 * files.</li> 147 * <li><strong>Set focus:</strong> The framework will handled moving focus in 148 * response to user input. To force focus to a specific view, call 149 * {@link #requestFocus}.</li> 150 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 151 * that will be notified when something interesting happens to the view. For 152 * example, all views will let you set a listener to be notified when the view 153 * gains or loses focus. You can register such a listener using 154 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}. 155 * Other view subclasses offer more specialized listeners. For example, a Button 156 * exposes a listener to notify clients when the button is clicked.</li> 157 * <li><strong>Set visibility:</strong> You can hide or show views using 158 * {@link #setVisibility(int)}.</li> 159 * </ul> 160 * </p> 161 * <p><em> 162 * Note: The Android framework is responsible for measuring, laying out and 163 * drawing views. You should not call methods that perform these actions on 164 * views yourself unless you are actually implementing a 165 * {@link android.view.ViewGroup}. 166 * </em></p> 167 * 168 * <a name="Lifecycle"></a> 169 * <h3>Implementing a Custom View</h3> 170 * 171 * <p> 172 * To implement a custom view, you will usually begin by providing overrides for 173 * some of the standard methods that the framework calls on all views. You do 174 * not need to override all of these methods. In fact, you can start by just 175 * overriding {@link #onDraw(android.graphics.Canvas)}. 176 * <table border="2" width="85%" align="center" cellpadding="5"> 177 * <thead> 178 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 179 * </thead> 180 * 181 * <tbody> 182 * <tr> 183 * <td rowspan="2">Creation</td> 184 * <td>Constructors</td> 185 * <td>There is a form of the constructor that are called when the view 186 * is created from code and a form that is called when the view is 187 * inflated from a layout file. The second form should parse and apply 188 * any attributes defined in the layout file. 189 * </td> 190 * </tr> 191 * <tr> 192 * <td><code>{@link #onFinishInflate()}</code></td> 193 * <td>Called after a view and all of its children has been inflated 194 * from XML.</td> 195 * </tr> 196 * 197 * <tr> 198 * <td rowspan="3">Layout</td> 199 * <td><code>{@link #onMeasure(int, int)}</code></td> 200 * <td>Called to determine the size requirements for this view and all 201 * of its children. 202 * </td> 203 * </tr> 204 * <tr> 205 * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td> 206 * <td>Called when this view should assign a size and position to all 207 * of its children. 208 * </td> 209 * </tr> 210 * <tr> 211 * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td> 212 * <td>Called when the size of this view has changed. 213 * </td> 214 * </tr> 215 * 216 * <tr> 217 * <td>Drawing</td> 218 * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td> 219 * <td>Called when the view should render its content. 220 * </td> 221 * </tr> 222 * 223 * <tr> 224 * <td rowspan="4">Event processing</td> 225 * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td> 226 * <td>Called when a new hardware key event occurs. 227 * </td> 228 * </tr> 229 * <tr> 230 * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td> 231 * <td>Called when a hardware key up event occurs. 232 * </td> 233 * </tr> 234 * <tr> 235 * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td> 236 * <td>Called when a trackball motion event occurs. 237 * </td> 238 * </tr> 239 * <tr> 240 * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td> 241 * <td>Called when a touch screen motion event occurs. 242 * </td> 243 * </tr> 244 * 245 * <tr> 246 * <td rowspan="2">Focus</td> 247 * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td> 248 * <td>Called when the view gains or loses focus. 249 * </td> 250 * </tr> 251 * 252 * <tr> 253 * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td> 254 * <td>Called when the window containing the view gains or loses focus. 255 * </td> 256 * </tr> 257 * 258 * <tr> 259 * <td rowspan="3">Attaching</td> 260 * <td><code>{@link #onAttachedToWindow()}</code></td> 261 * <td>Called when the view is attached to a window. 262 * </td> 263 * </tr> 264 * 265 * <tr> 266 * <td><code>{@link #onDetachedFromWindow}</code></td> 267 * <td>Called when the view is detached from its window. 268 * </td> 269 * </tr> 270 * 271 * <tr> 272 * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td> 273 * <td>Called when the visibility of the window containing the view 274 * has changed. 275 * </td> 276 * </tr> 277 * </tbody> 278 * 279 * </table> 280 * </p> 281 * 282 * <a name="IDs"></a> 283 * <h3>IDs</h3> 284 * Views may have an integer id associated with them. These ids are typically 285 * assigned in the layout XML files, and are used to find specific views within 286 * the view tree. A common pattern is to: 287 * <ul> 288 * <li>Define a Button in the layout file and assign it a unique ID. 289 * <pre> 290 * <Button 291 * android:id="@+id/my_button" 292 * android:layout_width="wrap_content" 293 * android:layout_height="wrap_content" 294 * android:text="@string/my_button_text"/> 295 * </pre></li> 296 * <li>From the onCreate method of an Activity, find the Button 297 * <pre class="prettyprint"> 298 * Button myButton = (Button) findViewById(R.id.my_button); 299 * </pre></li> 300 * </ul> 301 * <p> 302 * View IDs need not be unique throughout the tree, but it is good practice to 303 * ensure that they are at least unique within the part of the tree you are 304 * searching. 305 * </p> 306 * 307 * <a name="Position"></a> 308 * <h3>Position</h3> 309 * <p> 310 * The geometry of a view is that of a rectangle. A view has a location, 311 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 312 * two dimensions, expressed as a width and a height. The unit for location 313 * and dimensions is the pixel. 314 * </p> 315 * 316 * <p> 317 * It is possible to retrieve the location of a view by invoking the methods 318 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 319 * coordinate of the rectangle representing the view. The latter returns the 320 * top, or Y, coordinate of the rectangle representing the view. These methods 321 * both return the location of the view relative to its parent. For instance, 322 * when getLeft() returns 20, that means the view is located 20 pixels to the 323 * right of the left edge of its direct parent. 324 * </p> 325 * 326 * <p> 327 * In addition, several convenience methods are offered to avoid unnecessary 328 * computations, namely {@link #getRight()} and {@link #getBottom()}. 329 * These methods return the coordinates of the right and bottom edges of the 330 * rectangle representing the view. For instance, calling {@link #getRight()} 331 * is similar to the following computation: <code>getLeft() + getWidth()</code> 332 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 333 * </p> 334 * 335 * <a name="SizePaddingMargins"></a> 336 * <h3>Size, padding and margins</h3> 337 * <p> 338 * The size of a view is expressed with a width and a height. A view actually 339 * possess two pairs of width and height values. 340 * </p> 341 * 342 * <p> 343 * The first pair is known as <em>measured width</em> and 344 * <em>measured height</em>. These dimensions define how big a view wants to be 345 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 346 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 347 * and {@link #getMeasuredHeight()}. 348 * </p> 349 * 350 * <p> 351 * The second pair is simply known as <em>width</em> and <em>height</em>, or 352 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 353 * dimensions define the actual size of the view on screen, at drawing time and 354 * after layout. These values may, but do not have to, be different from the 355 * measured width and height. The width and height can be obtained by calling 356 * {@link #getWidth()} and {@link #getHeight()}. 357 * </p> 358 * 359 * <p> 360 * To measure its dimensions, a view takes into account its padding. The padding 361 * is expressed in pixels for the left, top, right and bottom parts of the view. 362 * Padding can be used to offset the content of the view by a specific amount of 363 * pixels. For instance, a left padding of 2 will push the view's content by 364 * 2 pixels to the right of the left edge. Padding can be set using the 365 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)} 366 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 367 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()}, 368 * {@link #getPaddingEnd()}. 369 * </p> 370 * 371 * <p> 372 * Even though a view can define a padding, it does not provide any support for 373 * margins. However, view groups provide such a support. Refer to 374 * {@link android.view.ViewGroup} and 375 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 376 * </p> 377 * 378 * <a name="Layout"></a> 379 * <h3>Layout</h3> 380 * <p> 381 * Layout is a two pass process: a measure pass and a layout pass. The measuring 382 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 383 * of the view tree. Each view pushes dimension specifications down the tree 384 * during the recursion. At the end of the measure pass, every view has stored 385 * its measurements. The second pass happens in 386 * {@link #layout(int,int,int,int)} and is also top-down. During 387 * this pass each parent is responsible for positioning all of its children 388 * using the sizes computed in the measure pass. 389 * </p> 390 * 391 * <p> 392 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 393 * {@link #getMeasuredHeight()} values must be set, along with those for all of 394 * that view's descendants. A view's measured width and measured height values 395 * must respect the constraints imposed by the view's parents. This guarantees 396 * that at the end of the measure pass, all parents accept all of their 397 * children's measurements. A parent view may call measure() more than once on 398 * its children. For example, the parent may measure each child once with 399 * unspecified dimensions to find out how big they want to be, then call 400 * measure() on them again with actual numbers if the sum of all the children's 401 * unconstrained sizes is too big or too small. 402 * </p> 403 * 404 * <p> 405 * The measure pass uses two classes to communicate dimensions. The 406 * {@link MeasureSpec} class is used by views to tell their parents how they 407 * want to be measured and positioned. The base LayoutParams class just 408 * describes how big the view wants to be for both width and height. For each 409 * dimension, it can specify one of: 410 * <ul> 411 * <li> an exact number 412 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 413 * (minus padding) 414 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 415 * enclose its content (plus padding). 416 * </ul> 417 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 418 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 419 * an X and Y value. 420 * </p> 421 * 422 * <p> 423 * MeasureSpecs are used to push requirements down the tree from parent to 424 * child. A MeasureSpec can be in one of three modes: 425 * <ul> 426 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 427 * of a child view. For example, a LinearLayout may call measure() on its child 428 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 429 * tall the child view wants to be given a width of 240 pixels. 430 * <li>EXACTLY: This is used by the parent to impose an exact size on the 431 * child. The child must use this size, and guarantee that all of its 432 * descendants will fit within this size. 433 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 434 * child. The child must gurantee that it and all of its descendants will fit 435 * within this size. 436 * </ul> 437 * </p> 438 * 439 * <p> 440 * To intiate a layout, call {@link #requestLayout}. This method is typically 441 * called by a view on itself when it believes that is can no longer fit within 442 * its current bounds. 443 * </p> 444 * 445 * <a name="Drawing"></a> 446 * <h3>Drawing</h3> 447 * <p> 448 * Drawing is handled by walking the tree and rendering each view that 449 * intersects the invalid region. Because the tree is traversed in-order, 450 * this means that parents will draw before (i.e., behind) their children, with 451 * siblings drawn in the order they appear in the tree. 452 * If you set a background drawable for a View, then the View will draw it for you 453 * before calling back to its <code>onDraw()</code> method. 454 * </p> 455 * 456 * <p> 457 * Note that the framework will not draw views that are not in the invalid region. 458 * </p> 459 * 460 * <p> 461 * To force a view to draw, call {@link #invalidate()}. 462 * </p> 463 * 464 * <a name="EventHandlingThreading"></a> 465 * <h3>Event Handling and Threading</h3> 466 * <p> 467 * The basic cycle of a view is as follows: 468 * <ol> 469 * <li>An event comes in and is dispatched to the appropriate view. The view 470 * handles the event and notifies any listeners.</li> 471 * <li>If in the course of processing the event, the view's bounds may need 472 * to be changed, the view will call {@link #requestLayout()}.</li> 473 * <li>Similarly, if in the course of processing the event the view's appearance 474 * may need to be changed, the view will call {@link #invalidate()}.</li> 475 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 476 * the framework will take care of measuring, laying out, and drawing the tree 477 * as appropriate.</li> 478 * </ol> 479 * </p> 480 * 481 * <p><em>Note: The entire view tree is single threaded. You must always be on 482 * the UI thread when calling any method on any view.</em> 483 * If you are doing work on other threads and want to update the state of a view 484 * from that thread, you should use a {@link Handler}. 485 * </p> 486 * 487 * <a name="FocusHandling"></a> 488 * <h3>Focus Handling</h3> 489 * <p> 490 * The framework will handle routine focus movement in response to user input. 491 * This includes changing the focus as views are removed or hidden, or as new 492 * views become available. Views indicate their willingness to take focus 493 * through the {@link #isFocusable} method. To change whether a view can take 494 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 495 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 496 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 497 * </p> 498 * <p> 499 * Focus movement is based on an algorithm which finds the nearest neighbor in a 500 * given direction. In rare cases, the default algorithm may not match the 501 * intended behavior of the developer. In these situations, you can provide 502 * explicit overrides by using these XML attributes in the layout file: 503 * <pre> 504 * nextFocusDown 505 * nextFocusLeft 506 * nextFocusRight 507 * nextFocusUp 508 * </pre> 509 * </p> 510 * 511 * 512 * <p> 513 * To get a particular view to take focus, call {@link #requestFocus()}. 514 * </p> 515 * 516 * <a name="TouchMode"></a> 517 * <h3>Touch Mode</h3> 518 * <p> 519 * When a user is navigating a user interface via directional keys such as a D-pad, it is 520 * necessary to give focus to actionable items such as buttons so the user can see 521 * what will take input. If the device has touch capabilities, however, and the user 522 * begins interacting with the interface by touching it, it is no longer necessary to 523 * always highlight, or give focus to, a particular view. This motivates a mode 524 * for interaction named 'touch mode'. 525 * </p> 526 * <p> 527 * For a touch capable device, once the user touches the screen, the device 528 * will enter touch mode. From this point onward, only views for which 529 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 530 * Other views that are touchable, like buttons, will not take focus when touched; they will 531 * only fire the on click listeners. 532 * </p> 533 * <p> 534 * Any time a user hits a directional key, such as a D-pad direction, the view device will 535 * exit touch mode, and find a view to take focus, so that the user may resume interacting 536 * with the user interface without touching the screen again. 537 * </p> 538 * <p> 539 * The touch mode state is maintained across {@link android.app.Activity}s. Call 540 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 541 * </p> 542 * 543 * <a name="Scrolling"></a> 544 * <h3>Scrolling</h3> 545 * <p> 546 * The framework provides basic support for views that wish to internally 547 * scroll their content. This includes keeping track of the X and Y scroll 548 * offset as well as mechanisms for drawing scrollbars. See 549 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 550 * {@link #awakenScrollBars()} for more details. 551 * </p> 552 * 553 * <a name="Tags"></a> 554 * <h3>Tags</h3> 555 * <p> 556 * Unlike IDs, tags are not used to identify views. Tags are essentially an 557 * extra piece of information that can be associated with a view. They are most 558 * often used as a convenience to store data related to views in the views 559 * themselves rather than by putting them in a separate structure. 560 * </p> 561 * 562 * <a name="Properties"></a> 563 * <h3>Properties</h3> 564 * <p> 565 * The View class exposes an {@link #ALPHA} property, as well as several transform-related 566 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are 567 * available both in the {@link Property} form as well as in similarly-named setter/getter 568 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can 569 * be used to set persistent state associated with these rendering-related properties on the view. 570 * The properties and methods can also be used in conjunction with 571 * {@link android.animation.Animator Animator}-based animations, described more in the 572 * <a href="#Animation">Animation</a> section. 573 * </p> 574 * 575 * <a name="Animation"></a> 576 * <h3>Animation</h3> 577 * <p> 578 * Starting with Android 3.0, the preferred way of animating views is to use the 579 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based 580 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and 581 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0 582 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only 583 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class 584 * makes animating these View properties particularly easy and efficient. 585 * </p> 586 * <p> 587 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered. 588 * You can attach an {@link Animation} object to a view using 589 * {@link #setAnimation(Animation)} or 590 * {@link #startAnimation(Animation)}. The animation can alter the scale, 591 * rotation, translation and alpha of a view over time. If the animation is 592 * attached to a view that has children, the animation will affect the entire 593 * subtree rooted by that node. When an animation is started, the framework will 594 * take care of redrawing the appropriate views until the animation completes. 595 * </p> 596 * 597 * <a name="Security"></a> 598 * <h3>Security</h3> 599 * <p> 600 * Sometimes it is essential that an application be able to verify that an action 601 * is being performed with the full knowledge and consent of the user, such as 602 * granting a permission request, making a purchase or clicking on an advertisement. 603 * Unfortunately, a malicious application could try to spoof the user into 604 * performing these actions, unaware, by concealing the intended purpose of the view. 605 * As a remedy, the framework offers a touch filtering mechanism that can be used to 606 * improve the security of views that provide access to sensitive functionality. 607 * </p><p> 608 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 609 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 610 * will discard touches that are received whenever the view's window is obscured by 611 * another visible window. As a result, the view will not receive touches whenever a 612 * toast, dialog or other window appears above the view's window. 613 * </p><p> 614 * For more fine-grained control over security, consider overriding the 615 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 616 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 617 * </p> 618 * 619 * @attr ref android.R.styleable#View_alpha 620 * @attr ref android.R.styleable#View_background 621 * @attr ref android.R.styleable#View_clickable 622 * @attr ref android.R.styleable#View_contentDescription 623 * @attr ref android.R.styleable#View_drawingCacheQuality 624 * @attr ref android.R.styleable#View_duplicateParentState 625 * @attr ref android.R.styleable#View_id 626 * @attr ref android.R.styleable#View_requiresFadingEdge 627 * @attr ref android.R.styleable#View_fadeScrollbars 628 * @attr ref android.R.styleable#View_fadingEdgeLength 629 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 630 * @attr ref android.R.styleable#View_fitsSystemWindows 631 * @attr ref android.R.styleable#View_isScrollContainer 632 * @attr ref android.R.styleable#View_focusable 633 * @attr ref android.R.styleable#View_focusableInTouchMode 634 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 635 * @attr ref android.R.styleable#View_keepScreenOn 636 * @attr ref android.R.styleable#View_layerType 637 * @attr ref android.R.styleable#View_layoutDirection 638 * @attr ref android.R.styleable#View_longClickable 639 * @attr ref android.R.styleable#View_minHeight 640 * @attr ref android.R.styleable#View_minWidth 641 * @attr ref android.R.styleable#View_nextFocusDown 642 * @attr ref android.R.styleable#View_nextFocusLeft 643 * @attr ref android.R.styleable#View_nextFocusRight 644 * @attr ref android.R.styleable#View_nextFocusUp 645 * @attr ref android.R.styleable#View_onClick 646 * @attr ref android.R.styleable#View_padding 647 * @attr ref android.R.styleable#View_paddingBottom 648 * @attr ref android.R.styleable#View_paddingLeft 649 * @attr ref android.R.styleable#View_paddingRight 650 * @attr ref android.R.styleable#View_paddingTop 651 * @attr ref android.R.styleable#View_paddingStart 652 * @attr ref android.R.styleable#View_paddingEnd 653 * @attr ref android.R.styleable#View_saveEnabled 654 * @attr ref android.R.styleable#View_rotation 655 * @attr ref android.R.styleable#View_rotationX 656 * @attr ref android.R.styleable#View_rotationY 657 * @attr ref android.R.styleable#View_scaleX 658 * @attr ref android.R.styleable#View_scaleY 659 * @attr ref android.R.styleable#View_scrollX 660 * @attr ref android.R.styleable#View_scrollY 661 * @attr ref android.R.styleable#View_scrollbarSize 662 * @attr ref android.R.styleable#View_scrollbarStyle 663 * @attr ref android.R.styleable#View_scrollbars 664 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 665 * @attr ref android.R.styleable#View_scrollbarFadeDuration 666 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 667 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 668 * @attr ref android.R.styleable#View_scrollbarThumbVertical 669 * @attr ref android.R.styleable#View_scrollbarTrackVertical 670 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 671 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 672 * @attr ref android.R.styleable#View_stateListAnimator 673 * @attr ref android.R.styleable#View_viewName 674 * @attr ref android.R.styleable#View_soundEffectsEnabled 675 * @attr ref android.R.styleable#View_tag 676 * @attr ref android.R.styleable#View_textAlignment 677 * @attr ref android.R.styleable#View_textDirection 678 * @attr ref android.R.styleable#View_transformPivotX 679 * @attr ref android.R.styleable#View_transformPivotY 680 * @attr ref android.R.styleable#View_translationX 681 * @attr ref android.R.styleable#View_translationY 682 * @attr ref android.R.styleable#View_translationZ 683 * @attr ref android.R.styleable#View_visibility 684 * 685 * @see android.view.ViewGroup 686 */ 687public class View implements Drawable.Callback, KeyEvent.Callback, 688 AccessibilityEventSource { 689 private static final boolean DBG = false; 690 691 /** 692 * The logging tag used by this class with android.util.Log. 693 */ 694 protected static final String VIEW_LOG_TAG = "View"; 695 696 /** 697 * When set to true, apps will draw debugging information about their layouts. 698 * 699 * @hide 700 */ 701 public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout"; 702 703 /** 704 * Used to mark a View that has no ID. 705 */ 706 public static final int NO_ID = -1; 707 708 /** 709 * Signals that compatibility booleans have been initialized according to 710 * target SDK versions. 711 */ 712 private static boolean sCompatibilityDone = false; 713 714 /** 715 * Use the old (broken) way of building MeasureSpecs. 716 */ 717 private static boolean sUseBrokenMakeMeasureSpec = false; 718 719 /** 720 * Ignore any optimizations using the measure cache. 721 */ 722 private static boolean sIgnoreMeasureCache = false; 723 724 /** 725 * Ignore the clipBounds of this view for the children. 726 */ 727 static boolean sIgnoreClipBoundsForChildren = false; 728 729 /** 730 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 731 * calling setFlags. 732 */ 733 private static final int NOT_FOCUSABLE = 0x00000000; 734 735 /** 736 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 737 * setFlags. 738 */ 739 private static final int FOCUSABLE = 0x00000001; 740 741 /** 742 * Mask for use with setFlags indicating bits used for focus. 743 */ 744 private static final int FOCUSABLE_MASK = 0x00000001; 745 746 /** 747 * This view will adjust its padding to fit sytem windows (e.g. status bar) 748 */ 749 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 750 751 /** @hide */ 752 @IntDef({VISIBLE, INVISIBLE, GONE}) 753 @Retention(RetentionPolicy.SOURCE) 754 public @interface Visibility {} 755 756 /** 757 * This view is visible. 758 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 759 * android:visibility}. 760 */ 761 public static final int VISIBLE = 0x00000000; 762 763 /** 764 * This view is invisible, but it still takes up space for layout purposes. 765 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 766 * android:visibility}. 767 */ 768 public static final int INVISIBLE = 0x00000004; 769 770 /** 771 * This view is invisible, and it doesn't take any space for layout 772 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 773 * android:visibility}. 774 */ 775 public static final int GONE = 0x00000008; 776 777 /** 778 * Mask for use with setFlags indicating bits used for visibility. 779 * {@hide} 780 */ 781 static final int VISIBILITY_MASK = 0x0000000C; 782 783 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 784 785 /** 786 * This view is enabled. Interpretation varies by subclass. 787 * Use with ENABLED_MASK when calling setFlags. 788 * {@hide} 789 */ 790 static final int ENABLED = 0x00000000; 791 792 /** 793 * This view is disabled. Interpretation varies by subclass. 794 * Use with ENABLED_MASK when calling setFlags. 795 * {@hide} 796 */ 797 static final int DISABLED = 0x00000020; 798 799 /** 800 * Mask for use with setFlags indicating bits used for indicating whether 801 * this view is enabled 802 * {@hide} 803 */ 804 static final int ENABLED_MASK = 0x00000020; 805 806 /** 807 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 808 * called and further optimizations will be performed. It is okay to have 809 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 810 * {@hide} 811 */ 812 static final int WILL_NOT_DRAW = 0x00000080; 813 814 /** 815 * Mask for use with setFlags indicating bits used for indicating whether 816 * this view is will draw 817 * {@hide} 818 */ 819 static final int DRAW_MASK = 0x00000080; 820 821 /** 822 * <p>This view doesn't show scrollbars.</p> 823 * {@hide} 824 */ 825 static final int SCROLLBARS_NONE = 0x00000000; 826 827 /** 828 * <p>This view shows horizontal scrollbars.</p> 829 * {@hide} 830 */ 831 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 832 833 /** 834 * <p>This view shows vertical scrollbars.</p> 835 * {@hide} 836 */ 837 static final int SCROLLBARS_VERTICAL = 0x00000200; 838 839 /** 840 * <p>Mask for use with setFlags indicating bits used for indicating which 841 * scrollbars are enabled.</p> 842 * {@hide} 843 */ 844 static final int SCROLLBARS_MASK = 0x00000300; 845 846 /** 847 * Indicates that the view should filter touches when its window is obscured. 848 * Refer to the class comments for more information about this security feature. 849 * {@hide} 850 */ 851 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 852 853 /** 854 * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate 855 * that they are optional and should be skipped if the window has 856 * requested system UI flags that ignore those insets for layout. 857 */ 858 static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800; 859 860 /** 861 * <p>This view doesn't show fading edges.</p> 862 * {@hide} 863 */ 864 static final int FADING_EDGE_NONE = 0x00000000; 865 866 /** 867 * <p>This view shows horizontal fading edges.</p> 868 * {@hide} 869 */ 870 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 871 872 /** 873 * <p>This view shows vertical fading edges.</p> 874 * {@hide} 875 */ 876 static final int FADING_EDGE_VERTICAL = 0x00002000; 877 878 /** 879 * <p>Mask for use with setFlags indicating bits used for indicating which 880 * fading edges are enabled.</p> 881 * {@hide} 882 */ 883 static final int FADING_EDGE_MASK = 0x00003000; 884 885 /** 886 * <p>Indicates this view can be clicked. When clickable, a View reacts 887 * to clicks by notifying the OnClickListener.<p> 888 * {@hide} 889 */ 890 static final int CLICKABLE = 0x00004000; 891 892 /** 893 * <p>Indicates this view is caching its drawing into a bitmap.</p> 894 * {@hide} 895 */ 896 static final int DRAWING_CACHE_ENABLED = 0x00008000; 897 898 /** 899 * <p>Indicates that no icicle should be saved for this view.<p> 900 * {@hide} 901 */ 902 static final int SAVE_DISABLED = 0x000010000; 903 904 /** 905 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 906 * property.</p> 907 * {@hide} 908 */ 909 static final int SAVE_DISABLED_MASK = 0x000010000; 910 911 /** 912 * <p>Indicates that no drawing cache should ever be created for this view.<p> 913 * {@hide} 914 */ 915 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 916 917 /** 918 * <p>Indicates this view can take / keep focus when int touch mode.</p> 919 * {@hide} 920 */ 921 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 922 923 /** @hide */ 924 @Retention(RetentionPolicy.SOURCE) 925 @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO}) 926 public @interface DrawingCacheQuality {} 927 928 /** 929 * <p>Enables low quality mode for the drawing cache.</p> 930 */ 931 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 932 933 /** 934 * <p>Enables high quality mode for the drawing cache.</p> 935 */ 936 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 937 938 /** 939 * <p>Enables automatic quality mode for the drawing cache.</p> 940 */ 941 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 942 943 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 944 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 945 }; 946 947 /** 948 * <p>Mask for use with setFlags indicating bits used for the cache 949 * quality property.</p> 950 * {@hide} 951 */ 952 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 953 954 /** 955 * <p> 956 * Indicates this view can be long clicked. When long clickable, a View 957 * reacts to long clicks by notifying the OnLongClickListener or showing a 958 * context menu. 959 * </p> 960 * {@hide} 961 */ 962 static final int LONG_CLICKABLE = 0x00200000; 963 964 /** 965 * <p>Indicates that this view gets its drawable states from its direct parent 966 * and ignores its original internal states.</p> 967 * 968 * @hide 969 */ 970 static final int DUPLICATE_PARENT_STATE = 0x00400000; 971 972 /** @hide */ 973 @IntDef({ 974 SCROLLBARS_INSIDE_OVERLAY, 975 SCROLLBARS_INSIDE_INSET, 976 SCROLLBARS_OUTSIDE_OVERLAY, 977 SCROLLBARS_OUTSIDE_INSET 978 }) 979 @Retention(RetentionPolicy.SOURCE) 980 public @interface ScrollBarStyle {} 981 982 /** 983 * The scrollbar style to display the scrollbars inside the content area, 984 * without increasing the padding. The scrollbars will be overlaid with 985 * translucency on the view's content. 986 */ 987 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 988 989 /** 990 * The scrollbar style to display the scrollbars inside the padded area, 991 * increasing the padding of the view. The scrollbars will not overlap the 992 * content area of the view. 993 */ 994 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 995 996 /** 997 * The scrollbar style to display the scrollbars at the edge of the view, 998 * without increasing the padding. The scrollbars will be overlaid with 999 * translucency. 1000 */ 1001 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 1002 1003 /** 1004 * The scrollbar style to display the scrollbars at the edge of the view, 1005 * increasing the padding of the view. The scrollbars will only overlap the 1006 * background, if any. 1007 */ 1008 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 1009 1010 /** 1011 * Mask to check if the scrollbar style is overlay or inset. 1012 * {@hide} 1013 */ 1014 static final int SCROLLBARS_INSET_MASK = 0x01000000; 1015 1016 /** 1017 * Mask to check if the scrollbar style is inside or outside. 1018 * {@hide} 1019 */ 1020 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 1021 1022 /** 1023 * Mask for scrollbar style. 1024 * {@hide} 1025 */ 1026 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 1027 1028 /** 1029 * View flag indicating that the screen should remain on while the 1030 * window containing this view is visible to the user. This effectively 1031 * takes care of automatically setting the WindowManager's 1032 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 1033 */ 1034 public static final int KEEP_SCREEN_ON = 0x04000000; 1035 1036 /** 1037 * View flag indicating whether this view should have sound effects enabled 1038 * for events such as clicking and touching. 1039 */ 1040 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 1041 1042 /** 1043 * View flag indicating whether this view should have haptic feedback 1044 * enabled for events such as long presses. 1045 */ 1046 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 1047 1048 /** 1049 * <p>Indicates that the view hierarchy should stop saving state when 1050 * it reaches this view. If state saving is initiated immediately at 1051 * the view, it will be allowed. 1052 * {@hide} 1053 */ 1054 static final int PARENT_SAVE_DISABLED = 0x20000000; 1055 1056 /** 1057 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 1058 * {@hide} 1059 */ 1060 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 1061 1062 /** @hide */ 1063 @IntDef(flag = true, 1064 value = { 1065 FOCUSABLES_ALL, 1066 FOCUSABLES_TOUCH_MODE 1067 }) 1068 @Retention(RetentionPolicy.SOURCE) 1069 public @interface FocusableMode {} 1070 1071 /** 1072 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1073 * should add all focusable Views regardless if they are focusable in touch mode. 1074 */ 1075 public static final int FOCUSABLES_ALL = 0x00000000; 1076 1077 /** 1078 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1079 * should add only Views focusable in touch mode. 1080 */ 1081 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 1082 1083 /** @hide */ 1084 @IntDef({ 1085 FOCUS_BACKWARD, 1086 FOCUS_FORWARD, 1087 FOCUS_LEFT, 1088 FOCUS_UP, 1089 FOCUS_RIGHT, 1090 FOCUS_DOWN 1091 }) 1092 @Retention(RetentionPolicy.SOURCE) 1093 public @interface FocusDirection {} 1094 1095 /** @hide */ 1096 @IntDef({ 1097 FOCUS_LEFT, 1098 FOCUS_UP, 1099 FOCUS_RIGHT, 1100 FOCUS_DOWN 1101 }) 1102 @Retention(RetentionPolicy.SOURCE) 1103 public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward 1104 1105 /** 1106 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 1107 * item. 1108 */ 1109 public static final int FOCUS_BACKWARD = 0x00000001; 1110 1111 /** 1112 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 1113 * item. 1114 */ 1115 public static final int FOCUS_FORWARD = 0x00000002; 1116 1117 /** 1118 * Use with {@link #focusSearch(int)}. Move focus to the left. 1119 */ 1120 public static final int FOCUS_LEFT = 0x00000011; 1121 1122 /** 1123 * Use with {@link #focusSearch(int)}. Move focus up. 1124 */ 1125 public static final int FOCUS_UP = 0x00000021; 1126 1127 /** 1128 * Use with {@link #focusSearch(int)}. Move focus to the right. 1129 */ 1130 public static final int FOCUS_RIGHT = 0x00000042; 1131 1132 /** 1133 * Use with {@link #focusSearch(int)}. Move focus down. 1134 */ 1135 public static final int FOCUS_DOWN = 0x00000082; 1136 1137 /** 1138 * Bits of {@link #getMeasuredWidthAndState()} and 1139 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1140 */ 1141 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1142 1143 /** 1144 * Bits of {@link #getMeasuredWidthAndState()} and 1145 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1146 */ 1147 public static final int MEASURED_STATE_MASK = 0xff000000; 1148 1149 /** 1150 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1151 * for functions that combine both width and height into a single int, 1152 * such as {@link #getMeasuredState()} and the childState argument of 1153 * {@link #resolveSizeAndState(int, int, int)}. 1154 */ 1155 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1156 1157 /** 1158 * Bit of {@link #getMeasuredWidthAndState()} and 1159 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1160 * is smaller that the space the view would like to have. 1161 */ 1162 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1163 1164 /** 1165 * Base View state sets 1166 */ 1167 // Singles 1168 /** 1169 * Indicates the view has no states set. States are used with 1170 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1171 * view depending on its state. 1172 * 1173 * @see android.graphics.drawable.Drawable 1174 * @see #getDrawableState() 1175 */ 1176 protected static final int[] EMPTY_STATE_SET; 1177 /** 1178 * Indicates the view is enabled. States are used with 1179 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1180 * view depending on its state. 1181 * 1182 * @see android.graphics.drawable.Drawable 1183 * @see #getDrawableState() 1184 */ 1185 protected static final int[] ENABLED_STATE_SET; 1186 /** 1187 * Indicates the view is focused. States are used with 1188 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1189 * view depending on its state. 1190 * 1191 * @see android.graphics.drawable.Drawable 1192 * @see #getDrawableState() 1193 */ 1194 protected static final int[] FOCUSED_STATE_SET; 1195 /** 1196 * Indicates the view is selected. States are used with 1197 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1198 * view depending on its state. 1199 * 1200 * @see android.graphics.drawable.Drawable 1201 * @see #getDrawableState() 1202 */ 1203 protected static final int[] SELECTED_STATE_SET; 1204 /** 1205 * Indicates the view is pressed. States are used with 1206 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1207 * view depending on its state. 1208 * 1209 * @see android.graphics.drawable.Drawable 1210 * @see #getDrawableState() 1211 */ 1212 protected static final int[] PRESSED_STATE_SET; 1213 /** 1214 * Indicates the view's window has focus. States are used with 1215 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1216 * view depending on its state. 1217 * 1218 * @see android.graphics.drawable.Drawable 1219 * @see #getDrawableState() 1220 */ 1221 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1222 // Doubles 1223 /** 1224 * Indicates the view is enabled and has the focus. 1225 * 1226 * @see #ENABLED_STATE_SET 1227 * @see #FOCUSED_STATE_SET 1228 */ 1229 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1230 /** 1231 * Indicates the view is enabled and selected. 1232 * 1233 * @see #ENABLED_STATE_SET 1234 * @see #SELECTED_STATE_SET 1235 */ 1236 protected static final int[] ENABLED_SELECTED_STATE_SET; 1237 /** 1238 * Indicates the view is enabled and that its window has focus. 1239 * 1240 * @see #ENABLED_STATE_SET 1241 * @see #WINDOW_FOCUSED_STATE_SET 1242 */ 1243 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1244 /** 1245 * Indicates the view is focused and selected. 1246 * 1247 * @see #FOCUSED_STATE_SET 1248 * @see #SELECTED_STATE_SET 1249 */ 1250 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1251 /** 1252 * Indicates the view has the focus and that its window has the focus. 1253 * 1254 * @see #FOCUSED_STATE_SET 1255 * @see #WINDOW_FOCUSED_STATE_SET 1256 */ 1257 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1258 /** 1259 * Indicates the view is selected and that its window has the focus. 1260 * 1261 * @see #SELECTED_STATE_SET 1262 * @see #WINDOW_FOCUSED_STATE_SET 1263 */ 1264 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1265 // Triples 1266 /** 1267 * Indicates the view is enabled, focused and selected. 1268 * 1269 * @see #ENABLED_STATE_SET 1270 * @see #FOCUSED_STATE_SET 1271 * @see #SELECTED_STATE_SET 1272 */ 1273 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1274 /** 1275 * Indicates the view is enabled, focused and its window has the focus. 1276 * 1277 * @see #ENABLED_STATE_SET 1278 * @see #FOCUSED_STATE_SET 1279 * @see #WINDOW_FOCUSED_STATE_SET 1280 */ 1281 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1282 /** 1283 * Indicates the view is enabled, selected and its window has the focus. 1284 * 1285 * @see #ENABLED_STATE_SET 1286 * @see #SELECTED_STATE_SET 1287 * @see #WINDOW_FOCUSED_STATE_SET 1288 */ 1289 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1290 /** 1291 * Indicates the view is focused, selected and its window has the focus. 1292 * 1293 * @see #FOCUSED_STATE_SET 1294 * @see #SELECTED_STATE_SET 1295 * @see #WINDOW_FOCUSED_STATE_SET 1296 */ 1297 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1298 /** 1299 * Indicates the view is enabled, focused, selected and its window 1300 * has the focus. 1301 * 1302 * @see #ENABLED_STATE_SET 1303 * @see #FOCUSED_STATE_SET 1304 * @see #SELECTED_STATE_SET 1305 * @see #WINDOW_FOCUSED_STATE_SET 1306 */ 1307 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1308 /** 1309 * Indicates the view is pressed and its window has the focus. 1310 * 1311 * @see #PRESSED_STATE_SET 1312 * @see #WINDOW_FOCUSED_STATE_SET 1313 */ 1314 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1315 /** 1316 * Indicates the view is pressed and selected. 1317 * 1318 * @see #PRESSED_STATE_SET 1319 * @see #SELECTED_STATE_SET 1320 */ 1321 protected static final int[] PRESSED_SELECTED_STATE_SET; 1322 /** 1323 * Indicates the view is pressed, selected and its window has the focus. 1324 * 1325 * @see #PRESSED_STATE_SET 1326 * @see #SELECTED_STATE_SET 1327 * @see #WINDOW_FOCUSED_STATE_SET 1328 */ 1329 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1330 /** 1331 * Indicates the view is pressed and focused. 1332 * 1333 * @see #PRESSED_STATE_SET 1334 * @see #FOCUSED_STATE_SET 1335 */ 1336 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1337 /** 1338 * Indicates the view is pressed, focused and its window has the focus. 1339 * 1340 * @see #PRESSED_STATE_SET 1341 * @see #FOCUSED_STATE_SET 1342 * @see #WINDOW_FOCUSED_STATE_SET 1343 */ 1344 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1345 /** 1346 * Indicates the view is pressed, focused and selected. 1347 * 1348 * @see #PRESSED_STATE_SET 1349 * @see #SELECTED_STATE_SET 1350 * @see #FOCUSED_STATE_SET 1351 */ 1352 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1353 /** 1354 * Indicates the view is pressed, focused, selected and its window has the focus. 1355 * 1356 * @see #PRESSED_STATE_SET 1357 * @see #FOCUSED_STATE_SET 1358 * @see #SELECTED_STATE_SET 1359 * @see #WINDOW_FOCUSED_STATE_SET 1360 */ 1361 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1362 /** 1363 * Indicates the view is pressed and enabled. 1364 * 1365 * @see #PRESSED_STATE_SET 1366 * @see #ENABLED_STATE_SET 1367 */ 1368 protected static final int[] PRESSED_ENABLED_STATE_SET; 1369 /** 1370 * Indicates the view is pressed, enabled and its window has the focus. 1371 * 1372 * @see #PRESSED_STATE_SET 1373 * @see #ENABLED_STATE_SET 1374 * @see #WINDOW_FOCUSED_STATE_SET 1375 */ 1376 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1377 /** 1378 * Indicates the view is pressed, enabled and selected. 1379 * 1380 * @see #PRESSED_STATE_SET 1381 * @see #ENABLED_STATE_SET 1382 * @see #SELECTED_STATE_SET 1383 */ 1384 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1385 /** 1386 * Indicates the view is pressed, enabled, selected and its window has the 1387 * focus. 1388 * 1389 * @see #PRESSED_STATE_SET 1390 * @see #ENABLED_STATE_SET 1391 * @see #SELECTED_STATE_SET 1392 * @see #WINDOW_FOCUSED_STATE_SET 1393 */ 1394 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1395 /** 1396 * Indicates the view is pressed, enabled and focused. 1397 * 1398 * @see #PRESSED_STATE_SET 1399 * @see #ENABLED_STATE_SET 1400 * @see #FOCUSED_STATE_SET 1401 */ 1402 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1403 /** 1404 * Indicates the view is pressed, enabled, focused and its window has the 1405 * focus. 1406 * 1407 * @see #PRESSED_STATE_SET 1408 * @see #ENABLED_STATE_SET 1409 * @see #FOCUSED_STATE_SET 1410 * @see #WINDOW_FOCUSED_STATE_SET 1411 */ 1412 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1413 /** 1414 * Indicates the view is pressed, enabled, focused and selected. 1415 * 1416 * @see #PRESSED_STATE_SET 1417 * @see #ENABLED_STATE_SET 1418 * @see #SELECTED_STATE_SET 1419 * @see #FOCUSED_STATE_SET 1420 */ 1421 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1422 /** 1423 * Indicates the view is pressed, enabled, focused, selected and its window 1424 * has the focus. 1425 * 1426 * @see #PRESSED_STATE_SET 1427 * @see #ENABLED_STATE_SET 1428 * @see #SELECTED_STATE_SET 1429 * @see #FOCUSED_STATE_SET 1430 * @see #WINDOW_FOCUSED_STATE_SET 1431 */ 1432 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1433 1434 /** 1435 * The order here is very important to {@link #getDrawableState()} 1436 */ 1437 private static final int[][] VIEW_STATE_SETS; 1438 1439 static final int VIEW_STATE_WINDOW_FOCUSED = 1; 1440 static final int VIEW_STATE_SELECTED = 1 << 1; 1441 static final int VIEW_STATE_FOCUSED = 1 << 2; 1442 static final int VIEW_STATE_ENABLED = 1 << 3; 1443 static final int VIEW_STATE_PRESSED = 1 << 4; 1444 static final int VIEW_STATE_ACTIVATED = 1 << 5; 1445 static final int VIEW_STATE_ACCELERATED = 1 << 6; 1446 static final int VIEW_STATE_HOVERED = 1 << 7; 1447 static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8; 1448 static final int VIEW_STATE_DRAG_HOVERED = 1 << 9; 1449 1450 static final int[] VIEW_STATE_IDS = new int[] { 1451 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED, 1452 R.attr.state_selected, VIEW_STATE_SELECTED, 1453 R.attr.state_focused, VIEW_STATE_FOCUSED, 1454 R.attr.state_enabled, VIEW_STATE_ENABLED, 1455 R.attr.state_pressed, VIEW_STATE_PRESSED, 1456 R.attr.state_activated, VIEW_STATE_ACTIVATED, 1457 R.attr.state_accelerated, VIEW_STATE_ACCELERATED, 1458 R.attr.state_hovered, VIEW_STATE_HOVERED, 1459 R.attr.state_drag_can_accept, VIEW_STATE_DRAG_CAN_ACCEPT, 1460 R.attr.state_drag_hovered, VIEW_STATE_DRAG_HOVERED 1461 }; 1462 1463 static { 1464 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) { 1465 throw new IllegalStateException( 1466 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array"); 1467 } 1468 int[] orderedIds = new int[VIEW_STATE_IDS.length]; 1469 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) { 1470 int viewState = R.styleable.ViewDrawableStates[i]; 1471 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) { 1472 if (VIEW_STATE_IDS[j] == viewState) { 1473 orderedIds[i * 2] = viewState; 1474 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1]; 1475 } 1476 } 1477 } 1478 final int NUM_BITS = VIEW_STATE_IDS.length / 2; 1479 VIEW_STATE_SETS = new int[1 << NUM_BITS][]; 1480 for (int i = 0; i < VIEW_STATE_SETS.length; i++) { 1481 int numBits = Integer.bitCount(i); 1482 int[] set = new int[numBits]; 1483 int pos = 0; 1484 for (int j = 0; j < orderedIds.length; j += 2) { 1485 if ((i & orderedIds[j+1]) != 0) { 1486 set[pos++] = orderedIds[j]; 1487 } 1488 } 1489 VIEW_STATE_SETS[i] = set; 1490 } 1491 1492 EMPTY_STATE_SET = VIEW_STATE_SETS[0]; 1493 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED]; 1494 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED]; 1495 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1496 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED]; 1497 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED]; 1498 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1499 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED]; 1500 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1501 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED]; 1502 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1503 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1504 | VIEW_STATE_FOCUSED]; 1505 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED]; 1506 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1507 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED]; 1508 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1509 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED]; 1510 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1511 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1512 | VIEW_STATE_ENABLED]; 1513 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1514 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED]; 1515 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1516 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1517 | VIEW_STATE_ENABLED]; 1518 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1519 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1520 | VIEW_STATE_ENABLED]; 1521 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1522 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1523 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED]; 1524 1525 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED]; 1526 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1527 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED]; 1528 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1529 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED]; 1530 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1531 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1532 | VIEW_STATE_PRESSED]; 1533 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1534 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1535 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1536 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1537 | VIEW_STATE_PRESSED]; 1538 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1539 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1540 | VIEW_STATE_PRESSED]; 1541 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1542 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1543 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1544 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[ 1545 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1546 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1547 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED 1548 | VIEW_STATE_PRESSED]; 1549 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1550 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED 1551 | VIEW_STATE_PRESSED]; 1552 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1553 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1554 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1555 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1556 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED 1557 | VIEW_STATE_PRESSED]; 1558 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1559 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1560 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1561 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1562 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1563 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1564 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1565 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1566 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED 1567 | VIEW_STATE_PRESSED]; 1568 } 1569 1570 /** 1571 * Accessibility event types that are dispatched for text population. 1572 */ 1573 private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES = 1574 AccessibilityEvent.TYPE_VIEW_CLICKED 1575 | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED 1576 | AccessibilityEvent.TYPE_VIEW_SELECTED 1577 | AccessibilityEvent.TYPE_VIEW_FOCUSED 1578 | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED 1579 | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER 1580 | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT 1581 | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED 1582 | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED 1583 | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED 1584 | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY; 1585 1586 /** 1587 * Temporary Rect currently for use in setBackground(). This will probably 1588 * be extended in the future to hold our own class with more than just 1589 * a Rect. :) 1590 */ 1591 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1592 1593 /** 1594 * Map used to store views' tags. 1595 */ 1596 private SparseArray<Object> mKeyedTags; 1597 1598 /** 1599 * The next available accessibility id. 1600 */ 1601 private static int sNextAccessibilityViewId; 1602 1603 /** 1604 * The animation currently associated with this view. 1605 * @hide 1606 */ 1607 protected Animation mCurrentAnimation = null; 1608 1609 /** 1610 * Width as measured during measure pass. 1611 * {@hide} 1612 */ 1613 @ViewDebug.ExportedProperty(category = "measurement") 1614 int mMeasuredWidth; 1615 1616 /** 1617 * Height as measured during measure pass. 1618 * {@hide} 1619 */ 1620 @ViewDebug.ExportedProperty(category = "measurement") 1621 int mMeasuredHeight; 1622 1623 /** 1624 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1625 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1626 * its display list. This flag, used only when hw accelerated, allows us to clear the 1627 * flag while retaining this information until it's needed (at getDisplayList() time and 1628 * in drawChild(), when we decide to draw a view's children's display lists into our own). 1629 * 1630 * {@hide} 1631 */ 1632 boolean mRecreateDisplayList = false; 1633 1634 /** 1635 * The view's identifier. 1636 * {@hide} 1637 * 1638 * @see #setId(int) 1639 * @see #getId() 1640 */ 1641 @ViewDebug.ExportedProperty(resolveId = true) 1642 int mID = NO_ID; 1643 1644 /** 1645 * The stable ID of this view for accessibility purposes. 1646 */ 1647 int mAccessibilityViewId = NO_ID; 1648 1649 private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 1650 1651 SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent; 1652 1653 /** 1654 * The view's tag. 1655 * {@hide} 1656 * 1657 * @see #setTag(Object) 1658 * @see #getTag() 1659 */ 1660 protected Object mTag = null; 1661 1662 // for mPrivateFlags: 1663 /** {@hide} */ 1664 static final int PFLAG_WANTS_FOCUS = 0x00000001; 1665 /** {@hide} */ 1666 static final int PFLAG_FOCUSED = 0x00000002; 1667 /** {@hide} */ 1668 static final int PFLAG_SELECTED = 0x00000004; 1669 /** {@hide} */ 1670 static final int PFLAG_IS_ROOT_NAMESPACE = 0x00000008; 1671 /** {@hide} */ 1672 static final int PFLAG_HAS_BOUNDS = 0x00000010; 1673 /** {@hide} */ 1674 static final int PFLAG_DRAWN = 0x00000020; 1675 /** 1676 * When this flag is set, this view is running an animation on behalf of its 1677 * children and should therefore not cancel invalidate requests, even if they 1678 * lie outside of this view's bounds. 1679 * 1680 * {@hide} 1681 */ 1682 static final int PFLAG_DRAW_ANIMATION = 0x00000040; 1683 /** {@hide} */ 1684 static final int PFLAG_SKIP_DRAW = 0x00000080; 1685 /** {@hide} */ 1686 static final int PFLAG_ONLY_DRAWS_BACKGROUND = 0x00000100; 1687 /** {@hide} */ 1688 static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1689 /** {@hide} */ 1690 static final int PFLAG_DRAWABLE_STATE_DIRTY = 0x00000400; 1691 /** {@hide} */ 1692 static final int PFLAG_MEASURED_DIMENSION_SET = 0x00000800; 1693 /** {@hide} */ 1694 static final int PFLAG_FORCE_LAYOUT = 0x00001000; 1695 /** {@hide} */ 1696 static final int PFLAG_LAYOUT_REQUIRED = 0x00002000; 1697 1698 private static final int PFLAG_PRESSED = 0x00004000; 1699 1700 /** {@hide} */ 1701 static final int PFLAG_DRAWING_CACHE_VALID = 0x00008000; 1702 /** 1703 * Flag used to indicate that this view should be drawn once more (and only once 1704 * more) after its animation has completed. 1705 * {@hide} 1706 */ 1707 static final int PFLAG_ANIMATION_STARTED = 0x00010000; 1708 1709 private static final int PFLAG_SAVE_STATE_CALLED = 0x00020000; 1710 1711 /** 1712 * Indicates that the View returned true when onSetAlpha() was called and that 1713 * the alpha must be restored. 1714 * {@hide} 1715 */ 1716 static final int PFLAG_ALPHA_SET = 0x00040000; 1717 1718 /** 1719 * Set by {@link #setScrollContainer(boolean)}. 1720 */ 1721 static final int PFLAG_SCROLL_CONTAINER = 0x00080000; 1722 1723 /** 1724 * Set by {@link #setScrollContainer(boolean)}. 1725 */ 1726 static final int PFLAG_SCROLL_CONTAINER_ADDED = 0x00100000; 1727 1728 /** 1729 * View flag indicating whether this view was invalidated (fully or partially.) 1730 * 1731 * @hide 1732 */ 1733 static final int PFLAG_DIRTY = 0x00200000; 1734 1735 /** 1736 * View flag indicating whether this view was invalidated by an opaque 1737 * invalidate request. 1738 * 1739 * @hide 1740 */ 1741 static final int PFLAG_DIRTY_OPAQUE = 0x00400000; 1742 1743 /** 1744 * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}. 1745 * 1746 * @hide 1747 */ 1748 static final int PFLAG_DIRTY_MASK = 0x00600000; 1749 1750 /** 1751 * Indicates whether the background is opaque. 1752 * 1753 * @hide 1754 */ 1755 static final int PFLAG_OPAQUE_BACKGROUND = 0x00800000; 1756 1757 /** 1758 * Indicates whether the scrollbars are opaque. 1759 * 1760 * @hide 1761 */ 1762 static final int PFLAG_OPAQUE_SCROLLBARS = 0x01000000; 1763 1764 /** 1765 * Indicates whether the view is opaque. 1766 * 1767 * @hide 1768 */ 1769 static final int PFLAG_OPAQUE_MASK = 0x01800000; 1770 1771 /** 1772 * Indicates a prepressed state; 1773 * the short time between ACTION_DOWN and recognizing 1774 * a 'real' press. Prepressed is used to recognize quick taps 1775 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1776 * 1777 * @hide 1778 */ 1779 private static final int PFLAG_PREPRESSED = 0x02000000; 1780 1781 /** 1782 * Indicates whether the view is temporarily detached. 1783 * 1784 * @hide 1785 */ 1786 static final int PFLAG_CANCEL_NEXT_UP_EVENT = 0x04000000; 1787 1788 /** 1789 * Indicates that we should awaken scroll bars once attached 1790 * 1791 * @hide 1792 */ 1793 private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1794 1795 /** 1796 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 1797 * @hide 1798 */ 1799 private static final int PFLAG_HOVERED = 0x10000000; 1800 1801 /** 1802 * no longer needed, should be reused 1803 */ 1804 private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000; 1805 1806 /** {@hide} */ 1807 static final int PFLAG_ACTIVATED = 0x40000000; 1808 1809 /** 1810 * Indicates that this view was specifically invalidated, not just dirtied because some 1811 * child view was invalidated. The flag is used to determine when we need to recreate 1812 * a view's display list (as opposed to just returning a reference to its existing 1813 * display list). 1814 * 1815 * @hide 1816 */ 1817 static final int PFLAG_INVALIDATED = 0x80000000; 1818 1819 /** 1820 * Masks for mPrivateFlags2, as generated by dumpFlags(): 1821 * 1822 * |-------|-------|-------|-------| 1823 * 1 PFLAG2_DRAG_CAN_ACCEPT 1824 * 1 PFLAG2_DRAG_HOVERED 1825 * 11 PFLAG2_LAYOUT_DIRECTION_MASK 1826 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL 1827 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED 1828 * 11 PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK 1829 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[1] 1830 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[2] 1831 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[3] 1832 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[4] 1833 * 1 1 PFLAG2_TEXT_DIRECTION_FLAGS[5] 1834 * 111 PFLAG2_TEXT_DIRECTION_MASK 1835 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED 1836 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT 1837 * 111 PFLAG2_TEXT_DIRECTION_RESOLVED_MASK 1838 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[1] 1839 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[2] 1840 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[3] 1841 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[4] 1842 * 1 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[5] 1843 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[6] 1844 * 111 PFLAG2_TEXT_ALIGNMENT_MASK 1845 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED 1846 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT 1847 * 111 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK 1848 * 111 PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK 1849 * 11 PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK 1850 * 1 PFLAG2_ACCESSIBILITY_FOCUSED 1851 * 1 PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED 1852 * 1 PFLAG2_VIEW_QUICK_REJECTED 1853 * 1 PFLAG2_PADDING_RESOLVED 1854 * 1 PFLAG2_DRAWABLE_RESOLVED 1855 * 1 PFLAG2_HAS_TRANSIENT_STATE 1856 * |-------|-------|-------|-------| 1857 */ 1858 1859 /** 1860 * Indicates that this view has reported that it can accept the current drag's content. 1861 * Cleared when the drag operation concludes. 1862 * @hide 1863 */ 1864 static final int PFLAG2_DRAG_CAN_ACCEPT = 0x00000001; 1865 1866 /** 1867 * Indicates that this view is currently directly under the drag location in a 1868 * drag-and-drop operation involving content that it can accept. Cleared when 1869 * the drag exits the view, or when the drag operation concludes. 1870 * @hide 1871 */ 1872 static final int PFLAG2_DRAG_HOVERED = 0x00000002; 1873 1874 /** @hide */ 1875 @IntDef({ 1876 LAYOUT_DIRECTION_LTR, 1877 LAYOUT_DIRECTION_RTL, 1878 LAYOUT_DIRECTION_INHERIT, 1879 LAYOUT_DIRECTION_LOCALE 1880 }) 1881 @Retention(RetentionPolicy.SOURCE) 1882 // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection 1883 public @interface LayoutDir {} 1884 1885 /** @hide */ 1886 @IntDef({ 1887 LAYOUT_DIRECTION_LTR, 1888 LAYOUT_DIRECTION_RTL 1889 }) 1890 @Retention(RetentionPolicy.SOURCE) 1891 public @interface ResolvedLayoutDir {} 1892 1893 /** 1894 * Horizontal layout direction of this view is from Left to Right. 1895 * Use with {@link #setLayoutDirection}. 1896 */ 1897 public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR; 1898 1899 /** 1900 * Horizontal layout direction of this view is from Right to Left. 1901 * Use with {@link #setLayoutDirection}. 1902 */ 1903 public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL; 1904 1905 /** 1906 * Horizontal layout direction of this view is inherited from its parent. 1907 * Use with {@link #setLayoutDirection}. 1908 */ 1909 public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT; 1910 1911 /** 1912 * Horizontal layout direction of this view is from deduced from the default language 1913 * script for the locale. Use with {@link #setLayoutDirection}. 1914 */ 1915 public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE; 1916 1917 /** 1918 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 1919 * @hide 1920 */ 1921 static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2; 1922 1923 /** 1924 * Mask for use with private flags indicating bits used for horizontal layout direction. 1925 * @hide 1926 */ 1927 static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1928 1929 /** 1930 * Indicates whether the view horizontal layout direction has been resolved and drawn to the 1931 * right-to-left direction. 1932 * @hide 1933 */ 1934 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1935 1936 /** 1937 * Indicates whether the view horizontal layout direction has been resolved. 1938 * @hide 1939 */ 1940 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1941 1942 /** 1943 * Mask for use with private flags indicating bits used for resolved horizontal layout direction. 1944 * @hide 1945 */ 1946 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C 1947 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1948 1949 /* 1950 * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct 1951 * flag value. 1952 * @hide 1953 */ 1954 private static final int[] LAYOUT_DIRECTION_FLAGS = { 1955 LAYOUT_DIRECTION_LTR, 1956 LAYOUT_DIRECTION_RTL, 1957 LAYOUT_DIRECTION_INHERIT, 1958 LAYOUT_DIRECTION_LOCALE 1959 }; 1960 1961 /** 1962 * Default horizontal layout direction. 1963 */ 1964 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 1965 1966 /** 1967 * Default horizontal layout direction. 1968 * @hide 1969 */ 1970 static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR; 1971 1972 /** 1973 * Text direction is inherited thru {@link ViewGroup} 1974 */ 1975 public static final int TEXT_DIRECTION_INHERIT = 0; 1976 1977 /** 1978 * Text direction is using "first strong algorithm". The first strong directional character 1979 * determines the paragraph direction. If there is no strong directional character, the 1980 * paragraph direction is the view's resolved layout direction. 1981 */ 1982 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 1983 1984 /** 1985 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 1986 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 1987 * If there are neither, the paragraph direction is the view's resolved layout direction. 1988 */ 1989 public static final int TEXT_DIRECTION_ANY_RTL = 2; 1990 1991 /** 1992 * Text direction is forced to LTR. 1993 */ 1994 public static final int TEXT_DIRECTION_LTR = 3; 1995 1996 /** 1997 * Text direction is forced to RTL. 1998 */ 1999 public static final int TEXT_DIRECTION_RTL = 4; 2000 2001 /** 2002 * Text direction is coming from the system Locale. 2003 */ 2004 public static final int TEXT_DIRECTION_LOCALE = 5; 2005 2006 /** 2007 * Default text direction is inherited 2008 */ 2009 private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT; 2010 2011 /** 2012 * Default resolved text direction 2013 * @hide 2014 */ 2015 static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG; 2016 2017 /** 2018 * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED) 2019 * @hide 2020 */ 2021 static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6; 2022 2023 /** 2024 * Mask for use with private flags indicating bits used for text direction. 2025 * @hide 2026 */ 2027 static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007 2028 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2029 2030 /** 2031 * Array of text direction flags for mapping attribute "textDirection" to correct 2032 * flag value. 2033 * @hide 2034 */ 2035 private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = { 2036 TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2037 TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2038 TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2039 TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2040 TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2041 TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT 2042 }; 2043 2044 /** 2045 * Indicates whether the view text direction has been resolved. 2046 * @hide 2047 */ 2048 static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008 2049 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2050 2051 /** 2052 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2053 * @hide 2054 */ 2055 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10; 2056 2057 /** 2058 * Mask for use with private flags indicating bits used for resolved text direction. 2059 * @hide 2060 */ 2061 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 2062 << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2063 2064 /** 2065 * Indicates whether the view text direction has been resolved to the "first strong" heuristic. 2066 * @hide 2067 */ 2068 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT = 2069 TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2070 2071 /** @hide */ 2072 @IntDef({ 2073 TEXT_ALIGNMENT_INHERIT, 2074 TEXT_ALIGNMENT_GRAVITY, 2075 TEXT_ALIGNMENT_CENTER, 2076 TEXT_ALIGNMENT_TEXT_START, 2077 TEXT_ALIGNMENT_TEXT_END, 2078 TEXT_ALIGNMENT_VIEW_START, 2079 TEXT_ALIGNMENT_VIEW_END 2080 }) 2081 @Retention(RetentionPolicy.SOURCE) 2082 public @interface TextAlignment {} 2083 2084 /** 2085 * Default text alignment. The text alignment of this View is inherited from its parent. 2086 * Use with {@link #setTextAlignment(int)} 2087 */ 2088 public static final int TEXT_ALIGNMENT_INHERIT = 0; 2089 2090 /** 2091 * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL, 2092 * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction. 2093 * 2094 * Use with {@link #setTextAlignment(int)} 2095 */ 2096 public static final int TEXT_ALIGNMENT_GRAVITY = 1; 2097 2098 /** 2099 * Align to the start of the paragraph, e.g. ALIGN_NORMAL. 2100 * 2101 * Use with {@link #setTextAlignment(int)} 2102 */ 2103 public static final int TEXT_ALIGNMENT_TEXT_START = 2; 2104 2105 /** 2106 * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE. 2107 * 2108 * Use with {@link #setTextAlignment(int)} 2109 */ 2110 public static final int TEXT_ALIGNMENT_TEXT_END = 3; 2111 2112 /** 2113 * Center the paragraph, e.g. ALIGN_CENTER. 2114 * 2115 * Use with {@link #setTextAlignment(int)} 2116 */ 2117 public static final int TEXT_ALIGNMENT_CENTER = 4; 2118 2119 /** 2120 * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved 2121 * layoutDirection is LTR, and ALIGN_RIGHT otherwise. 2122 * 2123 * Use with {@link #setTextAlignment(int)} 2124 */ 2125 public static final int TEXT_ALIGNMENT_VIEW_START = 5; 2126 2127 /** 2128 * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved 2129 * layoutDirection is LTR, and ALIGN_LEFT otherwise. 2130 * 2131 * Use with {@link #setTextAlignment(int)} 2132 */ 2133 public static final int TEXT_ALIGNMENT_VIEW_END = 6; 2134 2135 /** 2136 * Default text alignment is inherited 2137 */ 2138 private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2139 2140 /** 2141 * Default resolved text alignment 2142 * @hide 2143 */ 2144 static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2145 2146 /** 2147 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2148 * @hide 2149 */ 2150 static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13; 2151 2152 /** 2153 * Mask for use with private flags indicating bits used for text alignment. 2154 * @hide 2155 */ 2156 static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2157 2158 /** 2159 * Array of text direction flags for mapping attribute "textAlignment" to correct 2160 * flag value. 2161 * @hide 2162 */ 2163 private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = { 2164 TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2165 TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2166 TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2167 TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2168 TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2169 TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2170 TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT 2171 }; 2172 2173 /** 2174 * Indicates whether the view text alignment has been resolved. 2175 * @hide 2176 */ 2177 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2178 2179 /** 2180 * Bit shift to get the resolved text alignment. 2181 * @hide 2182 */ 2183 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17; 2184 2185 /** 2186 * Mask for use with private flags indicating bits used for text alignment. 2187 * @hide 2188 */ 2189 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 2190 << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2191 2192 /** 2193 * Indicates whether if the view text alignment has been resolved to gravity 2194 */ 2195 private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT = 2196 TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2197 2198 // Accessiblity constants for mPrivateFlags2 2199 2200 /** 2201 * Shift for the bits in {@link #mPrivateFlags2} related to the 2202 * "importantForAccessibility" attribute. 2203 */ 2204 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20; 2205 2206 /** 2207 * Automatically determine whether a view is important for accessibility. 2208 */ 2209 public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000; 2210 2211 /** 2212 * The view is important for accessibility. 2213 */ 2214 public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001; 2215 2216 /** 2217 * The view is not important for accessibility. 2218 */ 2219 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002; 2220 2221 /** 2222 * The view is not important for accessibility, nor are any of its 2223 * descendant views. 2224 */ 2225 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004; 2226 2227 /** 2228 * The default whether the view is important for accessibility. 2229 */ 2230 static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO; 2231 2232 /** 2233 * Mask for obtainig the bits which specify how to determine 2234 * whether a view is important for accessibility. 2235 */ 2236 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO 2237 | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO 2238 | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) 2239 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2240 2241 /** 2242 * Shift for the bits in {@link #mPrivateFlags2} related to the 2243 * "accessibilityLiveRegion" attribute. 2244 */ 2245 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23; 2246 2247 /** 2248 * Live region mode specifying that accessibility services should not 2249 * automatically announce changes to this view. This is the default live 2250 * region mode for most views. 2251 * <p> 2252 * Use with {@link #setAccessibilityLiveRegion(int)}. 2253 */ 2254 public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000; 2255 2256 /** 2257 * Live region mode specifying that accessibility services should announce 2258 * changes to this view. 2259 * <p> 2260 * Use with {@link #setAccessibilityLiveRegion(int)}. 2261 */ 2262 public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001; 2263 2264 /** 2265 * Live region mode specifying that accessibility services should interrupt 2266 * ongoing speech to immediately announce changes to this view. 2267 * <p> 2268 * Use with {@link #setAccessibilityLiveRegion(int)}. 2269 */ 2270 public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002; 2271 2272 /** 2273 * The default whether the view is important for accessibility. 2274 */ 2275 static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE; 2276 2277 /** 2278 * Mask for obtaining the bits which specify a view's accessibility live 2279 * region mode. 2280 */ 2281 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE 2282 | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE) 2283 << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 2284 2285 /** 2286 * Flag indicating whether a view has accessibility focus. 2287 */ 2288 static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000; 2289 2290 /** 2291 * Flag whether the accessibility state of the subtree rooted at this view changed. 2292 */ 2293 static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000; 2294 2295 /** 2296 * Flag indicating whether a view failed the quickReject() check in draw(). This condition 2297 * is used to check whether later changes to the view's transform should invalidate the 2298 * view to force the quickReject test to run again. 2299 */ 2300 static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000; 2301 2302 /** 2303 * Flag indicating that start/end padding has been resolved into left/right padding 2304 * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()} 2305 * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved 2306 * during measurement. In some special cases this is required such as when an adapter-based 2307 * view measures prospective children without attaching them to a window. 2308 */ 2309 static final int PFLAG2_PADDING_RESOLVED = 0x20000000; 2310 2311 /** 2312 * Flag indicating that the start/end drawables has been resolved into left/right ones. 2313 */ 2314 static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000; 2315 2316 /** 2317 * Indicates that the view is tracking some sort of transient state 2318 * that the app should not need to be aware of, but that the framework 2319 * should take special care to preserve. 2320 */ 2321 static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000; 2322 2323 /** 2324 * Group of bits indicating that RTL properties resolution is done. 2325 */ 2326 static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED | 2327 PFLAG2_TEXT_DIRECTION_RESOLVED | 2328 PFLAG2_TEXT_ALIGNMENT_RESOLVED | 2329 PFLAG2_PADDING_RESOLVED | 2330 PFLAG2_DRAWABLE_RESOLVED; 2331 2332 // There are a couple of flags left in mPrivateFlags2 2333 2334 /* End of masks for mPrivateFlags2 */ 2335 2336 /** 2337 * Masks for mPrivateFlags3, as generated by dumpFlags(): 2338 * 2339 * |-------|-------|-------|-------| 2340 * 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM 2341 * 1 PFLAG3_VIEW_IS_ANIMATING_ALPHA 2342 * 1 PFLAG3_IS_LAID_OUT 2343 * 1 PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT 2344 * 1 PFLAG3_CALLED_SUPER 2345 * |-------|-------|-------|-------| 2346 */ 2347 2348 /** 2349 * Flag indicating that view has a transform animation set on it. This is used to track whether 2350 * an animation is cleared between successive frames, in order to tell the associated 2351 * DisplayList to clear its animation matrix. 2352 */ 2353 static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1; 2354 2355 /** 2356 * Flag indicating that view has an alpha animation set on it. This is used to track whether an 2357 * animation is cleared between successive frames, in order to tell the associated 2358 * DisplayList to restore its alpha value. 2359 */ 2360 static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2; 2361 2362 /** 2363 * Flag indicating that the view has been through at least one layout since it 2364 * was last attached to a window. 2365 */ 2366 static final int PFLAG3_IS_LAID_OUT = 0x4; 2367 2368 /** 2369 * Flag indicating that a call to measure() was skipped and should be done 2370 * instead when layout() is invoked. 2371 */ 2372 static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8; 2373 2374 /** 2375 * Flag indicating that an overridden method correctly called down to 2376 * the superclass implementation as required by the API spec. 2377 */ 2378 static final int PFLAG3_CALLED_SUPER = 0x10; 2379 2380 /** 2381 * Flag indicating that a view's outline has been specifically defined. 2382 */ 2383 static final int PFLAG3_OUTLINE_DEFINED = 0x20; 2384 2385 /** 2386 * Flag indicating that we're in the process of applying window insets. 2387 */ 2388 static final int PFLAG3_APPLYING_INSETS = 0x40; 2389 2390 /** 2391 * Flag indicating that we're in the process of fitting system windows using the old method. 2392 */ 2393 static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x80; 2394 2395 /** 2396 * Flag indicating that nested scrolling is enabled for this view. 2397 * The view will optionally cooperate with views up its parent chain to allow for 2398 * integrated nested scrolling along the same axis. 2399 */ 2400 static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x200; 2401 2402 /* End of masks for mPrivateFlags3 */ 2403 2404 static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED; 2405 2406 /** 2407 * Always allow a user to over-scroll this view, provided it is a 2408 * view that can scroll. 2409 * 2410 * @see #getOverScrollMode() 2411 * @see #setOverScrollMode(int) 2412 */ 2413 public static final int OVER_SCROLL_ALWAYS = 0; 2414 2415 /** 2416 * Allow a user to over-scroll this view only if the content is large 2417 * enough to meaningfully scroll, provided it is a view that can scroll. 2418 * 2419 * @see #getOverScrollMode() 2420 * @see #setOverScrollMode(int) 2421 */ 2422 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 2423 2424 /** 2425 * Never allow a user to over-scroll this view. 2426 * 2427 * @see #getOverScrollMode() 2428 * @see #setOverScrollMode(int) 2429 */ 2430 public static final int OVER_SCROLL_NEVER = 2; 2431 2432 /** 2433 * Special constant for {@link #setSystemUiVisibility(int)}: View has 2434 * requested the system UI (status bar) to be visible (the default). 2435 * 2436 * @see #setSystemUiVisibility(int) 2437 */ 2438 public static final int SYSTEM_UI_FLAG_VISIBLE = 0; 2439 2440 /** 2441 * Flag for {@link #setSystemUiVisibility(int)}: View has requested the 2442 * system UI to enter an unobtrusive "low profile" mode. 2443 * 2444 * <p>This is for use in games, book readers, video players, or any other 2445 * "immersive" application where the usual system chrome is deemed too distracting. 2446 * 2447 * <p>In low profile mode, the status bar and/or navigation icons may dim. 2448 * 2449 * @see #setSystemUiVisibility(int) 2450 */ 2451 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001; 2452 2453 /** 2454 * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the 2455 * system navigation be temporarily hidden. 2456 * 2457 * <p>This is an even less obtrusive state than that called for by 2458 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls 2459 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause 2460 * those to disappear. This is useful (in conjunction with the 2461 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and 2462 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN} 2463 * window flags) for displaying content using every last pixel on the display. 2464 * 2465 * <p>There is a limitation: because navigation controls are so important, the least user 2466 * interaction will cause them to reappear immediately. When this happens, both 2467 * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically, 2468 * so that both elements reappear at the same time. 2469 * 2470 * @see #setSystemUiVisibility(int) 2471 */ 2472 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002; 2473 2474 /** 2475 * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go 2476 * into the normal fullscreen mode so that its content can take over the screen 2477 * while still allowing the user to interact with the application. 2478 * 2479 * <p>This has the same visual effect as 2480 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN 2481 * WindowManager.LayoutParams.FLAG_FULLSCREEN}, 2482 * meaning that non-critical screen decorations (such as the status bar) will be 2483 * hidden while the user is in the View's window, focusing the experience on 2484 * that content. Unlike the window flag, if you are using ActionBar in 2485 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2486 * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also 2487 * hide the action bar. 2488 * 2489 * <p>This approach to going fullscreen is best used over the window flag when 2490 * it is a transient state -- that is, the application does this at certain 2491 * points in its user interaction where it wants to allow the user to focus 2492 * on content, but not as a continuous state. For situations where the application 2493 * would like to simply stay full screen the entire time (such as a game that 2494 * wants to take over the screen), the 2495 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag} 2496 * is usually a better approach. The state set here will be removed by the system 2497 * in various situations (such as the user moving to another application) like 2498 * the other system UI states. 2499 * 2500 * <p>When using this flag, the application should provide some easy facility 2501 * for the user to go out of it. A common example would be in an e-book 2502 * reader, where tapping on the screen brings back whatever screen and UI 2503 * decorations that had been hidden while the user was immersed in reading 2504 * the book. 2505 * 2506 * @see #setSystemUiVisibility(int) 2507 */ 2508 public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004; 2509 2510 /** 2511 * Flag for {@link #setSystemUiVisibility(int)}: When using other layout 2512 * flags, we would like a stable view of the content insets given to 2513 * {@link #fitSystemWindows(Rect)}. This means that the insets seen there 2514 * will always represent the worst case that the application can expect 2515 * as a continuous state. In the stock Android UI this is the space for 2516 * the system bar, nav bar, and status bar, but not more transient elements 2517 * such as an input method. 2518 * 2519 * The stable layout your UI sees is based on the system UI modes you can 2520 * switch to. That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 2521 * then you will get a stable layout for changes of the 2522 * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify 2523 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and 2524 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition 2525 * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} 2526 * with a stable layout. (Note that you should avoid using 2527 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.) 2528 * 2529 * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN} 2530 * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}), 2531 * then a hidden status bar will be considered a "stable" state for purposes 2532 * here. This allows your UI to continually hide the status bar, while still 2533 * using the system UI flags to hide the action bar while still retaining 2534 * a stable layout. Note that changing the window fullscreen flag will never 2535 * provide a stable layout for a clean transition. 2536 * 2537 * <p>If you are using ActionBar in 2538 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2539 * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the 2540 * insets it adds to those given to the application. 2541 */ 2542 public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100; 2543 2544 /** 2545 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2546 * to be layed out as if it has requested 2547 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't. This 2548 * allows it to avoid artifacts when switching in and out of that mode, at 2549 * the expense that some of its user interface may be covered by screen 2550 * decorations when they are shown. You can perform layout of your inner 2551 * UI elements to account for the navigation system UI through the 2552 * {@link #fitSystemWindows(Rect)} method. 2553 */ 2554 public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200; 2555 2556 /** 2557 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2558 * to be layed out as if it has requested 2559 * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't. This 2560 * allows it to avoid artifacts when switching in and out of that mode, at 2561 * the expense that some of its user interface may be covered by screen 2562 * decorations when they are shown. You can perform layout of your inner 2563 * UI elements to account for non-fullscreen system UI through the 2564 * {@link #fitSystemWindows(Rect)} method. 2565 */ 2566 public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400; 2567 2568 /** 2569 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2570 * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. If this flag is 2571 * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any 2572 * user interaction. 2573 * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only 2574 * has an effect when used in combination with that flag.</p> 2575 */ 2576 public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800; 2577 2578 /** 2579 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2580 * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation 2581 * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. Use this flag to create an immersive 2582 * experience while also hiding the system bars. If this flag is not set, 2583 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user 2584 * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system 2585 * if the user swipes from the top of the screen. 2586 * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with 2587 * system gestures, such as swiping from the top of the screen. These transient system bars 2588 * will overlay app’s content, may have some degree of transparency, and will automatically 2589 * hide after a short timeout. 2590 * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and 2591 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination 2592 * with one or both of those flags.</p> 2593 */ 2594 public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000; 2595 2596 /** 2597 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead. 2598 */ 2599 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE; 2600 2601 /** 2602 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead. 2603 */ 2604 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE; 2605 2606 /** 2607 * @hide 2608 * 2609 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2610 * out of the public fields to keep the undefined bits out of the developer's way. 2611 * 2612 * Flag to make the status bar not expandable. Unless you also 2613 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 2614 */ 2615 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 2616 2617 /** 2618 * @hide 2619 * 2620 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2621 * out of the public fields to keep the undefined bits out of the developer's way. 2622 * 2623 * Flag to hide notification icons and scrolling ticker text. 2624 */ 2625 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 2626 2627 /** 2628 * @hide 2629 * 2630 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2631 * out of the public fields to keep the undefined bits out of the developer's way. 2632 * 2633 * Flag to disable incoming notification alerts. This will not block 2634 * icons, but it will block sound, vibrating and other visual or aural notifications. 2635 */ 2636 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 2637 2638 /** 2639 * @hide 2640 * 2641 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2642 * out of the public fields to keep the undefined bits out of the developer's way. 2643 * 2644 * Flag to hide only the scrolling ticker. Note that 2645 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 2646 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 2647 */ 2648 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 2649 2650 /** 2651 * @hide 2652 * 2653 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2654 * out of the public fields to keep the undefined bits out of the developer's way. 2655 * 2656 * Flag to hide the center system info area. 2657 */ 2658 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 2659 2660 /** 2661 * @hide 2662 * 2663 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2664 * out of the public fields to keep the undefined bits out of the developer's way. 2665 * 2666 * Flag to hide only the home button. Don't use this 2667 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2668 */ 2669 public static final int STATUS_BAR_DISABLE_HOME = 0x00200000; 2670 2671 /** 2672 * @hide 2673 * 2674 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2675 * out of the public fields to keep the undefined bits out of the developer's way. 2676 * 2677 * Flag to hide only the back button. Don't use this 2678 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2679 */ 2680 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 2681 2682 /** 2683 * @hide 2684 * 2685 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2686 * out of the public fields to keep the undefined bits out of the developer's way. 2687 * 2688 * Flag to hide only the clock. You might use this if your activity has 2689 * its own clock making the status bar's clock redundant. 2690 */ 2691 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 2692 2693 /** 2694 * @hide 2695 * 2696 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2697 * out of the public fields to keep the undefined bits out of the developer's way. 2698 * 2699 * Flag to hide only the recent apps button. Don't use this 2700 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2701 */ 2702 public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000; 2703 2704 /** 2705 * @hide 2706 * 2707 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2708 * out of the public fields to keep the undefined bits out of the developer's way. 2709 * 2710 * Flag to disable the global search gesture. Don't use this 2711 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2712 */ 2713 public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000; 2714 2715 /** 2716 * @hide 2717 * 2718 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2719 * out of the public fields to keep the undefined bits out of the developer's way. 2720 * 2721 * Flag to specify that the status bar is displayed in transient mode. 2722 */ 2723 public static final int STATUS_BAR_TRANSIENT = 0x04000000; 2724 2725 /** 2726 * @hide 2727 * 2728 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2729 * out of the public fields to keep the undefined bits out of the developer's way. 2730 * 2731 * Flag to specify that the navigation bar is displayed in transient mode. 2732 */ 2733 public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000; 2734 2735 /** 2736 * @hide 2737 * 2738 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2739 * out of the public fields to keep the undefined bits out of the developer's way. 2740 * 2741 * Flag to specify that the hidden status bar would like to be shown. 2742 */ 2743 public static final int STATUS_BAR_UNHIDE = 0x10000000; 2744 2745 /** 2746 * @hide 2747 * 2748 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2749 * out of the public fields to keep the undefined bits out of the developer's way. 2750 * 2751 * Flag to specify that the hidden navigation bar would like to be shown. 2752 */ 2753 public static final int NAVIGATION_BAR_UNHIDE = 0x20000000; 2754 2755 /** 2756 * @hide 2757 * 2758 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2759 * out of the public fields to keep the undefined bits out of the developer's way. 2760 * 2761 * Flag to specify that the status bar is displayed in translucent mode. 2762 */ 2763 public static final int STATUS_BAR_TRANSLUCENT = 0x40000000; 2764 2765 /** 2766 * @hide 2767 * 2768 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2769 * out of the public fields to keep the undefined bits out of the developer's way. 2770 * 2771 * Flag to specify that the navigation bar is displayed in translucent mode. 2772 */ 2773 public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000; 2774 2775 /** 2776 * @hide 2777 * 2778 * Makes system ui transparent. 2779 */ 2780 public static final int SYSTEM_UI_TRANSPARENT = 0x00008000; 2781 2782 /** 2783 * @hide 2784 */ 2785 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00007FFF; 2786 2787 /** 2788 * These are the system UI flags that can be cleared by events outside 2789 * of an application. Currently this is just the ability to tap on the 2790 * screen while hiding the navigation bar to have it return. 2791 * @hide 2792 */ 2793 public static final int SYSTEM_UI_CLEARABLE_FLAGS = 2794 SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION 2795 | SYSTEM_UI_FLAG_FULLSCREEN; 2796 2797 /** 2798 * Flags that can impact the layout in relation to system UI. 2799 */ 2800 public static final int SYSTEM_UI_LAYOUT_FLAGS = 2801 SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 2802 | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; 2803 2804 /** @hide */ 2805 @IntDef(flag = true, 2806 value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION }) 2807 @Retention(RetentionPolicy.SOURCE) 2808 public @interface FindViewFlags {} 2809 2810 /** 2811 * Find views that render the specified text. 2812 * 2813 * @see #findViewsWithText(ArrayList, CharSequence, int) 2814 */ 2815 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001; 2816 2817 /** 2818 * Find find views that contain the specified content description. 2819 * 2820 * @see #findViewsWithText(ArrayList, CharSequence, int) 2821 */ 2822 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002; 2823 2824 /** 2825 * Find views that contain {@link AccessibilityNodeProvider}. Such 2826 * a View is a root of virtual view hierarchy and may contain the searched 2827 * text. If this flag is set Views with providers are automatically 2828 * added and it is a responsibility of the client to call the APIs of 2829 * the provider to determine whether the virtual tree rooted at this View 2830 * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s 2831 * representing the virtual views with this text. 2832 * 2833 * @see #findViewsWithText(ArrayList, CharSequence, int) 2834 * 2835 * @hide 2836 */ 2837 public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004; 2838 2839 /** 2840 * The undefined cursor position. 2841 * 2842 * @hide 2843 */ 2844 public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1; 2845 2846 /** 2847 * Indicates that the screen has changed state and is now off. 2848 * 2849 * @see #onScreenStateChanged(int) 2850 */ 2851 public static final int SCREEN_STATE_OFF = 0x0; 2852 2853 /** 2854 * Indicates that the screen has changed state and is now on. 2855 * 2856 * @see #onScreenStateChanged(int) 2857 */ 2858 public static final int SCREEN_STATE_ON = 0x1; 2859 2860 /** 2861 * Indicates no axis of view scrolling. 2862 */ 2863 public static final int SCROLL_AXIS_NONE = 0; 2864 2865 /** 2866 * Indicates scrolling along the horizontal axis. 2867 */ 2868 public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0; 2869 2870 /** 2871 * Indicates scrolling along the vertical axis. 2872 */ 2873 public static final int SCROLL_AXIS_VERTICAL = 1 << 1; 2874 2875 /** 2876 * Controls the over-scroll mode for this view. 2877 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 2878 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 2879 * and {@link #OVER_SCROLL_NEVER}. 2880 */ 2881 private int mOverScrollMode; 2882 2883 /** 2884 * The parent this view is attached to. 2885 * {@hide} 2886 * 2887 * @see #getParent() 2888 */ 2889 protected ViewParent mParent; 2890 2891 /** 2892 * {@hide} 2893 */ 2894 AttachInfo mAttachInfo; 2895 2896 /** 2897 * {@hide} 2898 */ 2899 @ViewDebug.ExportedProperty(flagMapping = { 2900 @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT, 2901 name = "FORCE_LAYOUT"), 2902 @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED, 2903 name = "LAYOUT_REQUIRED"), 2904 @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID, 2905 name = "DRAWING_CACHE_INVALID", outputIf = false), 2906 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true), 2907 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false), 2908 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 2909 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY") 2910 }) 2911 int mPrivateFlags; 2912 int mPrivateFlags2; 2913 int mPrivateFlags3; 2914 2915 /** 2916 * This view's request for the visibility of the status bar. 2917 * @hide 2918 */ 2919 @ViewDebug.ExportedProperty(flagMapping = { 2920 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 2921 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 2922 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 2923 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2924 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2925 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 2926 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 2927 equals = SYSTEM_UI_FLAG_VISIBLE, 2928 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 2929 }) 2930 int mSystemUiVisibility; 2931 2932 /** 2933 * Reference count for transient state. 2934 * @see #setHasTransientState(boolean) 2935 */ 2936 int mTransientStateCount = 0; 2937 2938 /** 2939 * Count of how many windows this view has been attached to. 2940 */ 2941 int mWindowAttachCount; 2942 2943 /** 2944 * The layout parameters associated with this view and used by the parent 2945 * {@link android.view.ViewGroup} to determine how this view should be 2946 * laid out. 2947 * {@hide} 2948 */ 2949 protected ViewGroup.LayoutParams mLayoutParams; 2950 2951 /** 2952 * The view flags hold various views states. 2953 * {@hide} 2954 */ 2955 @ViewDebug.ExportedProperty 2956 int mViewFlags; 2957 2958 static class TransformationInfo { 2959 /** 2960 * The transform matrix for the View. This transform is calculated internally 2961 * based on the translation, rotation, and scale properties. 2962 * 2963 * Do *not* use this variable directly; instead call getMatrix(), which will 2964 * load the value from the View's RenderNode. 2965 */ 2966 private final Matrix mMatrix = new Matrix(); 2967 2968 /** 2969 * The inverse transform matrix for the View. This transform is calculated 2970 * internally based on the translation, rotation, and scale properties. 2971 * 2972 * Do *not* use this variable directly; instead call getInverseMatrix(), 2973 * which will load the value from the View's RenderNode. 2974 */ 2975 private Matrix mInverseMatrix; 2976 2977 /** 2978 * The opacity of the View. This is a value from 0 to 1, where 0 means 2979 * completely transparent and 1 means completely opaque. 2980 */ 2981 @ViewDebug.ExportedProperty 2982 float mAlpha = 1f; 2983 2984 /** 2985 * The opacity of the view as manipulated by the Fade transition. This is a hidden 2986 * property only used by transitions, which is composited with the other alpha 2987 * values to calculate the final visual alpha value. 2988 */ 2989 float mTransitionAlpha = 1f; 2990 } 2991 2992 TransformationInfo mTransformationInfo; 2993 2994 /** 2995 * Current clip bounds. to which all drawing of this view are constrained. 2996 */ 2997 Rect mClipBounds = null; 2998 2999 private boolean mLastIsOpaque; 3000 3001 /** 3002 * The distance in pixels from the left edge of this view's parent 3003 * to the left edge of this view. 3004 * {@hide} 3005 */ 3006 @ViewDebug.ExportedProperty(category = "layout") 3007 protected int mLeft; 3008 /** 3009 * The distance in pixels from the left edge of this view's parent 3010 * to the right edge of this view. 3011 * {@hide} 3012 */ 3013 @ViewDebug.ExportedProperty(category = "layout") 3014 protected int mRight; 3015 /** 3016 * The distance in pixels from the top edge of this view's parent 3017 * to the top edge of this view. 3018 * {@hide} 3019 */ 3020 @ViewDebug.ExportedProperty(category = "layout") 3021 protected int mTop; 3022 /** 3023 * The distance in pixels from the top edge of this view's parent 3024 * to the bottom edge of this view. 3025 * {@hide} 3026 */ 3027 @ViewDebug.ExportedProperty(category = "layout") 3028 protected int mBottom; 3029 3030 /** 3031 * The offset, in pixels, by which the content of this view is scrolled 3032 * horizontally. 3033 * {@hide} 3034 */ 3035 @ViewDebug.ExportedProperty(category = "scrolling") 3036 protected int mScrollX; 3037 /** 3038 * The offset, in pixels, by which the content of this view is scrolled 3039 * vertically. 3040 * {@hide} 3041 */ 3042 @ViewDebug.ExportedProperty(category = "scrolling") 3043 protected int mScrollY; 3044 3045 /** 3046 * The left padding in pixels, that is the distance in pixels between the 3047 * left edge of this view and the left edge of its content. 3048 * {@hide} 3049 */ 3050 @ViewDebug.ExportedProperty(category = "padding") 3051 protected int mPaddingLeft = 0; 3052 /** 3053 * The right padding in pixels, that is the distance in pixels between the 3054 * right edge of this view and the right edge of its content. 3055 * {@hide} 3056 */ 3057 @ViewDebug.ExportedProperty(category = "padding") 3058 protected int mPaddingRight = 0; 3059 /** 3060 * The top padding in pixels, that is the distance in pixels between the 3061 * top edge of this view and the top edge of its content. 3062 * {@hide} 3063 */ 3064 @ViewDebug.ExportedProperty(category = "padding") 3065 protected int mPaddingTop; 3066 /** 3067 * The bottom padding in pixels, that is the distance in pixels between the 3068 * bottom edge of this view and the bottom edge of its content. 3069 * {@hide} 3070 */ 3071 @ViewDebug.ExportedProperty(category = "padding") 3072 protected int mPaddingBottom; 3073 3074 /** 3075 * The layout insets in pixels, that is the distance in pixels between the 3076 * visible edges of this view its bounds. 3077 */ 3078 private Insets mLayoutInsets; 3079 3080 /** 3081 * Briefly describes the view and is primarily used for accessibility support. 3082 */ 3083 private CharSequence mContentDescription; 3084 3085 /** 3086 * Specifies the id of a view for which this view serves as a label for 3087 * accessibility purposes. 3088 */ 3089 private int mLabelForId = View.NO_ID; 3090 3091 /** 3092 * Predicate for matching labeled view id with its label for 3093 * accessibility purposes. 3094 */ 3095 private MatchLabelForPredicate mMatchLabelForPredicate; 3096 3097 /** 3098 * Predicate for matching a view by its id. 3099 */ 3100 private MatchIdPredicate mMatchIdPredicate; 3101 3102 /** 3103 * Cache the paddingRight set by the user to append to the scrollbar's size. 3104 * 3105 * @hide 3106 */ 3107 @ViewDebug.ExportedProperty(category = "padding") 3108 protected int mUserPaddingRight; 3109 3110 /** 3111 * Cache the paddingBottom set by the user to append to the scrollbar's size. 3112 * 3113 * @hide 3114 */ 3115 @ViewDebug.ExportedProperty(category = "padding") 3116 protected int mUserPaddingBottom; 3117 3118 /** 3119 * Cache the paddingLeft set by the user to append to the scrollbar's size. 3120 * 3121 * @hide 3122 */ 3123 @ViewDebug.ExportedProperty(category = "padding") 3124 protected int mUserPaddingLeft; 3125 3126 /** 3127 * Cache the paddingStart set by the user to append to the scrollbar's size. 3128 * 3129 */ 3130 @ViewDebug.ExportedProperty(category = "padding") 3131 int mUserPaddingStart; 3132 3133 /** 3134 * Cache the paddingEnd set by the user to append to the scrollbar's size. 3135 * 3136 */ 3137 @ViewDebug.ExportedProperty(category = "padding") 3138 int mUserPaddingEnd; 3139 3140 /** 3141 * Cache initial left padding. 3142 * 3143 * @hide 3144 */ 3145 int mUserPaddingLeftInitial; 3146 3147 /** 3148 * Cache initial right padding. 3149 * 3150 * @hide 3151 */ 3152 int mUserPaddingRightInitial; 3153 3154 /** 3155 * Default undefined padding 3156 */ 3157 private static final int UNDEFINED_PADDING = Integer.MIN_VALUE; 3158 3159 /** 3160 * Cache if a left padding has been defined 3161 */ 3162 private boolean mLeftPaddingDefined = false; 3163 3164 /** 3165 * Cache if a right padding has been defined 3166 */ 3167 private boolean mRightPaddingDefined = false; 3168 3169 /** 3170 * @hide 3171 */ 3172 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 3173 /** 3174 * @hide 3175 */ 3176 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 3177 3178 private LongSparseLongArray mMeasureCache; 3179 3180 @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_") 3181 private Drawable mBackground; 3182 3183 /** 3184 * Display list used for backgrounds. 3185 * <p> 3186 * When non-null and valid, this is expected to contain an up-to-date copy 3187 * of the background drawable. It is cleared on temporary detach and reset 3188 * on cleanup. 3189 */ 3190 private RenderNode mBackgroundDisplayList; 3191 3192 private int mBackgroundResource; 3193 private boolean mBackgroundSizeChanged; 3194 3195 private String mViewName; 3196 3197 static class ListenerInfo { 3198 /** 3199 * Listener used to dispatch focus change events. 3200 * This field should be made private, so it is hidden from the SDK. 3201 * {@hide} 3202 */ 3203 protected OnFocusChangeListener mOnFocusChangeListener; 3204 3205 /** 3206 * Listeners for layout change events. 3207 */ 3208 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 3209 3210 /** 3211 * Listeners for attach events. 3212 */ 3213 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 3214 3215 /** 3216 * Listener used to dispatch click events. 3217 * This field should be made private, so it is hidden from the SDK. 3218 * {@hide} 3219 */ 3220 public OnClickListener mOnClickListener; 3221 3222 /** 3223 * Listener used to dispatch long click events. 3224 * This field should be made private, so it is hidden from the SDK. 3225 * {@hide} 3226 */ 3227 protected OnLongClickListener mOnLongClickListener; 3228 3229 /** 3230 * Listener used to build the context menu. 3231 * This field should be made private, so it is hidden from the SDK. 3232 * {@hide} 3233 */ 3234 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 3235 3236 private OnKeyListener mOnKeyListener; 3237 3238 private OnTouchListener mOnTouchListener; 3239 3240 private OnHoverListener mOnHoverListener; 3241 3242 private OnGenericMotionListener mOnGenericMotionListener; 3243 3244 private OnDragListener mOnDragListener; 3245 3246 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 3247 3248 OnApplyWindowInsetsListener mOnApplyWindowInsetsListener; 3249 } 3250 3251 ListenerInfo mListenerInfo; 3252 3253 /** 3254 * The application environment this view lives in. 3255 * This field should be made private, so it is hidden from the SDK. 3256 * {@hide} 3257 */ 3258 protected Context mContext; 3259 3260 private final Resources mResources; 3261 3262 private ScrollabilityCache mScrollCache; 3263 3264 private int[] mDrawableState = null; 3265 3266 /** 3267 * Stores the outline of the view, passed down to the DisplayList level for 3268 * defining shadow shape. 3269 */ 3270 private Outline mOutline; 3271 3272 /** 3273 * Animator that automatically runs based on state changes. 3274 */ 3275 private StateListAnimator mStateListAnimator; 3276 3277 /** 3278 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 3279 * the user may specify which view to go to next. 3280 */ 3281 private int mNextFocusLeftId = View.NO_ID; 3282 3283 /** 3284 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 3285 * the user may specify which view to go to next. 3286 */ 3287 private int mNextFocusRightId = View.NO_ID; 3288 3289 /** 3290 * When this view has focus and the next focus is {@link #FOCUS_UP}, 3291 * the user may specify which view to go to next. 3292 */ 3293 private int mNextFocusUpId = View.NO_ID; 3294 3295 /** 3296 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 3297 * the user may specify which view to go to next. 3298 */ 3299 private int mNextFocusDownId = View.NO_ID; 3300 3301 /** 3302 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 3303 * the user may specify which view to go to next. 3304 */ 3305 int mNextFocusForwardId = View.NO_ID; 3306 3307 private CheckForLongPress mPendingCheckForLongPress; 3308 private CheckForTap mPendingCheckForTap = null; 3309 private PerformClick mPerformClick; 3310 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 3311 3312 private UnsetPressedState mUnsetPressedState; 3313 3314 /** 3315 * Whether the long press's action has been invoked. The tap's action is invoked on the 3316 * up event while a long press is invoked as soon as the long press duration is reached, so 3317 * a long press could be performed before the tap is checked, in which case the tap's action 3318 * should not be invoked. 3319 */ 3320 private boolean mHasPerformedLongPress; 3321 3322 /** 3323 * The minimum height of the view. We'll try our best to have the height 3324 * of this view to at least this amount. 3325 */ 3326 @ViewDebug.ExportedProperty(category = "measurement") 3327 private int mMinHeight; 3328 3329 /** 3330 * The minimum width of the view. We'll try our best to have the width 3331 * of this view to at least this amount. 3332 */ 3333 @ViewDebug.ExportedProperty(category = "measurement") 3334 private int mMinWidth; 3335 3336 /** 3337 * The delegate to handle touch events that are physically in this view 3338 * but should be handled by another view. 3339 */ 3340 private TouchDelegate mTouchDelegate = null; 3341 3342 /** 3343 * Solid color to use as a background when creating the drawing cache. Enables 3344 * the cache to use 16 bit bitmaps instead of 32 bit. 3345 */ 3346 private int mDrawingCacheBackgroundColor = 0; 3347 3348 /** 3349 * Special tree observer used when mAttachInfo is null. 3350 */ 3351 private ViewTreeObserver mFloatingTreeObserver; 3352 3353 /** 3354 * Cache the touch slop from the context that created the view. 3355 */ 3356 private int mTouchSlop; 3357 3358 /** 3359 * Object that handles automatic animation of view properties. 3360 */ 3361 private ViewPropertyAnimator mAnimator = null; 3362 3363 /** 3364 * Flag indicating that a drag can cross window boundaries. When 3365 * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called 3366 * with this flag set, all visible applications will be able to participate 3367 * in the drag operation and receive the dragged content. 3368 * 3369 * @hide 3370 */ 3371 public static final int DRAG_FLAG_GLOBAL = 1; 3372 3373 /** 3374 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 3375 */ 3376 private float mVerticalScrollFactor; 3377 3378 /** 3379 * Position of the vertical scroll bar. 3380 */ 3381 private int mVerticalScrollbarPosition; 3382 3383 /** 3384 * Position the scroll bar at the default position as determined by the system. 3385 */ 3386 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 3387 3388 /** 3389 * Position the scroll bar along the left edge. 3390 */ 3391 public static final int SCROLLBAR_POSITION_LEFT = 1; 3392 3393 /** 3394 * Position the scroll bar along the right edge. 3395 */ 3396 public static final int SCROLLBAR_POSITION_RIGHT = 2; 3397 3398 /** 3399 * Indicates that the view does not have a layer. 3400 * 3401 * @see #getLayerType() 3402 * @see #setLayerType(int, android.graphics.Paint) 3403 * @see #LAYER_TYPE_SOFTWARE 3404 * @see #LAYER_TYPE_HARDWARE 3405 */ 3406 public static final int LAYER_TYPE_NONE = 0; 3407 3408 /** 3409 * <p>Indicates that the view has a software layer. A software layer is backed 3410 * by a bitmap and causes the view to be rendered using Android's software 3411 * rendering pipeline, even if hardware acceleration is enabled.</p> 3412 * 3413 * <p>Software layers have various usages:</p> 3414 * <p>When the application is not using hardware acceleration, a software layer 3415 * is useful to apply a specific color filter and/or blending mode and/or 3416 * translucency to a view and all its children.</p> 3417 * <p>When the application is using hardware acceleration, a software layer 3418 * is useful to render drawing primitives not supported by the hardware 3419 * accelerated pipeline. It can also be used to cache a complex view tree 3420 * into a texture and reduce the complexity of drawing operations. For instance, 3421 * when animating a complex view tree with a translation, a software layer can 3422 * be used to render the view tree only once.</p> 3423 * <p>Software layers should be avoided when the affected view tree updates 3424 * often. Every update will require to re-render the software layer, which can 3425 * potentially be slow (particularly when hardware acceleration is turned on 3426 * since the layer will have to be uploaded into a hardware texture after every 3427 * update.)</p> 3428 * 3429 * @see #getLayerType() 3430 * @see #setLayerType(int, android.graphics.Paint) 3431 * @see #LAYER_TYPE_NONE 3432 * @see #LAYER_TYPE_HARDWARE 3433 */ 3434 public static final int LAYER_TYPE_SOFTWARE = 1; 3435 3436 /** 3437 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 3438 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 3439 * OpenGL hardware) and causes the view to be rendered using Android's hardware 3440 * rendering pipeline, but only if hardware acceleration is turned on for the 3441 * view hierarchy. When hardware acceleration is turned off, hardware layers 3442 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 3443 * 3444 * <p>A hardware layer is useful to apply a specific color filter and/or 3445 * blending mode and/or translucency to a view and all its children.</p> 3446 * <p>A hardware layer can be used to cache a complex view tree into a 3447 * texture and reduce the complexity of drawing operations. For instance, 3448 * when animating a complex view tree with a translation, a hardware layer can 3449 * be used to render the view tree only once.</p> 3450 * <p>A hardware layer can also be used to increase the rendering quality when 3451 * rotation transformations are applied on a view. It can also be used to 3452 * prevent potential clipping issues when applying 3D transforms on a view.</p> 3453 * 3454 * @see #getLayerType() 3455 * @see #setLayerType(int, android.graphics.Paint) 3456 * @see #LAYER_TYPE_NONE 3457 * @see #LAYER_TYPE_SOFTWARE 3458 */ 3459 public static final int LAYER_TYPE_HARDWARE = 2; 3460 3461 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 3462 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 3463 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 3464 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 3465 }) 3466 int mLayerType = LAYER_TYPE_NONE; 3467 Paint mLayerPaint; 3468 Rect mLocalDirtyRect; 3469 private HardwareLayer mHardwareLayer; 3470 3471 /** 3472 * Set to true when drawing cache is enabled and cannot be created. 3473 * 3474 * @hide 3475 */ 3476 public boolean mCachingFailed; 3477 private Bitmap mDrawingCache; 3478 private Bitmap mUnscaledDrawingCache; 3479 3480 /** 3481 * RenderNode holding View properties, potentially holding a DisplayList of View content. 3482 * <p> 3483 * When non-null and valid, this is expected to contain an up-to-date copy 3484 * of the View content. Its DisplayList content is cleared on temporary detach and reset on 3485 * cleanup. 3486 */ 3487 final RenderNode mRenderNode; 3488 3489 /** 3490 * Set to true when the view is sending hover accessibility events because it 3491 * is the innermost hovered view. 3492 */ 3493 private boolean mSendingHoverAccessibilityEvents; 3494 3495 /** 3496 * Delegate for injecting accessibility functionality. 3497 */ 3498 AccessibilityDelegate mAccessibilityDelegate; 3499 3500 /** 3501 * The view's overlay layer. Developers get a reference to the overlay via getOverlay() 3502 * and add/remove objects to/from the overlay directly through the Overlay methods. 3503 */ 3504 ViewOverlay mOverlay; 3505 3506 /** 3507 * The currently active parent view for receiving delegated nested scrolling events. 3508 * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared 3509 * by {@link #stopNestedScroll()} at the same point where we clear 3510 * requestDisallowInterceptTouchEvent. 3511 */ 3512 private ViewParent mNestedScrollingParent; 3513 3514 /** 3515 * Consistency verifier for debugging purposes. 3516 * @hide 3517 */ 3518 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 3519 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 3520 new InputEventConsistencyVerifier(this, 0) : null; 3521 3522 private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); 3523 3524 private int[] mTempNestedScrollConsumed; 3525 3526 /** 3527 * Simple constructor to use when creating a view from code. 3528 * 3529 * @param context The Context the view is running in, through which it can 3530 * access the current theme, resources, etc. 3531 */ 3532 public View(Context context) { 3533 mContext = context; 3534 mResources = context != null ? context.getResources() : null; 3535 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED; 3536 // Set some flags defaults 3537 mPrivateFlags2 = 3538 (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) | 3539 (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) | 3540 (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) | 3541 (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) | 3542 (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) | 3543 (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT); 3544 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 3545 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 3546 mUserPaddingStart = UNDEFINED_PADDING; 3547 mUserPaddingEnd = UNDEFINED_PADDING; 3548 mRenderNode = RenderNode.create(getClass().getName()); 3549 3550 if (!sCompatibilityDone && context != null) { 3551 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3552 3553 // Older apps may need this compatibility hack for measurement. 3554 sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1; 3555 3556 // Older apps expect onMeasure() to always be called on a layout pass, regardless 3557 // of whether a layout was requested on that View. 3558 sIgnoreMeasureCache = targetSdkVersion < KITKAT; 3559 3560 // Older apps may need this to ignore the clip bounds 3561 sIgnoreClipBoundsForChildren = targetSdkVersion < L; 3562 3563 sCompatibilityDone = true; 3564 } 3565 } 3566 3567 /** 3568 * Constructor that is called when inflating a view from XML. This is called 3569 * when a view is being constructed from an XML file, supplying attributes 3570 * that were specified in the XML file. This version uses a default style of 3571 * 0, so the only attribute values applied are those in the Context's Theme 3572 * and the given AttributeSet. 3573 * 3574 * <p> 3575 * The method onFinishInflate() will be called after all children have been 3576 * added. 3577 * 3578 * @param context The Context the view is running in, through which it can 3579 * access the current theme, resources, etc. 3580 * @param attrs The attributes of the XML tag that is inflating the view. 3581 * @see #View(Context, AttributeSet, int) 3582 */ 3583 public View(Context context, AttributeSet attrs) { 3584 this(context, attrs, 0); 3585 } 3586 3587 /** 3588 * Perform inflation from XML and apply a class-specific base style from a 3589 * theme attribute. This constructor of View allows subclasses to use their 3590 * own base style when they are inflating. For example, a Button class's 3591 * constructor would call this version of the super class constructor and 3592 * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this 3593 * allows the theme's button style to modify all of the base view attributes 3594 * (in particular its background) as well as the Button class's attributes. 3595 * 3596 * @param context The Context the view is running in, through which it can 3597 * access the current theme, resources, etc. 3598 * @param attrs The attributes of the XML tag that is inflating the view. 3599 * @param defStyleAttr An attribute in the current theme that contains a 3600 * reference to a style resource that supplies default values for 3601 * the view. Can be 0 to not look for defaults. 3602 * @see #View(Context, AttributeSet) 3603 */ 3604 public View(Context context, AttributeSet attrs, int defStyleAttr) { 3605 this(context, attrs, defStyleAttr, 0); 3606 } 3607 3608 /** 3609 * Perform inflation from XML and apply a class-specific base style from a 3610 * theme attribute or style resource. This constructor of View allows 3611 * subclasses to use their own base style when they are inflating. 3612 * <p> 3613 * When determining the final value of a particular attribute, there are 3614 * four inputs that come into play: 3615 * <ol> 3616 * <li>Any attribute values in the given AttributeSet. 3617 * <li>The style resource specified in the AttributeSet (named "style"). 3618 * <li>The default style specified by <var>defStyleAttr</var>. 3619 * <li>The default style specified by <var>defStyleRes</var>. 3620 * <li>The base values in this theme. 3621 * </ol> 3622 * <p> 3623 * Each of these inputs is considered in-order, with the first listed taking 3624 * precedence over the following ones. In other words, if in the 3625 * AttributeSet you have supplied <code><Button * textColor="#ff000000"></code> 3626 * , then the button's text will <em>always</em> be black, regardless of 3627 * what is specified in any of the styles. 3628 * 3629 * @param context The Context the view is running in, through which it can 3630 * access the current theme, resources, etc. 3631 * @param attrs The attributes of the XML tag that is inflating the view. 3632 * @param defStyleAttr An attribute in the current theme that contains a 3633 * reference to a style resource that supplies default values for 3634 * the view. Can be 0 to not look for defaults. 3635 * @param defStyleRes A resource identifier of a style resource that 3636 * supplies default values for the view, used only if 3637 * defStyleAttr is 0 or can not be found in the theme. Can be 0 3638 * to not look for defaults. 3639 * @see #View(Context, AttributeSet, int) 3640 */ 3641 public View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { 3642 this(context); 3643 3644 final TypedArray a = context.obtainStyledAttributes( 3645 attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes); 3646 3647 Drawable background = null; 3648 3649 int leftPadding = -1; 3650 int topPadding = -1; 3651 int rightPadding = -1; 3652 int bottomPadding = -1; 3653 int startPadding = UNDEFINED_PADDING; 3654 int endPadding = UNDEFINED_PADDING; 3655 3656 int padding = -1; 3657 3658 int viewFlagValues = 0; 3659 int viewFlagMasks = 0; 3660 3661 boolean setScrollContainer = false; 3662 3663 int x = 0; 3664 int y = 0; 3665 3666 float tx = 0; 3667 float ty = 0; 3668 float tz = 0; 3669 float elevation = 0; 3670 float rotation = 0; 3671 float rotationX = 0; 3672 float rotationY = 0; 3673 float sx = 1f; 3674 float sy = 1f; 3675 boolean transformSet = false; 3676 3677 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 3678 int overScrollMode = mOverScrollMode; 3679 boolean initializeScrollbars = false; 3680 3681 boolean startPaddingDefined = false; 3682 boolean endPaddingDefined = false; 3683 boolean leftPaddingDefined = false; 3684 boolean rightPaddingDefined = false; 3685 3686 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3687 3688 final int N = a.getIndexCount(); 3689 for (int i = 0; i < N; i++) { 3690 int attr = a.getIndex(i); 3691 switch (attr) { 3692 case com.android.internal.R.styleable.View_background: 3693 background = a.getDrawable(attr); 3694 break; 3695 case com.android.internal.R.styleable.View_padding: 3696 padding = a.getDimensionPixelSize(attr, -1); 3697 mUserPaddingLeftInitial = padding; 3698 mUserPaddingRightInitial = padding; 3699 leftPaddingDefined = true; 3700 rightPaddingDefined = true; 3701 break; 3702 case com.android.internal.R.styleable.View_paddingLeft: 3703 leftPadding = a.getDimensionPixelSize(attr, -1); 3704 mUserPaddingLeftInitial = leftPadding; 3705 leftPaddingDefined = true; 3706 break; 3707 case com.android.internal.R.styleable.View_paddingTop: 3708 topPadding = a.getDimensionPixelSize(attr, -1); 3709 break; 3710 case com.android.internal.R.styleable.View_paddingRight: 3711 rightPadding = a.getDimensionPixelSize(attr, -1); 3712 mUserPaddingRightInitial = rightPadding; 3713 rightPaddingDefined = true; 3714 break; 3715 case com.android.internal.R.styleable.View_paddingBottom: 3716 bottomPadding = a.getDimensionPixelSize(attr, -1); 3717 break; 3718 case com.android.internal.R.styleable.View_paddingStart: 3719 startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3720 startPaddingDefined = (startPadding != UNDEFINED_PADDING); 3721 break; 3722 case com.android.internal.R.styleable.View_paddingEnd: 3723 endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3724 endPaddingDefined = (endPadding != UNDEFINED_PADDING); 3725 break; 3726 case com.android.internal.R.styleable.View_scrollX: 3727 x = a.getDimensionPixelOffset(attr, 0); 3728 break; 3729 case com.android.internal.R.styleable.View_scrollY: 3730 y = a.getDimensionPixelOffset(attr, 0); 3731 break; 3732 case com.android.internal.R.styleable.View_alpha: 3733 setAlpha(a.getFloat(attr, 1f)); 3734 break; 3735 case com.android.internal.R.styleable.View_transformPivotX: 3736 setPivotX(a.getDimensionPixelOffset(attr, 0)); 3737 break; 3738 case com.android.internal.R.styleable.View_transformPivotY: 3739 setPivotY(a.getDimensionPixelOffset(attr, 0)); 3740 break; 3741 case com.android.internal.R.styleable.View_translationX: 3742 tx = a.getDimensionPixelOffset(attr, 0); 3743 transformSet = true; 3744 break; 3745 case com.android.internal.R.styleable.View_translationY: 3746 ty = a.getDimensionPixelOffset(attr, 0); 3747 transformSet = true; 3748 break; 3749 case com.android.internal.R.styleable.View_translationZ: 3750 tz = a.getDimensionPixelOffset(attr, 0); 3751 transformSet = true; 3752 break; 3753 case com.android.internal.R.styleable.View_elevation: 3754 elevation = a.getDimensionPixelOffset(attr, 0); 3755 transformSet = true; 3756 break; 3757 case com.android.internal.R.styleable.View_rotation: 3758 rotation = a.getFloat(attr, 0); 3759 transformSet = true; 3760 break; 3761 case com.android.internal.R.styleable.View_rotationX: 3762 rotationX = a.getFloat(attr, 0); 3763 transformSet = true; 3764 break; 3765 case com.android.internal.R.styleable.View_rotationY: 3766 rotationY = a.getFloat(attr, 0); 3767 transformSet = true; 3768 break; 3769 case com.android.internal.R.styleable.View_scaleX: 3770 sx = a.getFloat(attr, 1f); 3771 transformSet = true; 3772 break; 3773 case com.android.internal.R.styleable.View_scaleY: 3774 sy = a.getFloat(attr, 1f); 3775 transformSet = true; 3776 break; 3777 case com.android.internal.R.styleable.View_id: 3778 mID = a.getResourceId(attr, NO_ID); 3779 break; 3780 case com.android.internal.R.styleable.View_tag: 3781 mTag = a.getText(attr); 3782 break; 3783 case com.android.internal.R.styleable.View_fitsSystemWindows: 3784 if (a.getBoolean(attr, false)) { 3785 viewFlagValues |= FITS_SYSTEM_WINDOWS; 3786 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 3787 } 3788 break; 3789 case com.android.internal.R.styleable.View_focusable: 3790 if (a.getBoolean(attr, false)) { 3791 viewFlagValues |= FOCUSABLE; 3792 viewFlagMasks |= FOCUSABLE_MASK; 3793 } 3794 break; 3795 case com.android.internal.R.styleable.View_focusableInTouchMode: 3796 if (a.getBoolean(attr, false)) { 3797 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 3798 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 3799 } 3800 break; 3801 case com.android.internal.R.styleable.View_clickable: 3802 if (a.getBoolean(attr, false)) { 3803 viewFlagValues |= CLICKABLE; 3804 viewFlagMasks |= CLICKABLE; 3805 } 3806 break; 3807 case com.android.internal.R.styleable.View_longClickable: 3808 if (a.getBoolean(attr, false)) { 3809 viewFlagValues |= LONG_CLICKABLE; 3810 viewFlagMasks |= LONG_CLICKABLE; 3811 } 3812 break; 3813 case com.android.internal.R.styleable.View_saveEnabled: 3814 if (!a.getBoolean(attr, true)) { 3815 viewFlagValues |= SAVE_DISABLED; 3816 viewFlagMasks |= SAVE_DISABLED_MASK; 3817 } 3818 break; 3819 case com.android.internal.R.styleable.View_duplicateParentState: 3820 if (a.getBoolean(attr, false)) { 3821 viewFlagValues |= DUPLICATE_PARENT_STATE; 3822 viewFlagMasks |= DUPLICATE_PARENT_STATE; 3823 } 3824 break; 3825 case com.android.internal.R.styleable.View_visibility: 3826 final int visibility = a.getInt(attr, 0); 3827 if (visibility != 0) { 3828 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 3829 viewFlagMasks |= VISIBILITY_MASK; 3830 } 3831 break; 3832 case com.android.internal.R.styleable.View_layoutDirection: 3833 // Clear any layout direction flags (included resolved bits) already set 3834 mPrivateFlags2 &= 3835 ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK); 3836 // Set the layout direction flags depending on the value of the attribute 3837 final int layoutDirection = a.getInt(attr, -1); 3838 final int value = (layoutDirection != -1) ? 3839 LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT; 3840 mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT); 3841 break; 3842 case com.android.internal.R.styleable.View_drawingCacheQuality: 3843 final int cacheQuality = a.getInt(attr, 0); 3844 if (cacheQuality != 0) { 3845 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 3846 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 3847 } 3848 break; 3849 case com.android.internal.R.styleable.View_contentDescription: 3850 setContentDescription(a.getString(attr)); 3851 break; 3852 case com.android.internal.R.styleable.View_labelFor: 3853 setLabelFor(a.getResourceId(attr, NO_ID)); 3854 break; 3855 case com.android.internal.R.styleable.View_soundEffectsEnabled: 3856 if (!a.getBoolean(attr, true)) { 3857 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 3858 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 3859 } 3860 break; 3861 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 3862 if (!a.getBoolean(attr, true)) { 3863 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 3864 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 3865 } 3866 break; 3867 case R.styleable.View_scrollbars: 3868 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 3869 if (scrollbars != SCROLLBARS_NONE) { 3870 viewFlagValues |= scrollbars; 3871 viewFlagMasks |= SCROLLBARS_MASK; 3872 initializeScrollbars = true; 3873 } 3874 break; 3875 //noinspection deprecation 3876 case R.styleable.View_fadingEdge: 3877 if (targetSdkVersion >= ICE_CREAM_SANDWICH) { 3878 // Ignore the attribute starting with ICS 3879 break; 3880 } 3881 // With builds < ICS, fall through and apply fading edges 3882 case R.styleable.View_requiresFadingEdge: 3883 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 3884 if (fadingEdge != FADING_EDGE_NONE) { 3885 viewFlagValues |= fadingEdge; 3886 viewFlagMasks |= FADING_EDGE_MASK; 3887 initializeFadingEdge(a); 3888 } 3889 break; 3890 case R.styleable.View_scrollbarStyle: 3891 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 3892 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3893 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 3894 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 3895 } 3896 break; 3897 case R.styleable.View_isScrollContainer: 3898 setScrollContainer = true; 3899 if (a.getBoolean(attr, false)) { 3900 setScrollContainer(true); 3901 } 3902 break; 3903 case com.android.internal.R.styleable.View_keepScreenOn: 3904 if (a.getBoolean(attr, false)) { 3905 viewFlagValues |= KEEP_SCREEN_ON; 3906 viewFlagMasks |= KEEP_SCREEN_ON; 3907 } 3908 break; 3909 case R.styleable.View_filterTouchesWhenObscured: 3910 if (a.getBoolean(attr, false)) { 3911 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 3912 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 3913 } 3914 break; 3915 case R.styleable.View_nextFocusLeft: 3916 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 3917 break; 3918 case R.styleable.View_nextFocusRight: 3919 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 3920 break; 3921 case R.styleable.View_nextFocusUp: 3922 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 3923 break; 3924 case R.styleable.View_nextFocusDown: 3925 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 3926 break; 3927 case R.styleable.View_nextFocusForward: 3928 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 3929 break; 3930 case R.styleable.View_minWidth: 3931 mMinWidth = a.getDimensionPixelSize(attr, 0); 3932 break; 3933 case R.styleable.View_minHeight: 3934 mMinHeight = a.getDimensionPixelSize(attr, 0); 3935 break; 3936 case R.styleable.View_onClick: 3937 if (context.isRestricted()) { 3938 throw new IllegalStateException("The android:onClick attribute cannot " 3939 + "be used within a restricted context"); 3940 } 3941 3942 final String handlerName = a.getString(attr); 3943 if (handlerName != null) { 3944 setOnClickListener(new OnClickListener() { 3945 private Method mHandler; 3946 3947 public void onClick(View v) { 3948 if (mHandler == null) { 3949 try { 3950 mHandler = getContext().getClass().getMethod(handlerName, 3951 View.class); 3952 } catch (NoSuchMethodException e) { 3953 int id = getId(); 3954 String idText = id == NO_ID ? "" : " with id '" 3955 + getContext().getResources().getResourceEntryName( 3956 id) + "'"; 3957 throw new IllegalStateException("Could not find a method " + 3958 handlerName + "(View) in the activity " 3959 + getContext().getClass() + " for onClick handler" 3960 + " on view " + View.this.getClass() + idText, e); 3961 } 3962 } 3963 3964 try { 3965 mHandler.invoke(getContext(), View.this); 3966 } catch (IllegalAccessException e) { 3967 throw new IllegalStateException("Could not execute non " 3968 + "public method of the activity", e); 3969 } catch (InvocationTargetException e) { 3970 throw new IllegalStateException("Could not execute " 3971 + "method of the activity", e); 3972 } 3973 } 3974 }); 3975 } 3976 break; 3977 case R.styleable.View_overScrollMode: 3978 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 3979 break; 3980 case R.styleable.View_verticalScrollbarPosition: 3981 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 3982 break; 3983 case R.styleable.View_layerType: 3984 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 3985 break; 3986 case R.styleable.View_textDirection: 3987 // Clear any text direction flag already set 3988 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 3989 // Set the text direction flags depending on the value of the attribute 3990 final int textDirection = a.getInt(attr, -1); 3991 if (textDirection != -1) { 3992 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection]; 3993 } 3994 break; 3995 case R.styleable.View_textAlignment: 3996 // Clear any text alignment flag already set 3997 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 3998 // Set the text alignment flag depending on the value of the attribute 3999 final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT); 4000 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment]; 4001 break; 4002 case R.styleable.View_importantForAccessibility: 4003 setImportantForAccessibility(a.getInt(attr, 4004 IMPORTANT_FOR_ACCESSIBILITY_DEFAULT)); 4005 break; 4006 case R.styleable.View_accessibilityLiveRegion: 4007 setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT)); 4008 break; 4009 case R.styleable.View_viewName: 4010 setViewName(a.getString(attr)); 4011 break; 4012 case R.styleable.View_nestedScrollingEnabled: 4013 setNestedScrollingEnabled(a.getBoolean(attr, false)); 4014 break; 4015 case R.styleable.View_stateListAnimator: 4016 setStateListAnimator(AnimatorInflater.loadStateListAnimator(context, 4017 a.getResourceId(attr, 0))); 4018 break; 4019 } 4020 } 4021 4022 setOverScrollMode(overScrollMode); 4023 4024 // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet 4025 // the resolved layout direction). Those cached values will be used later during padding 4026 // resolution. 4027 mUserPaddingStart = startPadding; 4028 mUserPaddingEnd = endPadding; 4029 4030 if (background != null) { 4031 setBackground(background); 4032 } 4033 4034 // setBackground above will record that padding is currently provided by the background. 4035 // If we have padding specified via xml, record that here instead and use it. 4036 mLeftPaddingDefined = leftPaddingDefined; 4037 mRightPaddingDefined = rightPaddingDefined; 4038 4039 if (padding >= 0) { 4040 leftPadding = padding; 4041 topPadding = padding; 4042 rightPadding = padding; 4043 bottomPadding = padding; 4044 mUserPaddingLeftInitial = padding; 4045 mUserPaddingRightInitial = padding; 4046 } 4047 4048 if (isRtlCompatibilityMode()) { 4049 // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case. 4050 // left / right padding are used if defined (meaning here nothing to do). If they are not 4051 // defined and start / end padding are defined (e.g. in Frameworks resources), then we use 4052 // start / end and resolve them as left / right (layout direction is not taken into account). 4053 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4054 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4055 // defined. 4056 if (!mLeftPaddingDefined && startPaddingDefined) { 4057 leftPadding = startPadding; 4058 } 4059 mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial; 4060 if (!mRightPaddingDefined && endPaddingDefined) { 4061 rightPadding = endPadding; 4062 } 4063 mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial; 4064 } else { 4065 // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right 4066 // values defined. Otherwise, left /right values are used. 4067 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4068 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4069 // defined. 4070 final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined; 4071 4072 if (mLeftPaddingDefined && !hasRelativePadding) { 4073 mUserPaddingLeftInitial = leftPadding; 4074 } 4075 if (mRightPaddingDefined && !hasRelativePadding) { 4076 mUserPaddingRightInitial = rightPadding; 4077 } 4078 } 4079 4080 internalSetPadding( 4081 mUserPaddingLeftInitial, 4082 topPadding >= 0 ? topPadding : mPaddingTop, 4083 mUserPaddingRightInitial, 4084 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 4085 4086 if (viewFlagMasks != 0) { 4087 setFlags(viewFlagValues, viewFlagMasks); 4088 } 4089 4090 if (initializeScrollbars) { 4091 initializeScrollbars(a); 4092 } 4093 4094 a.recycle(); 4095 4096 // Needs to be called after mViewFlags is set 4097 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 4098 recomputePadding(); 4099 } 4100 4101 if (x != 0 || y != 0) { 4102 scrollTo(x, y); 4103 } 4104 4105 if (transformSet) { 4106 setTranslationX(tx); 4107 setTranslationY(ty); 4108 setTranslationZ(tz); 4109 setElevation(elevation); 4110 setRotation(rotation); 4111 setRotationX(rotationX); 4112 setRotationY(rotationY); 4113 setScaleX(sx); 4114 setScaleY(sy); 4115 } 4116 4117 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 4118 setScrollContainer(true); 4119 } 4120 4121 computeOpaqueFlags(); 4122 } 4123 4124 /** 4125 * Non-public constructor for use in testing 4126 */ 4127 View() { 4128 mResources = null; 4129 mRenderNode = RenderNode.create(getClass().getName()); 4130 } 4131 4132 public String toString() { 4133 StringBuilder out = new StringBuilder(128); 4134 out.append(getClass().getName()); 4135 out.append('{'); 4136 out.append(Integer.toHexString(System.identityHashCode(this))); 4137 out.append(' '); 4138 switch (mViewFlags&VISIBILITY_MASK) { 4139 case VISIBLE: out.append('V'); break; 4140 case INVISIBLE: out.append('I'); break; 4141 case GONE: out.append('G'); break; 4142 default: out.append('.'); break; 4143 } 4144 out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.'); 4145 out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.'); 4146 out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D'); 4147 out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.'); 4148 out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.'); 4149 out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.'); 4150 out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.'); 4151 out.append(' '); 4152 out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.'); 4153 out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.'); 4154 out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.'); 4155 if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) { 4156 out.append('p'); 4157 } else { 4158 out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.'); 4159 } 4160 out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.'); 4161 out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.'); 4162 out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.'); 4163 out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.'); 4164 out.append(' '); 4165 out.append(mLeft); 4166 out.append(','); 4167 out.append(mTop); 4168 out.append('-'); 4169 out.append(mRight); 4170 out.append(','); 4171 out.append(mBottom); 4172 final int id = getId(); 4173 if (id != NO_ID) { 4174 out.append(" #"); 4175 out.append(Integer.toHexString(id)); 4176 final Resources r = mResources; 4177 if (Resources.resourceHasPackage(id) && r != null) { 4178 try { 4179 String pkgname; 4180 switch (id&0xff000000) { 4181 case 0x7f000000: 4182 pkgname="app"; 4183 break; 4184 case 0x01000000: 4185 pkgname="android"; 4186 break; 4187 default: 4188 pkgname = r.getResourcePackageName(id); 4189 break; 4190 } 4191 String typename = r.getResourceTypeName(id); 4192 String entryname = r.getResourceEntryName(id); 4193 out.append(" "); 4194 out.append(pkgname); 4195 out.append(":"); 4196 out.append(typename); 4197 out.append("/"); 4198 out.append(entryname); 4199 } catch (Resources.NotFoundException e) { 4200 } 4201 } 4202 } 4203 out.append("}"); 4204 return out.toString(); 4205 } 4206 4207 /** 4208 * <p> 4209 * Initializes the fading edges from a given set of styled attributes. This 4210 * method should be called by subclasses that need fading edges and when an 4211 * instance of these subclasses is created programmatically rather than 4212 * being inflated from XML. This method is automatically called when the XML 4213 * is inflated. 4214 * </p> 4215 * 4216 * @param a the styled attributes set to initialize the fading edges from 4217 */ 4218 protected void initializeFadingEdge(TypedArray a) { 4219 initScrollCache(); 4220 4221 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 4222 R.styleable.View_fadingEdgeLength, 4223 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 4224 } 4225 4226 /** 4227 * Returns the size of the vertical faded edges used to indicate that more 4228 * content in this view is visible. 4229 * 4230 * @return The size in pixels of the vertical faded edge or 0 if vertical 4231 * faded edges are not enabled for this view. 4232 * @attr ref android.R.styleable#View_fadingEdgeLength 4233 */ 4234 public int getVerticalFadingEdgeLength() { 4235 if (isVerticalFadingEdgeEnabled()) { 4236 ScrollabilityCache cache = mScrollCache; 4237 if (cache != null) { 4238 return cache.fadingEdgeLength; 4239 } 4240 } 4241 return 0; 4242 } 4243 4244 /** 4245 * Set the size of the faded edge used to indicate that more content in this 4246 * view is available. Will not change whether the fading edge is enabled; use 4247 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 4248 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 4249 * for the vertical or horizontal fading edges. 4250 * 4251 * @param length The size in pixels of the faded edge used to indicate that more 4252 * content in this view is visible. 4253 */ 4254 public void setFadingEdgeLength(int length) { 4255 initScrollCache(); 4256 mScrollCache.fadingEdgeLength = length; 4257 } 4258 4259 /** 4260 * Returns the size of the horizontal faded edges used to indicate that more 4261 * content in this view is visible. 4262 * 4263 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 4264 * faded edges are not enabled for this view. 4265 * @attr ref android.R.styleable#View_fadingEdgeLength 4266 */ 4267 public int getHorizontalFadingEdgeLength() { 4268 if (isHorizontalFadingEdgeEnabled()) { 4269 ScrollabilityCache cache = mScrollCache; 4270 if (cache != null) { 4271 return cache.fadingEdgeLength; 4272 } 4273 } 4274 return 0; 4275 } 4276 4277 /** 4278 * Returns the width of the vertical scrollbar. 4279 * 4280 * @return The width in pixels of the vertical scrollbar or 0 if there 4281 * is no vertical scrollbar. 4282 */ 4283 public int getVerticalScrollbarWidth() { 4284 ScrollabilityCache cache = mScrollCache; 4285 if (cache != null) { 4286 ScrollBarDrawable scrollBar = cache.scrollBar; 4287 if (scrollBar != null) { 4288 int size = scrollBar.getSize(true); 4289 if (size <= 0) { 4290 size = cache.scrollBarSize; 4291 } 4292 return size; 4293 } 4294 return 0; 4295 } 4296 return 0; 4297 } 4298 4299 /** 4300 * Returns the height of the horizontal scrollbar. 4301 * 4302 * @return The height in pixels of the horizontal scrollbar or 0 if 4303 * there is no horizontal scrollbar. 4304 */ 4305 protected int getHorizontalScrollbarHeight() { 4306 ScrollabilityCache cache = mScrollCache; 4307 if (cache != null) { 4308 ScrollBarDrawable scrollBar = cache.scrollBar; 4309 if (scrollBar != null) { 4310 int size = scrollBar.getSize(false); 4311 if (size <= 0) { 4312 size = cache.scrollBarSize; 4313 } 4314 return size; 4315 } 4316 return 0; 4317 } 4318 return 0; 4319 } 4320 4321 /** 4322 * <p> 4323 * Initializes the scrollbars from a given set of styled attributes. This 4324 * method should be called by subclasses that need scrollbars and when an 4325 * instance of these subclasses is created programmatically rather than 4326 * being inflated from XML. This method is automatically called when the XML 4327 * is inflated. 4328 * </p> 4329 * 4330 * @param a the styled attributes set to initialize the scrollbars from 4331 */ 4332 protected void initializeScrollbars(TypedArray a) { 4333 initScrollCache(); 4334 4335 final ScrollabilityCache scrollabilityCache = mScrollCache; 4336 4337 if (scrollabilityCache.scrollBar == null) { 4338 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 4339 } 4340 4341 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 4342 4343 if (!fadeScrollbars) { 4344 scrollabilityCache.state = ScrollabilityCache.ON; 4345 } 4346 scrollabilityCache.fadeScrollBars = fadeScrollbars; 4347 4348 4349 scrollabilityCache.scrollBarFadeDuration = a.getInt( 4350 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 4351 .getScrollBarFadeDuration()); 4352 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 4353 R.styleable.View_scrollbarDefaultDelayBeforeFade, 4354 ViewConfiguration.getScrollDefaultDelay()); 4355 4356 4357 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 4358 com.android.internal.R.styleable.View_scrollbarSize, 4359 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 4360 4361 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 4362 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 4363 4364 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 4365 if (thumb != null) { 4366 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 4367 } 4368 4369 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 4370 false); 4371 if (alwaysDraw) { 4372 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 4373 } 4374 4375 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 4376 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 4377 4378 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 4379 if (thumb != null) { 4380 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 4381 } 4382 4383 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 4384 false); 4385 if (alwaysDraw) { 4386 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 4387 } 4388 4389 // Apply layout direction to the new Drawables if needed 4390 final int layoutDirection = getLayoutDirection(); 4391 if (track != null) { 4392 track.setLayoutDirection(layoutDirection); 4393 } 4394 if (thumb != null) { 4395 thumb.setLayoutDirection(layoutDirection); 4396 } 4397 4398 // Re-apply user/background padding so that scrollbar(s) get added 4399 resolvePadding(); 4400 } 4401 4402 /** 4403 * <p> 4404 * Initalizes the scrollability cache if necessary. 4405 * </p> 4406 */ 4407 private void initScrollCache() { 4408 if (mScrollCache == null) { 4409 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 4410 } 4411 } 4412 4413 private ScrollabilityCache getScrollCache() { 4414 initScrollCache(); 4415 return mScrollCache; 4416 } 4417 4418 /** 4419 * Set the position of the vertical scroll bar. Should be one of 4420 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 4421 * {@link #SCROLLBAR_POSITION_RIGHT}. 4422 * 4423 * @param position Where the vertical scroll bar should be positioned. 4424 */ 4425 public void setVerticalScrollbarPosition(int position) { 4426 if (mVerticalScrollbarPosition != position) { 4427 mVerticalScrollbarPosition = position; 4428 computeOpaqueFlags(); 4429 resolvePadding(); 4430 } 4431 } 4432 4433 /** 4434 * @return The position where the vertical scroll bar will show, if applicable. 4435 * @see #setVerticalScrollbarPosition(int) 4436 */ 4437 public int getVerticalScrollbarPosition() { 4438 return mVerticalScrollbarPosition; 4439 } 4440 4441 ListenerInfo getListenerInfo() { 4442 if (mListenerInfo != null) { 4443 return mListenerInfo; 4444 } 4445 mListenerInfo = new ListenerInfo(); 4446 return mListenerInfo; 4447 } 4448 4449 /** 4450 * Register a callback to be invoked when focus of this view changed. 4451 * 4452 * @param l The callback that will run. 4453 */ 4454 public void setOnFocusChangeListener(OnFocusChangeListener l) { 4455 getListenerInfo().mOnFocusChangeListener = l; 4456 } 4457 4458 /** 4459 * Add a listener that will be called when the bounds of the view change due to 4460 * layout processing. 4461 * 4462 * @param listener The listener that will be called when layout bounds change. 4463 */ 4464 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 4465 ListenerInfo li = getListenerInfo(); 4466 if (li.mOnLayoutChangeListeners == null) { 4467 li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 4468 } 4469 if (!li.mOnLayoutChangeListeners.contains(listener)) { 4470 li.mOnLayoutChangeListeners.add(listener); 4471 } 4472 } 4473 4474 /** 4475 * Remove a listener for layout changes. 4476 * 4477 * @param listener The listener for layout bounds change. 4478 */ 4479 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 4480 ListenerInfo li = mListenerInfo; 4481 if (li == null || li.mOnLayoutChangeListeners == null) { 4482 return; 4483 } 4484 li.mOnLayoutChangeListeners.remove(listener); 4485 } 4486 4487 /** 4488 * Add a listener for attach state changes. 4489 * 4490 * This listener will be called whenever this view is attached or detached 4491 * from a window. Remove the listener using 4492 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 4493 * 4494 * @param listener Listener to attach 4495 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 4496 */ 4497 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4498 ListenerInfo li = getListenerInfo(); 4499 if (li.mOnAttachStateChangeListeners == null) { 4500 li.mOnAttachStateChangeListeners 4501 = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 4502 } 4503 li.mOnAttachStateChangeListeners.add(listener); 4504 } 4505 4506 /** 4507 * Remove a listener for attach state changes. The listener will receive no further 4508 * notification of window attach/detach events. 4509 * 4510 * @param listener Listener to remove 4511 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 4512 */ 4513 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4514 ListenerInfo li = mListenerInfo; 4515 if (li == null || li.mOnAttachStateChangeListeners == null) { 4516 return; 4517 } 4518 li.mOnAttachStateChangeListeners.remove(listener); 4519 } 4520 4521 /** 4522 * Returns the focus-change callback registered for this view. 4523 * 4524 * @return The callback, or null if one is not registered. 4525 */ 4526 public OnFocusChangeListener getOnFocusChangeListener() { 4527 ListenerInfo li = mListenerInfo; 4528 return li != null ? li.mOnFocusChangeListener : null; 4529 } 4530 4531 /** 4532 * Register a callback to be invoked when this view is clicked. If this view is not 4533 * clickable, it becomes clickable. 4534 * 4535 * @param l The callback that will run 4536 * 4537 * @see #setClickable(boolean) 4538 */ 4539 public void setOnClickListener(OnClickListener l) { 4540 if (!isClickable()) { 4541 setClickable(true); 4542 } 4543 getListenerInfo().mOnClickListener = l; 4544 } 4545 4546 /** 4547 * Return whether this view has an attached OnClickListener. Returns 4548 * true if there is a listener, false if there is none. 4549 */ 4550 public boolean hasOnClickListeners() { 4551 ListenerInfo li = mListenerInfo; 4552 return (li != null && li.mOnClickListener != null); 4553 } 4554 4555 /** 4556 * Register a callback to be invoked when this view is clicked and held. If this view is not 4557 * long clickable, it becomes long clickable. 4558 * 4559 * @param l The callback that will run 4560 * 4561 * @see #setLongClickable(boolean) 4562 */ 4563 public void setOnLongClickListener(OnLongClickListener l) { 4564 if (!isLongClickable()) { 4565 setLongClickable(true); 4566 } 4567 getListenerInfo().mOnLongClickListener = l; 4568 } 4569 4570 /** 4571 * Register a callback to be invoked when the context menu for this view is 4572 * being built. If this view is not long clickable, it becomes long clickable. 4573 * 4574 * @param l The callback that will run 4575 * 4576 */ 4577 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 4578 if (!isLongClickable()) { 4579 setLongClickable(true); 4580 } 4581 getListenerInfo().mOnCreateContextMenuListener = l; 4582 } 4583 4584 /** 4585 * Call this view's OnClickListener, if it is defined. Performs all normal 4586 * actions associated with clicking: reporting accessibility event, playing 4587 * a sound, etc. 4588 * 4589 * @return True there was an assigned OnClickListener that was called, false 4590 * otherwise is returned. 4591 */ 4592 public boolean performClick() { 4593 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 4594 4595 ListenerInfo li = mListenerInfo; 4596 if (li != null && li.mOnClickListener != null) { 4597 playSoundEffect(SoundEffectConstants.CLICK); 4598 li.mOnClickListener.onClick(this); 4599 return true; 4600 } 4601 4602 return false; 4603 } 4604 4605 /** 4606 * Directly call any attached OnClickListener. Unlike {@link #performClick()}, 4607 * this only calls the listener, and does not do any associated clicking 4608 * actions like reporting an accessibility event. 4609 * 4610 * @return True there was an assigned OnClickListener that was called, false 4611 * otherwise is returned. 4612 */ 4613 public boolean callOnClick() { 4614 ListenerInfo li = mListenerInfo; 4615 if (li != null && li.mOnClickListener != null) { 4616 li.mOnClickListener.onClick(this); 4617 return true; 4618 } 4619 return false; 4620 } 4621 4622 /** 4623 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the 4624 * OnLongClickListener did not consume the event. 4625 * 4626 * @return True if one of the above receivers consumed the event, false otherwise. 4627 */ 4628 public boolean performLongClick() { 4629 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 4630 4631 boolean handled = false; 4632 ListenerInfo li = mListenerInfo; 4633 if (li != null && li.mOnLongClickListener != null) { 4634 handled = li.mOnLongClickListener.onLongClick(View.this); 4635 } 4636 if (!handled) { 4637 handled = showContextMenu(); 4638 } 4639 if (handled) { 4640 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 4641 } 4642 return handled; 4643 } 4644 4645 /** 4646 * Performs button-related actions during a touch down event. 4647 * 4648 * @param event The event. 4649 * @return True if the down was consumed. 4650 * 4651 * @hide 4652 */ 4653 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 4654 if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 4655 if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) { 4656 return true; 4657 } 4658 } 4659 return false; 4660 } 4661 4662 /** 4663 * Bring up the context menu for this view. 4664 * 4665 * @return Whether a context menu was displayed. 4666 */ 4667 public boolean showContextMenu() { 4668 return getParent().showContextMenuForChild(this); 4669 } 4670 4671 /** 4672 * Bring up the context menu for this view, referring to the item under the specified point. 4673 * 4674 * @param x The referenced x coordinate. 4675 * @param y The referenced y coordinate. 4676 * @param metaState The keyboard modifiers that were pressed. 4677 * @return Whether a context menu was displayed. 4678 * 4679 * @hide 4680 */ 4681 public boolean showContextMenu(float x, float y, int metaState) { 4682 return showContextMenu(); 4683 } 4684 4685 /** 4686 * Start an action mode. 4687 * 4688 * @param callback Callback that will control the lifecycle of the action mode 4689 * @return The new action mode if it is started, null otherwise 4690 * 4691 * @see ActionMode 4692 */ 4693 public ActionMode startActionMode(ActionMode.Callback callback) { 4694 ViewParent parent = getParent(); 4695 if (parent == null) return null; 4696 return parent.startActionModeForChild(this, callback); 4697 } 4698 4699 /** 4700 * Register a callback to be invoked when a hardware key is pressed in this view. 4701 * Key presses in software input methods will generally not trigger the methods of 4702 * this listener. 4703 * @param l the key listener to attach to this view 4704 */ 4705 public void setOnKeyListener(OnKeyListener l) { 4706 getListenerInfo().mOnKeyListener = l; 4707 } 4708 4709 /** 4710 * Register a callback to be invoked when a touch event is sent to this view. 4711 * @param l the touch listener to attach to this view 4712 */ 4713 public void setOnTouchListener(OnTouchListener l) { 4714 getListenerInfo().mOnTouchListener = l; 4715 } 4716 4717 /** 4718 * Register a callback to be invoked when a generic motion event is sent to this view. 4719 * @param l the generic motion listener to attach to this view 4720 */ 4721 public void setOnGenericMotionListener(OnGenericMotionListener l) { 4722 getListenerInfo().mOnGenericMotionListener = l; 4723 } 4724 4725 /** 4726 * Register a callback to be invoked when a hover event is sent to this view. 4727 * @param l the hover listener to attach to this view 4728 */ 4729 public void setOnHoverListener(OnHoverListener l) { 4730 getListenerInfo().mOnHoverListener = l; 4731 } 4732 4733 /** 4734 * Register a drag event listener callback object for this View. The parameter is 4735 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 4736 * View, the system calls the 4737 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 4738 * @param l An implementation of {@link android.view.View.OnDragListener}. 4739 */ 4740 public void setOnDragListener(OnDragListener l) { 4741 getListenerInfo().mOnDragListener = l; 4742 } 4743 4744 /** 4745 * Give this view focus. This will cause 4746 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 4747 * 4748 * Note: this does not check whether this {@link View} should get focus, it just 4749 * gives it focus no matter what. It should only be called internally by framework 4750 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 4751 * 4752 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 4753 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 4754 * focus moved when requestFocus() is called. It may not always 4755 * apply, in which case use the default View.FOCUS_DOWN. 4756 * @param previouslyFocusedRect The rectangle of the view that had focus 4757 * prior in this View's coordinate system. 4758 */ 4759 void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) { 4760 if (DBG) { 4761 System.out.println(this + " requestFocus()"); 4762 } 4763 4764 if ((mPrivateFlags & PFLAG_FOCUSED) == 0) { 4765 mPrivateFlags |= PFLAG_FOCUSED; 4766 4767 View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null; 4768 4769 if (mParent != null) { 4770 mParent.requestChildFocus(this, this); 4771 } 4772 4773 if (mAttachInfo != null) { 4774 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this); 4775 } 4776 4777 onFocusChanged(true, direction, previouslyFocusedRect); 4778 manageFocusHotspot(true, oldFocus); 4779 refreshDrawableState(); 4780 } 4781 } 4782 4783 /** 4784 * Forwards focus information to the background drawable, if necessary. When 4785 * the view is gaining focus, <code>v</code> is the previous focus holder. 4786 * When the view is losing focus, <code>v</code> is the next focus holder. 4787 * 4788 * @param focused whether this view is focused 4789 * @param v previous or the next focus holder, or null if none 4790 */ 4791 private void manageFocusHotspot(boolean focused, View v) { 4792 if (mBackground == null) { 4793 return; 4794 } 4795 4796 final Rect r = new Rect(); 4797 if (!focused && v != null) { 4798 v.getBoundsOnScreen(r); 4799 final int[] location = new int[2]; 4800 getLocationOnScreen(location); 4801 r.offset(-location[0], -location[1]); 4802 } else { 4803 r.set(0, 0, mRight - mLeft, mBottom - mTop); 4804 } 4805 4806 final float x = r.exactCenterX(); 4807 final float y = r.exactCenterY(); 4808 mBackground.setHotspot(x, y); 4809 } 4810 4811 /** 4812 * Request that a rectangle of this view be visible on the screen, 4813 * scrolling if necessary just enough. 4814 * 4815 * <p>A View should call this if it maintains some notion of which part 4816 * of its content is interesting. For example, a text editing view 4817 * should call this when its cursor moves. 4818 * 4819 * @param rectangle The rectangle. 4820 * @return Whether any parent scrolled. 4821 */ 4822 public boolean requestRectangleOnScreen(Rect rectangle) { 4823 return requestRectangleOnScreen(rectangle, false); 4824 } 4825 4826 /** 4827 * Request that a rectangle of this view be visible on the screen, 4828 * scrolling if necessary just enough. 4829 * 4830 * <p>A View should call this if it maintains some notion of which part 4831 * of its content is interesting. For example, a text editing view 4832 * should call this when its cursor moves. 4833 * 4834 * <p>When <code>immediate</code> is set to true, scrolling will not be 4835 * animated. 4836 * 4837 * @param rectangle The rectangle. 4838 * @param immediate True to forbid animated scrolling, false otherwise 4839 * @return Whether any parent scrolled. 4840 */ 4841 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 4842 if (mParent == null) { 4843 return false; 4844 } 4845 4846 View child = this; 4847 4848 RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF(); 4849 position.set(rectangle); 4850 4851 ViewParent parent = mParent; 4852 boolean scrolled = false; 4853 while (parent != null) { 4854 rectangle.set((int) position.left, (int) position.top, 4855 (int) position.right, (int) position.bottom); 4856 4857 scrolled |= parent.requestChildRectangleOnScreen(child, 4858 rectangle, immediate); 4859 4860 if (!child.hasIdentityMatrix()) { 4861 child.getMatrix().mapRect(position); 4862 } 4863 4864 position.offset(child.mLeft, child.mTop); 4865 4866 if (!(parent instanceof View)) { 4867 break; 4868 } 4869 4870 View parentView = (View) parent; 4871 4872 position.offset(-parentView.getScrollX(), -parentView.getScrollY()); 4873 4874 child = parentView; 4875 parent = child.getParent(); 4876 } 4877 4878 return scrolled; 4879 } 4880 4881 /** 4882 * Called when this view wants to give up focus. If focus is cleared 4883 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called. 4884 * <p> 4885 * <strong>Note:</strong> When a View clears focus the framework is trying 4886 * to give focus to the first focusable View from the top. Hence, if this 4887 * View is the first from the top that can take focus, then all callbacks 4888 * related to clearing focus will be invoked after wich the framework will 4889 * give focus to this view. 4890 * </p> 4891 */ 4892 public void clearFocus() { 4893 if (DBG) { 4894 System.out.println(this + " clearFocus()"); 4895 } 4896 4897 clearFocusInternal(null, true, true); 4898 } 4899 4900 /** 4901 * Clears focus from the view, optionally propagating the change up through 4902 * the parent hierarchy and requesting that the root view place new focus. 4903 * 4904 * @param propagate whether to propagate the change up through the parent 4905 * hierarchy 4906 * @param refocus when propagate is true, specifies whether to request the 4907 * root view place new focus 4908 */ 4909 void clearFocusInternal(View focused, boolean propagate, boolean refocus) { 4910 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 4911 mPrivateFlags &= ~PFLAG_FOCUSED; 4912 4913 if (propagate && mParent != null) { 4914 mParent.clearChildFocus(this); 4915 } 4916 4917 onFocusChanged(false, 0, null); 4918 4919 manageFocusHotspot(false, focused); 4920 refreshDrawableState(); 4921 4922 if (propagate && (!refocus || !rootViewRequestFocus())) { 4923 notifyGlobalFocusCleared(this); 4924 } 4925 } 4926 } 4927 4928 void notifyGlobalFocusCleared(View oldFocus) { 4929 if (oldFocus != null && mAttachInfo != null) { 4930 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null); 4931 } 4932 } 4933 4934 boolean rootViewRequestFocus() { 4935 final View root = getRootView(); 4936 return root != null && root.requestFocus(); 4937 } 4938 4939 /** 4940 * Called internally by the view system when a new view is getting focus. 4941 * This is what clears the old focus. 4942 * <p> 4943 * <b>NOTE:</b> The parent view's focused child must be updated manually 4944 * after calling this method. Otherwise, the view hierarchy may be left in 4945 * an inconstent state. 4946 */ 4947 void unFocus(View focused) { 4948 if (DBG) { 4949 System.out.println(this + " unFocus()"); 4950 } 4951 4952 clearFocusInternal(focused, false, false); 4953 } 4954 4955 /** 4956 * Returns true if this view has focus iteself, or is the ancestor of the 4957 * view that has focus. 4958 * 4959 * @return True if this view has or contains focus, false otherwise. 4960 */ 4961 @ViewDebug.ExportedProperty(category = "focus") 4962 public boolean hasFocus() { 4963 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 4964 } 4965 4966 /** 4967 * Returns true if this view is focusable or if it contains a reachable View 4968 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 4969 * is a View whose parents do not block descendants focus. 4970 * 4971 * Only {@link #VISIBLE} views are considered focusable. 4972 * 4973 * @return True if the view is focusable or if the view contains a focusable 4974 * View, false otherwise. 4975 * 4976 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 4977 */ 4978 public boolean hasFocusable() { 4979 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 4980 } 4981 4982 /** 4983 * Called by the view system when the focus state of this view changes. 4984 * When the focus change event is caused by directional navigation, direction 4985 * and previouslyFocusedRect provide insight into where the focus is coming from. 4986 * When overriding, be sure to call up through to the super class so that 4987 * the standard focus handling will occur. 4988 * 4989 * @param gainFocus True if the View has focus; false otherwise. 4990 * @param direction The direction focus has moved when requestFocus() 4991 * is called to give this view focus. Values are 4992 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 4993 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 4994 * It may not always apply, in which case use the default. 4995 * @param previouslyFocusedRect The rectangle, in this view's coordinate 4996 * system, of the previously focused view. If applicable, this will be 4997 * passed in as finer grained information about where the focus is coming 4998 * from (in addition to direction). Will be <code>null</code> otherwise. 4999 */ 5000 protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction, 5001 @Nullable Rect previouslyFocusedRect) { 5002 if (gainFocus) { 5003 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 5004 } else { 5005 notifyViewAccessibilityStateChangedIfNeeded( 5006 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 5007 } 5008 5009 InputMethodManager imm = InputMethodManager.peekInstance(); 5010 if (!gainFocus) { 5011 if (isPressed()) { 5012 setPressed(false); 5013 } 5014 if (imm != null && mAttachInfo != null 5015 && mAttachInfo.mHasWindowFocus) { 5016 imm.focusOut(this); 5017 } 5018 onFocusLost(); 5019 } else if (imm != null && mAttachInfo != null 5020 && mAttachInfo.mHasWindowFocus) { 5021 imm.focusIn(this); 5022 } 5023 5024 invalidate(true); 5025 ListenerInfo li = mListenerInfo; 5026 if (li != null && li.mOnFocusChangeListener != null) { 5027 li.mOnFocusChangeListener.onFocusChange(this, gainFocus); 5028 } 5029 5030 if (mAttachInfo != null) { 5031 mAttachInfo.mKeyDispatchState.reset(this); 5032 } 5033 } 5034 5035 /** 5036 * Sends an accessibility event of the given type. If accessibility is 5037 * not enabled this method has no effect. The default implementation calls 5038 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 5039 * to populate information about the event source (this View), then calls 5040 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 5041 * populate the text content of the event source including its descendants, 5042 * and last calls 5043 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 5044 * on its parent to resuest sending of the event to interested parties. 5045 * <p> 5046 * If an {@link AccessibilityDelegate} has been specified via calling 5047 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5048 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 5049 * responsible for handling this call. 5050 * </p> 5051 * 5052 * @param eventType The type of the event to send, as defined by several types from 5053 * {@link android.view.accessibility.AccessibilityEvent}, such as 5054 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or 5055 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}. 5056 * 5057 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 5058 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5059 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 5060 * @see AccessibilityDelegate 5061 */ 5062 public void sendAccessibilityEvent(int eventType) { 5063 if (mAccessibilityDelegate != null) { 5064 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 5065 } else { 5066 sendAccessibilityEventInternal(eventType); 5067 } 5068 } 5069 5070 /** 5071 * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT} 5072 * {@link AccessibilityEvent} to make an announcement which is related to some 5073 * sort of a context change for which none of the events representing UI transitions 5074 * is a good fit. For example, announcing a new page in a book. If accessibility 5075 * is not enabled this method does nothing. 5076 * 5077 * @param text The announcement text. 5078 */ 5079 public void announceForAccessibility(CharSequence text) { 5080 if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) { 5081 AccessibilityEvent event = AccessibilityEvent.obtain( 5082 AccessibilityEvent.TYPE_ANNOUNCEMENT); 5083 onInitializeAccessibilityEvent(event); 5084 event.getText().add(text); 5085 event.setContentDescription(null); 5086 mParent.requestSendAccessibilityEvent(this, event); 5087 } 5088 } 5089 5090 /** 5091 * @see #sendAccessibilityEvent(int) 5092 * 5093 * Note: Called from the default {@link AccessibilityDelegate}. 5094 */ 5095 void sendAccessibilityEventInternal(int eventType) { 5096 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 5097 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 5098 } 5099 } 5100 5101 /** 5102 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 5103 * takes as an argument an empty {@link AccessibilityEvent} and does not 5104 * perform a check whether accessibility is enabled. 5105 * <p> 5106 * If an {@link AccessibilityDelegate} has been specified via calling 5107 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5108 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 5109 * is responsible for handling this call. 5110 * </p> 5111 * 5112 * @param event The event to send. 5113 * 5114 * @see #sendAccessibilityEvent(int) 5115 */ 5116 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 5117 if (mAccessibilityDelegate != null) { 5118 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 5119 } else { 5120 sendAccessibilityEventUncheckedInternal(event); 5121 } 5122 } 5123 5124 /** 5125 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 5126 * 5127 * Note: Called from the default {@link AccessibilityDelegate}. 5128 */ 5129 void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 5130 if (!isShown()) { 5131 return; 5132 } 5133 onInitializeAccessibilityEvent(event); 5134 // Only a subset of accessibility events populates text content. 5135 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) { 5136 dispatchPopulateAccessibilityEvent(event); 5137 } 5138 // In the beginning we called #isShown(), so we know that getParent() is not null. 5139 getParent().requestSendAccessibilityEvent(this, event); 5140 } 5141 5142 /** 5143 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 5144 * to its children for adding their text content to the event. Note that the 5145 * event text is populated in a separate dispatch path since we add to the 5146 * event not only the text of the source but also the text of all its descendants. 5147 * A typical implementation will call 5148 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 5149 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 5150 * on each child. Override this method if custom population of the event text 5151 * content is required. 5152 * <p> 5153 * If an {@link AccessibilityDelegate} has been specified via calling 5154 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5155 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 5156 * is responsible for handling this call. 5157 * </p> 5158 * <p> 5159 * <em>Note:</em> Accessibility events of certain types are not dispatched for 5160 * populating the event text via this method. For details refer to {@link AccessibilityEvent}. 5161 * </p> 5162 * 5163 * @param event The event. 5164 * 5165 * @return True if the event population was completed. 5166 */ 5167 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 5168 if (mAccessibilityDelegate != null) { 5169 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 5170 } else { 5171 return dispatchPopulateAccessibilityEventInternal(event); 5172 } 5173 } 5174 5175 /** 5176 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5177 * 5178 * Note: Called from the default {@link AccessibilityDelegate}. 5179 */ 5180 boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5181 onPopulateAccessibilityEvent(event); 5182 return false; 5183 } 5184 5185 /** 5186 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 5187 * giving a chance to this View to populate the accessibility event with its 5188 * text content. While this method is free to modify event 5189 * attributes other than text content, doing so should normally be performed in 5190 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 5191 * <p> 5192 * Example: Adding formatted date string to an accessibility event in addition 5193 * to the text added by the super implementation: 5194 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5195 * super.onPopulateAccessibilityEvent(event); 5196 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 5197 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 5198 * mCurrentDate.getTimeInMillis(), flags); 5199 * event.getText().add(selectedDateUtterance); 5200 * }</pre> 5201 * <p> 5202 * If an {@link AccessibilityDelegate} has been specified via calling 5203 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5204 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 5205 * is responsible for handling this call. 5206 * </p> 5207 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5208 * information to the event, in case the default implementation has basic information to add. 5209 * </p> 5210 * 5211 * @param event The accessibility event which to populate. 5212 * 5213 * @see #sendAccessibilityEvent(int) 5214 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5215 */ 5216 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5217 if (mAccessibilityDelegate != null) { 5218 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 5219 } else { 5220 onPopulateAccessibilityEventInternal(event); 5221 } 5222 } 5223 5224 /** 5225 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 5226 * 5227 * Note: Called from the default {@link AccessibilityDelegate}. 5228 */ 5229 void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5230 } 5231 5232 /** 5233 * Initializes an {@link AccessibilityEvent} with information about 5234 * this View which is the event source. In other words, the source of 5235 * an accessibility event is the view whose state change triggered firing 5236 * the event. 5237 * <p> 5238 * Example: Setting the password property of an event in addition 5239 * to properties set by the super implementation: 5240 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5241 * super.onInitializeAccessibilityEvent(event); 5242 * event.setPassword(true); 5243 * }</pre> 5244 * <p> 5245 * If an {@link AccessibilityDelegate} has been specified via calling 5246 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5247 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 5248 * is responsible for handling this call. 5249 * </p> 5250 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5251 * information to the event, in case the default implementation has basic information to add. 5252 * </p> 5253 * @param event The event to initialize. 5254 * 5255 * @see #sendAccessibilityEvent(int) 5256 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5257 */ 5258 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5259 if (mAccessibilityDelegate != null) { 5260 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 5261 } else { 5262 onInitializeAccessibilityEventInternal(event); 5263 } 5264 } 5265 5266 /** 5267 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 5268 * 5269 * Note: Called from the default {@link AccessibilityDelegate}. 5270 */ 5271 void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 5272 event.setSource(this); 5273 event.setClassName(View.class.getName()); 5274 event.setPackageName(getContext().getPackageName()); 5275 event.setEnabled(isEnabled()); 5276 event.setContentDescription(mContentDescription); 5277 5278 switch (event.getEventType()) { 5279 case AccessibilityEvent.TYPE_VIEW_FOCUSED: { 5280 ArrayList<View> focusablesTempList = (mAttachInfo != null) 5281 ? mAttachInfo.mTempArrayList : new ArrayList<View>(); 5282 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL); 5283 event.setItemCount(focusablesTempList.size()); 5284 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 5285 if (mAttachInfo != null) { 5286 focusablesTempList.clear(); 5287 } 5288 } break; 5289 case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: { 5290 CharSequence text = getIterableTextForAccessibility(); 5291 if (text != null && text.length() > 0) { 5292 event.setFromIndex(getAccessibilitySelectionStart()); 5293 event.setToIndex(getAccessibilitySelectionEnd()); 5294 event.setItemCount(text.length()); 5295 } 5296 } break; 5297 } 5298 } 5299 5300 /** 5301 * Returns an {@link AccessibilityNodeInfo} representing this view from the 5302 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 5303 * This method is responsible for obtaining an accessibility node info from a 5304 * pool of reusable instances and calling 5305 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 5306 * initialize the former. 5307 * <p> 5308 * Note: The client is responsible for recycling the obtained instance by calling 5309 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 5310 * </p> 5311 * 5312 * @return A populated {@link AccessibilityNodeInfo}. 5313 * 5314 * @see AccessibilityNodeInfo 5315 */ 5316 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 5317 if (mAccessibilityDelegate != null) { 5318 return mAccessibilityDelegate.createAccessibilityNodeInfo(this); 5319 } else { 5320 return createAccessibilityNodeInfoInternal(); 5321 } 5322 } 5323 5324 /** 5325 * @see #createAccessibilityNodeInfo() 5326 */ 5327 AccessibilityNodeInfo createAccessibilityNodeInfoInternal() { 5328 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 5329 if (provider != null) { 5330 return provider.createAccessibilityNodeInfo(View.NO_ID); 5331 } else { 5332 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 5333 onInitializeAccessibilityNodeInfo(info); 5334 return info; 5335 } 5336 } 5337 5338 /** 5339 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 5340 * The base implementation sets: 5341 * <ul> 5342 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 5343 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 5344 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 5345 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 5346 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 5347 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 5348 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 5349 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 5350 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 5351 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 5352 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 5353 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 5354 * </ul> 5355 * <p> 5356 * Subclasses should override this method, call the super implementation, 5357 * and set additional attributes. 5358 * </p> 5359 * <p> 5360 * If an {@link AccessibilityDelegate} has been specified via calling 5361 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5362 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 5363 * is responsible for handling this call. 5364 * </p> 5365 * 5366 * @param info The instance to initialize. 5367 */ 5368 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 5369 if (mAccessibilityDelegate != null) { 5370 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 5371 } else { 5372 onInitializeAccessibilityNodeInfoInternal(info); 5373 } 5374 } 5375 5376 /** 5377 * Gets the location of this view in screen coordintates. 5378 * 5379 * @param outRect The output location 5380 */ 5381 void getBoundsOnScreen(Rect outRect) { 5382 if (mAttachInfo == null) { 5383 return; 5384 } 5385 5386 RectF position = mAttachInfo.mTmpTransformRect; 5387 position.set(0, 0, mRight - mLeft, mBottom - mTop); 5388 5389 if (!hasIdentityMatrix()) { 5390 getMatrix().mapRect(position); 5391 } 5392 5393 position.offset(mLeft, mTop); 5394 5395 ViewParent parent = mParent; 5396 while (parent instanceof View) { 5397 View parentView = (View) parent; 5398 5399 position.offset(-parentView.mScrollX, -parentView.mScrollY); 5400 5401 if (!parentView.hasIdentityMatrix()) { 5402 parentView.getMatrix().mapRect(position); 5403 } 5404 5405 position.offset(parentView.mLeft, parentView.mTop); 5406 5407 parent = parentView.mParent; 5408 } 5409 5410 if (parent instanceof ViewRootImpl) { 5411 ViewRootImpl viewRootImpl = (ViewRootImpl) parent; 5412 position.offset(0, -viewRootImpl.mCurScrollY); 5413 } 5414 5415 position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 5416 5417 outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f), 5418 (int) (position.right + 0.5f), (int) (position.bottom + 0.5f)); 5419 } 5420 5421 /** 5422 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 5423 * 5424 * Note: Called from the default {@link AccessibilityDelegate}. 5425 */ 5426 void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 5427 Rect bounds = mAttachInfo.mTmpInvalRect; 5428 5429 getDrawingRect(bounds); 5430 info.setBoundsInParent(bounds); 5431 5432 getBoundsOnScreen(bounds); 5433 info.setBoundsInScreen(bounds); 5434 5435 ViewParent parent = getParentForAccessibility(); 5436 if (parent instanceof View) { 5437 info.setParent((View) parent); 5438 } 5439 5440 if (mID != View.NO_ID) { 5441 View rootView = getRootView(); 5442 if (rootView == null) { 5443 rootView = this; 5444 } 5445 View label = rootView.findLabelForView(this, mID); 5446 if (label != null) { 5447 info.setLabeledBy(label); 5448 } 5449 5450 if ((mAttachInfo.mAccessibilityFetchFlags 5451 & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0 5452 && Resources.resourceHasPackage(mID)) { 5453 try { 5454 String viewId = getResources().getResourceName(mID); 5455 info.setViewIdResourceName(viewId); 5456 } catch (Resources.NotFoundException nfe) { 5457 /* ignore */ 5458 } 5459 } 5460 } 5461 5462 if (mLabelForId != View.NO_ID) { 5463 View rootView = getRootView(); 5464 if (rootView == null) { 5465 rootView = this; 5466 } 5467 View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId); 5468 if (labeled != null) { 5469 info.setLabelFor(labeled); 5470 } 5471 } 5472 5473 info.setVisibleToUser(isVisibleToUser()); 5474 5475 info.setPackageName(mContext.getPackageName()); 5476 info.setClassName(View.class.getName()); 5477 info.setContentDescription(getContentDescription()); 5478 5479 info.setEnabled(isEnabled()); 5480 info.setClickable(isClickable()); 5481 info.setFocusable(isFocusable()); 5482 info.setFocused(isFocused()); 5483 info.setAccessibilityFocused(isAccessibilityFocused()); 5484 info.setSelected(isSelected()); 5485 info.setLongClickable(isLongClickable()); 5486 info.setLiveRegion(getAccessibilityLiveRegion()); 5487 5488 // TODO: These make sense only if we are in an AdapterView but all 5489 // views can be selected. Maybe from accessibility perspective 5490 // we should report as selectable view in an AdapterView. 5491 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 5492 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 5493 5494 if (isFocusable()) { 5495 if (isFocused()) { 5496 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 5497 } else { 5498 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 5499 } 5500 } 5501 5502 if (!isAccessibilityFocused()) { 5503 info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); 5504 } else { 5505 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); 5506 } 5507 5508 if (isClickable() && isEnabled()) { 5509 info.addAction(AccessibilityNodeInfo.ACTION_CLICK); 5510 } 5511 5512 if (isLongClickable() && isEnabled()) { 5513 info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); 5514 } 5515 5516 CharSequence text = getIterableTextForAccessibility(); 5517 if (text != null && text.length() > 0) { 5518 info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd()); 5519 5520 info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION); 5521 info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); 5522 info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); 5523 info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER 5524 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD 5525 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH); 5526 } 5527 } 5528 5529 private View findLabelForView(View view, int labeledId) { 5530 if (mMatchLabelForPredicate == null) { 5531 mMatchLabelForPredicate = new MatchLabelForPredicate(); 5532 } 5533 mMatchLabelForPredicate.mLabeledId = labeledId; 5534 return findViewByPredicateInsideOut(view, mMatchLabelForPredicate); 5535 } 5536 5537 /** 5538 * Computes whether this view is visible to the user. Such a view is 5539 * attached, visible, all its predecessors are visible, it is not clipped 5540 * entirely by its predecessors, and has an alpha greater than zero. 5541 * 5542 * @return Whether the view is visible on the screen. 5543 * 5544 * @hide 5545 */ 5546 protected boolean isVisibleToUser() { 5547 return isVisibleToUser(null); 5548 } 5549 5550 /** 5551 * Computes whether the given portion of this view is visible to the user. 5552 * Such a view is attached, visible, all its predecessors are visible, 5553 * has an alpha greater than zero, and the specified portion is not 5554 * clipped entirely by its predecessors. 5555 * 5556 * @param boundInView the portion of the view to test; coordinates should be relative; may be 5557 * <code>null</code>, and the entire view will be tested in this case. 5558 * When <code>true</code> is returned by the function, the actual visible 5559 * region will be stored in this parameter; that is, if boundInView is fully 5560 * contained within the view, no modification will be made, otherwise regions 5561 * outside of the visible area of the view will be clipped. 5562 * 5563 * @return Whether the specified portion of the view is visible on the screen. 5564 * 5565 * @hide 5566 */ 5567 protected boolean isVisibleToUser(Rect boundInView) { 5568 if (mAttachInfo != null) { 5569 // Attached to invisible window means this view is not visible. 5570 if (mAttachInfo.mWindowVisibility != View.VISIBLE) { 5571 return false; 5572 } 5573 // An invisible predecessor or one with alpha zero means 5574 // that this view is not visible to the user. 5575 Object current = this; 5576 while (current instanceof View) { 5577 View view = (View) current; 5578 // We have attach info so this view is attached and there is no 5579 // need to check whether we reach to ViewRootImpl on the way up. 5580 if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 || 5581 view.getVisibility() != VISIBLE) { 5582 return false; 5583 } 5584 current = view.mParent; 5585 } 5586 // Check if the view is entirely covered by its predecessors. 5587 Rect visibleRect = mAttachInfo.mTmpInvalRect; 5588 Point offset = mAttachInfo.mPoint; 5589 if (!getGlobalVisibleRect(visibleRect, offset)) { 5590 return false; 5591 } 5592 // Check if the visible portion intersects the rectangle of interest. 5593 if (boundInView != null) { 5594 visibleRect.offset(-offset.x, -offset.y); 5595 return boundInView.intersect(visibleRect); 5596 } 5597 return true; 5598 } 5599 return false; 5600 } 5601 5602 /** 5603 * Returns the delegate for implementing accessibility support via 5604 * composition. For more details see {@link AccessibilityDelegate}. 5605 * 5606 * @return The delegate, or null if none set. 5607 * 5608 * @hide 5609 */ 5610 public AccessibilityDelegate getAccessibilityDelegate() { 5611 return mAccessibilityDelegate; 5612 } 5613 5614 /** 5615 * Sets a delegate for implementing accessibility support via composition as 5616 * opposed to inheritance. The delegate's primary use is for implementing 5617 * backwards compatible widgets. For more details see {@link AccessibilityDelegate}. 5618 * 5619 * @param delegate The delegate instance. 5620 * 5621 * @see AccessibilityDelegate 5622 */ 5623 public void setAccessibilityDelegate(AccessibilityDelegate delegate) { 5624 mAccessibilityDelegate = delegate; 5625 } 5626 5627 /** 5628 * Gets the provider for managing a virtual view hierarchy rooted at this View 5629 * and reported to {@link android.accessibilityservice.AccessibilityService}s 5630 * that explore the window content. 5631 * <p> 5632 * If this method returns an instance, this instance is responsible for managing 5633 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this 5634 * View including the one representing the View itself. Similarly the returned 5635 * instance is responsible for performing accessibility actions on any virtual 5636 * view or the root view itself. 5637 * </p> 5638 * <p> 5639 * If an {@link AccessibilityDelegate} has been specified via calling 5640 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5641 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)} 5642 * is responsible for handling this call. 5643 * </p> 5644 * 5645 * @return The provider. 5646 * 5647 * @see AccessibilityNodeProvider 5648 */ 5649 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 5650 if (mAccessibilityDelegate != null) { 5651 return mAccessibilityDelegate.getAccessibilityNodeProvider(this); 5652 } else { 5653 return null; 5654 } 5655 } 5656 5657 /** 5658 * Gets the unique identifier of this view on the screen for accessibility purposes. 5659 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 5660 * 5661 * @return The view accessibility id. 5662 * 5663 * @hide 5664 */ 5665 public int getAccessibilityViewId() { 5666 if (mAccessibilityViewId == NO_ID) { 5667 mAccessibilityViewId = sNextAccessibilityViewId++; 5668 } 5669 return mAccessibilityViewId; 5670 } 5671 5672 /** 5673 * Gets the unique identifier of the window in which this View reseides. 5674 * 5675 * @return The window accessibility id. 5676 * 5677 * @hide 5678 */ 5679 public int getAccessibilityWindowId() { 5680 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId 5681 : AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 5682 } 5683 5684 /** 5685 * Gets the {@link View} description. It briefly describes the view and is 5686 * primarily used for accessibility support. Set this property to enable 5687 * better accessibility support for your application. This is especially 5688 * true for views that do not have textual representation (For example, 5689 * ImageButton). 5690 * 5691 * @return The content description. 5692 * 5693 * @attr ref android.R.styleable#View_contentDescription 5694 */ 5695 @ViewDebug.ExportedProperty(category = "accessibility") 5696 public CharSequence getContentDescription() { 5697 return mContentDescription; 5698 } 5699 5700 /** 5701 * Sets the {@link View} description. It briefly describes the view and is 5702 * primarily used for accessibility support. Set this property to enable 5703 * better accessibility support for your application. This is especially 5704 * true for views that do not have textual representation (For example, 5705 * ImageButton). 5706 * 5707 * @param contentDescription The content description. 5708 * 5709 * @attr ref android.R.styleable#View_contentDescription 5710 */ 5711 @RemotableViewMethod 5712 public void setContentDescription(CharSequence contentDescription) { 5713 if (mContentDescription == null) { 5714 if (contentDescription == null) { 5715 return; 5716 } 5717 } else if (mContentDescription.equals(contentDescription)) { 5718 return; 5719 } 5720 mContentDescription = contentDescription; 5721 final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0; 5722 if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 5723 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); 5724 notifySubtreeAccessibilityStateChangedIfNeeded(); 5725 } else { 5726 notifyViewAccessibilityStateChangedIfNeeded( 5727 AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION); 5728 } 5729 } 5730 5731 /** 5732 * Gets the id of a view for which this view serves as a label for 5733 * accessibility purposes. 5734 * 5735 * @return The labeled view id. 5736 */ 5737 @ViewDebug.ExportedProperty(category = "accessibility") 5738 public int getLabelFor() { 5739 return mLabelForId; 5740 } 5741 5742 /** 5743 * Sets the id of a view for which this view serves as a label for 5744 * accessibility purposes. 5745 * 5746 * @param id The labeled view id. 5747 */ 5748 @RemotableViewMethod 5749 public void setLabelFor(int id) { 5750 mLabelForId = id; 5751 if (mLabelForId != View.NO_ID 5752 && mID == View.NO_ID) { 5753 mID = generateViewId(); 5754 } 5755 } 5756 5757 /** 5758 * Invoked whenever this view loses focus, either by losing window focus or by losing 5759 * focus within its window. This method can be used to clear any state tied to the 5760 * focus. For instance, if a button is held pressed with the trackball and the window 5761 * loses focus, this method can be used to cancel the press. 5762 * 5763 * Subclasses of View overriding this method should always call super.onFocusLost(). 5764 * 5765 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 5766 * @see #onWindowFocusChanged(boolean) 5767 * 5768 * @hide pending API council approval 5769 */ 5770 protected void onFocusLost() { 5771 resetPressedState(); 5772 } 5773 5774 private void resetPressedState() { 5775 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 5776 return; 5777 } 5778 5779 if (isPressed()) { 5780 setPressed(false); 5781 5782 if (!mHasPerformedLongPress) { 5783 removeLongPressCallback(); 5784 } 5785 } 5786 } 5787 5788 /** 5789 * Returns true if this view has focus 5790 * 5791 * @return True if this view has focus, false otherwise. 5792 */ 5793 @ViewDebug.ExportedProperty(category = "focus") 5794 public boolean isFocused() { 5795 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 5796 } 5797 5798 /** 5799 * Find the view in the hierarchy rooted at this view that currently has 5800 * focus. 5801 * 5802 * @return The view that currently has focus, or null if no focused view can 5803 * be found. 5804 */ 5805 public View findFocus() { 5806 return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null; 5807 } 5808 5809 /** 5810 * Indicates whether this view is one of the set of scrollable containers in 5811 * its window. 5812 * 5813 * @return whether this view is one of the set of scrollable containers in 5814 * its window 5815 * 5816 * @attr ref android.R.styleable#View_isScrollContainer 5817 */ 5818 public boolean isScrollContainer() { 5819 return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0; 5820 } 5821 5822 /** 5823 * Change whether this view is one of the set of scrollable containers in 5824 * its window. This will be used to determine whether the window can 5825 * resize or must pan when a soft input area is open -- scrollable 5826 * containers allow the window to use resize mode since the container 5827 * will appropriately shrink. 5828 * 5829 * @attr ref android.R.styleable#View_isScrollContainer 5830 */ 5831 public void setScrollContainer(boolean isScrollContainer) { 5832 if (isScrollContainer) { 5833 if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) { 5834 mAttachInfo.mScrollContainers.add(this); 5835 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 5836 } 5837 mPrivateFlags |= PFLAG_SCROLL_CONTAINER; 5838 } else { 5839 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 5840 mAttachInfo.mScrollContainers.remove(this); 5841 } 5842 mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED); 5843 } 5844 } 5845 5846 /** 5847 * Returns the quality of the drawing cache. 5848 * 5849 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5850 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5851 * 5852 * @see #setDrawingCacheQuality(int) 5853 * @see #setDrawingCacheEnabled(boolean) 5854 * @see #isDrawingCacheEnabled() 5855 * 5856 * @attr ref android.R.styleable#View_drawingCacheQuality 5857 */ 5858 @DrawingCacheQuality 5859 public int getDrawingCacheQuality() { 5860 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 5861 } 5862 5863 /** 5864 * Set the drawing cache quality of this view. This value is used only when the 5865 * drawing cache is enabled 5866 * 5867 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5868 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5869 * 5870 * @see #getDrawingCacheQuality() 5871 * @see #setDrawingCacheEnabled(boolean) 5872 * @see #isDrawingCacheEnabled() 5873 * 5874 * @attr ref android.R.styleable#View_drawingCacheQuality 5875 */ 5876 public void setDrawingCacheQuality(@DrawingCacheQuality int quality) { 5877 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 5878 } 5879 5880 /** 5881 * Returns whether the screen should remain on, corresponding to the current 5882 * value of {@link #KEEP_SCREEN_ON}. 5883 * 5884 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 5885 * 5886 * @see #setKeepScreenOn(boolean) 5887 * 5888 * @attr ref android.R.styleable#View_keepScreenOn 5889 */ 5890 public boolean getKeepScreenOn() { 5891 return (mViewFlags & KEEP_SCREEN_ON) != 0; 5892 } 5893 5894 /** 5895 * Controls whether the screen should remain on, modifying the 5896 * value of {@link #KEEP_SCREEN_ON}. 5897 * 5898 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 5899 * 5900 * @see #getKeepScreenOn() 5901 * 5902 * @attr ref android.R.styleable#View_keepScreenOn 5903 */ 5904 public void setKeepScreenOn(boolean keepScreenOn) { 5905 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 5906 } 5907 5908 /** 5909 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5910 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5911 * 5912 * @attr ref android.R.styleable#View_nextFocusLeft 5913 */ 5914 public int getNextFocusLeftId() { 5915 return mNextFocusLeftId; 5916 } 5917 5918 /** 5919 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5920 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 5921 * decide automatically. 5922 * 5923 * @attr ref android.R.styleable#View_nextFocusLeft 5924 */ 5925 public void setNextFocusLeftId(int nextFocusLeftId) { 5926 mNextFocusLeftId = nextFocusLeftId; 5927 } 5928 5929 /** 5930 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 5931 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5932 * 5933 * @attr ref android.R.styleable#View_nextFocusRight 5934 */ 5935 public int getNextFocusRightId() { 5936 return mNextFocusRightId; 5937 } 5938 5939 /** 5940 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 5941 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 5942 * decide automatically. 5943 * 5944 * @attr ref android.R.styleable#View_nextFocusRight 5945 */ 5946 public void setNextFocusRightId(int nextFocusRightId) { 5947 mNextFocusRightId = nextFocusRightId; 5948 } 5949 5950 /** 5951 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 5952 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5953 * 5954 * @attr ref android.R.styleable#View_nextFocusUp 5955 */ 5956 public int getNextFocusUpId() { 5957 return mNextFocusUpId; 5958 } 5959 5960 /** 5961 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 5962 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 5963 * decide automatically. 5964 * 5965 * @attr ref android.R.styleable#View_nextFocusUp 5966 */ 5967 public void setNextFocusUpId(int nextFocusUpId) { 5968 mNextFocusUpId = nextFocusUpId; 5969 } 5970 5971 /** 5972 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 5973 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5974 * 5975 * @attr ref android.R.styleable#View_nextFocusDown 5976 */ 5977 public int getNextFocusDownId() { 5978 return mNextFocusDownId; 5979 } 5980 5981 /** 5982 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 5983 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 5984 * decide automatically. 5985 * 5986 * @attr ref android.R.styleable#View_nextFocusDown 5987 */ 5988 public void setNextFocusDownId(int nextFocusDownId) { 5989 mNextFocusDownId = nextFocusDownId; 5990 } 5991 5992 /** 5993 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 5994 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5995 * 5996 * @attr ref android.R.styleable#View_nextFocusForward 5997 */ 5998 public int getNextFocusForwardId() { 5999 return mNextFocusForwardId; 6000 } 6001 6002 /** 6003 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 6004 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 6005 * decide automatically. 6006 * 6007 * @attr ref android.R.styleable#View_nextFocusForward 6008 */ 6009 public void setNextFocusForwardId(int nextFocusForwardId) { 6010 mNextFocusForwardId = nextFocusForwardId; 6011 } 6012 6013 /** 6014 * Returns the visibility of this view and all of its ancestors 6015 * 6016 * @return True if this view and all of its ancestors are {@link #VISIBLE} 6017 */ 6018 public boolean isShown() { 6019 View current = this; 6020 //noinspection ConstantConditions 6021 do { 6022 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 6023 return false; 6024 } 6025 ViewParent parent = current.mParent; 6026 if (parent == null) { 6027 return false; // We are not attached to the view root 6028 } 6029 if (!(parent instanceof View)) { 6030 return true; 6031 } 6032 current = (View) parent; 6033 } while (current != null); 6034 6035 return false; 6036 } 6037 6038 /** 6039 * Called by the view hierarchy when the content insets for a window have 6040 * changed, to allow it to adjust its content to fit within those windows. 6041 * The content insets tell you the space that the status bar, input method, 6042 * and other system windows infringe on the application's window. 6043 * 6044 * <p>You do not normally need to deal with this function, since the default 6045 * window decoration given to applications takes care of applying it to the 6046 * content of the window. If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 6047 * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case, 6048 * and your content can be placed under those system elements. You can then 6049 * use this method within your view hierarchy if you have parts of your UI 6050 * which you would like to ensure are not being covered. 6051 * 6052 * <p>The default implementation of this method simply applies the content 6053 * insets to the view's padding, consuming that content (modifying the 6054 * insets to be 0), and returning true. This behavior is off by default, but can 6055 * be enabled through {@link #setFitsSystemWindows(boolean)}. 6056 * 6057 * <p>This function's traversal down the hierarchy is depth-first. The same content 6058 * insets object is propagated down the hierarchy, so any changes made to it will 6059 * be seen by all following views (including potentially ones above in 6060 * the hierarchy since this is a depth-first traversal). The first view 6061 * that returns true will abort the entire traversal. 6062 * 6063 * <p>The default implementation works well for a situation where it is 6064 * used with a container that covers the entire window, allowing it to 6065 * apply the appropriate insets to its content on all edges. If you need 6066 * a more complicated layout (such as two different views fitting system 6067 * windows, one on the top of the window, and one on the bottom), 6068 * you can override the method and handle the insets however you would like. 6069 * Note that the insets provided by the framework are always relative to the 6070 * far edges of the window, not accounting for the location of the called view 6071 * within that window. (In fact when this method is called you do not yet know 6072 * where the layout will place the view, as it is done before layout happens.) 6073 * 6074 * <p>Note: unlike many View methods, there is no dispatch phase to this 6075 * call. If you are overriding it in a ViewGroup and want to allow the 6076 * call to continue to your children, you must be sure to call the super 6077 * implementation. 6078 * 6079 * <p>Here is a sample layout that makes use of fitting system windows 6080 * to have controls for a video view placed inside of the window decorations 6081 * that it hides and shows. This can be used with code like the second 6082 * sample (video player) shown in {@link #setSystemUiVisibility(int)}. 6083 * 6084 * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete} 6085 * 6086 * @param insets Current content insets of the window. Prior to 6087 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify 6088 * the insets or else you and Android will be unhappy. 6089 * 6090 * @return {@code true} if this view applied the insets and it should not 6091 * continue propagating further down the hierarchy, {@code false} otherwise. 6092 * @see #getFitsSystemWindows() 6093 * @see #setFitsSystemWindows(boolean) 6094 * @see #setSystemUiVisibility(int) 6095 * 6096 * @deprecated As of API XX use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply 6097 * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use 6098 * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)} 6099 * to implement handling their own insets. 6100 */ 6101 protected boolean fitSystemWindows(Rect insets) { 6102 if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) { 6103 // If we're not in the process of dispatching the newer apply insets call, 6104 // that means we're not in the compatibility path. Dispatch into the newer 6105 // apply insets path and take things from there. 6106 try { 6107 mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS; 6108 return !dispatchApplyWindowInsets(new WindowInsets(insets)).hasInsets(); 6109 } finally { 6110 mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS; 6111 } 6112 } else { 6113 // We're being called from the newer apply insets path. 6114 // Perform the standard fallback behavior. 6115 return fitSystemWindowsInt(insets); 6116 } 6117 } 6118 6119 private boolean fitSystemWindowsInt(Rect insets) { 6120 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 6121 mUserPaddingStart = UNDEFINED_PADDING; 6122 mUserPaddingEnd = UNDEFINED_PADDING; 6123 Rect localInsets = sThreadLocal.get(); 6124 if (localInsets == null) { 6125 localInsets = new Rect(); 6126 sThreadLocal.set(localInsets); 6127 } 6128 boolean res = computeFitSystemWindows(insets, localInsets); 6129 mUserPaddingLeftInitial = localInsets.left; 6130 mUserPaddingRightInitial = localInsets.right; 6131 internalSetPadding(localInsets.left, localInsets.top, 6132 localInsets.right, localInsets.bottom); 6133 return res; 6134 } 6135 return false; 6136 } 6137 6138 /** 6139 * Called when the view should apply {@link WindowInsets} according to its internal policy. 6140 * 6141 * <p>This method should be overridden by views that wish to apply a policy different from or 6142 * in addition to the default behavior. Clients that wish to force a view subtree 6143 * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p> 6144 * 6145 * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set 6146 * it will be called during dispatch instead of this method. The listener may optionally 6147 * call this method from its own implementation if it wishes to apply the view's default 6148 * insets policy in addition to its own.</p> 6149 * 6150 * <p>Implementations of this method should either return the insets parameter unchanged 6151 * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed 6152 * that this view applied itself. This allows new inset types added in future platform 6153 * versions to pass through existing implementations unchanged without being erroneously 6154 * consumed.</p> 6155 * 6156 * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows} 6157 * property is set then the view will consume the system window insets and apply them 6158 * as padding for the view.</p> 6159 * 6160 * @param insets Insets to apply 6161 * @return The supplied insets with any applied insets consumed 6162 */ 6163 public WindowInsets onApplyWindowInsets(WindowInsets insets) { 6164 if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) { 6165 // We weren't called from within a direct call to fitSystemWindows, 6166 // call into it as a fallback in case we're in a class that overrides it 6167 // and has logic to perform. 6168 if (fitSystemWindows(insets.getSystemWindowInsets())) { 6169 return insets.consumeSystemWindowInsets(); 6170 } 6171 } else { 6172 // We were called from within a direct call to fitSystemWindows. 6173 if (fitSystemWindowsInt(insets.getSystemWindowInsets())) { 6174 return insets.consumeSystemWindowInsets(); 6175 } 6176 } 6177 return insets; 6178 } 6179 6180 /** 6181 * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying 6182 * window insets to this view. The listener's 6183 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 6184 * method will be called instead of the view's 6185 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 6186 * 6187 * @param listener Listener to set 6188 * 6189 * @see #onApplyWindowInsets(WindowInsets) 6190 */ 6191 public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) { 6192 getListenerInfo().mOnApplyWindowInsetsListener = listener; 6193 } 6194 6195 /** 6196 * Request to apply the given window insets to this view or another view in its subtree. 6197 * 6198 * <p>This method should be called by clients wishing to apply insets corresponding to areas 6199 * obscured by window decorations or overlays. This can include the status and navigation bars, 6200 * action bars, input methods and more. New inset categories may be added in the future. 6201 * The method returns the insets provided minus any that were applied by this view or its 6202 * children.</p> 6203 * 6204 * <p>Clients wishing to provide custom behavior should override the 6205 * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a 6206 * {@link OnApplyWindowInsetsListener} via the 6207 * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener} 6208 * method.</p> 6209 * 6210 * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method. 6211 * </p> 6212 * 6213 * @param insets Insets to apply 6214 * @return The provided insets minus the insets that were consumed 6215 */ 6216 public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) { 6217 try { 6218 mPrivateFlags3 |= PFLAG3_APPLYING_INSETS; 6219 if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) { 6220 return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets); 6221 } else { 6222 return onApplyWindowInsets(insets); 6223 } 6224 } finally { 6225 mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS; 6226 } 6227 } 6228 6229 /** 6230 * @hide Compute the insets that should be consumed by this view and the ones 6231 * that should propagate to those under it. 6232 */ 6233 protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) { 6234 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 6235 || mAttachInfo == null 6236 || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0 6237 && !mAttachInfo.mOverscanRequested)) { 6238 outLocalInsets.set(inoutInsets); 6239 inoutInsets.set(0, 0, 0, 0); 6240 return true; 6241 } else { 6242 // The application wants to take care of fitting system window for 6243 // the content... however we still need to take care of any overscan here. 6244 final Rect overscan = mAttachInfo.mOverscanInsets; 6245 outLocalInsets.set(overscan); 6246 inoutInsets.left -= overscan.left; 6247 inoutInsets.top -= overscan.top; 6248 inoutInsets.right -= overscan.right; 6249 inoutInsets.bottom -= overscan.bottom; 6250 return false; 6251 } 6252 } 6253 6254 /** 6255 * Sets whether or not this view should account for system screen decorations 6256 * such as the status bar and inset its content; that is, controlling whether 6257 * the default implementation of {@link #fitSystemWindows(Rect)} will be 6258 * executed. See that method for more details. 6259 * 6260 * <p>Note that if you are providing your own implementation of 6261 * {@link #fitSystemWindows(Rect)}, then there is no need to set this 6262 * flag to true -- your implementation will be overriding the default 6263 * implementation that checks this flag. 6264 * 6265 * @param fitSystemWindows If true, then the default implementation of 6266 * {@link #fitSystemWindows(Rect)} will be executed. 6267 * 6268 * @attr ref android.R.styleable#View_fitsSystemWindows 6269 * @see #getFitsSystemWindows() 6270 * @see #fitSystemWindows(Rect) 6271 * @see #setSystemUiVisibility(int) 6272 */ 6273 public void setFitsSystemWindows(boolean fitSystemWindows) { 6274 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 6275 } 6276 6277 /** 6278 * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method 6279 * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)} 6280 * will be executed. 6281 * 6282 * @return {@code true} if the default implementation of 6283 * {@link #fitSystemWindows(Rect)} will be executed. 6284 * 6285 * @attr ref android.R.styleable#View_fitsSystemWindows 6286 * @see #setFitsSystemWindows(boolean) 6287 * @see #fitSystemWindows(Rect) 6288 * @see #setSystemUiVisibility(int) 6289 */ 6290 public boolean getFitsSystemWindows() { 6291 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 6292 } 6293 6294 /** @hide */ 6295 public boolean fitsSystemWindows() { 6296 return getFitsSystemWindows(); 6297 } 6298 6299 /** 6300 * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed. 6301 * @deprecated Use {@link #requestApplyInsets()} for newer platform versions. 6302 */ 6303 public void requestFitSystemWindows() { 6304 if (mParent != null) { 6305 mParent.requestFitSystemWindows(); 6306 } 6307 } 6308 6309 /** 6310 * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed. 6311 */ 6312 public void requestApplyInsets() { 6313 requestFitSystemWindows(); 6314 } 6315 6316 /** 6317 * For use by PhoneWindow to make its own system window fitting optional. 6318 * @hide 6319 */ 6320 public void makeOptionalFitsSystemWindows() { 6321 setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS); 6322 } 6323 6324 /** 6325 * Returns the visibility status for this view. 6326 * 6327 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 6328 * @attr ref android.R.styleable#View_visibility 6329 */ 6330 @ViewDebug.ExportedProperty(mapping = { 6331 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 6332 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 6333 @ViewDebug.IntToString(from = GONE, to = "GONE") 6334 }) 6335 @Visibility 6336 public int getVisibility() { 6337 return mViewFlags & VISIBILITY_MASK; 6338 } 6339 6340 /** 6341 * Set the enabled state of this view. 6342 * 6343 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 6344 * @attr ref android.R.styleable#View_visibility 6345 */ 6346 @RemotableViewMethod 6347 public void setVisibility(@Visibility int visibility) { 6348 setFlags(visibility, VISIBILITY_MASK); 6349 if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false); 6350 } 6351 6352 /** 6353 * Returns the enabled status for this view. The interpretation of the 6354 * enabled state varies by subclass. 6355 * 6356 * @return True if this view is enabled, false otherwise. 6357 */ 6358 @ViewDebug.ExportedProperty 6359 public boolean isEnabled() { 6360 return (mViewFlags & ENABLED_MASK) == ENABLED; 6361 } 6362 6363 /** 6364 * Set the enabled state of this view. The interpretation of the enabled 6365 * state varies by subclass. 6366 * 6367 * @param enabled True if this view is enabled, false otherwise. 6368 */ 6369 @RemotableViewMethod 6370 public void setEnabled(boolean enabled) { 6371 if (enabled == isEnabled()) return; 6372 6373 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 6374 6375 /* 6376 * The View most likely has to change its appearance, so refresh 6377 * the drawable state. 6378 */ 6379 refreshDrawableState(); 6380 6381 // Invalidate too, since the default behavior for views is to be 6382 // be drawn at 50% alpha rather than to change the drawable. 6383 invalidate(true); 6384 6385 if (!enabled) { 6386 cancelPendingInputEvents(); 6387 } 6388 } 6389 6390 /** 6391 * Set whether this view can receive the focus. 6392 * 6393 * Setting this to false will also ensure that this view is not focusable 6394 * in touch mode. 6395 * 6396 * @param focusable If true, this view can receive the focus. 6397 * 6398 * @see #setFocusableInTouchMode(boolean) 6399 * @attr ref android.R.styleable#View_focusable 6400 */ 6401 public void setFocusable(boolean focusable) { 6402 if (!focusable) { 6403 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 6404 } 6405 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 6406 } 6407 6408 /** 6409 * Set whether this view can receive focus while in touch mode. 6410 * 6411 * Setting this to true will also ensure that this view is focusable. 6412 * 6413 * @param focusableInTouchMode If true, this view can receive the focus while 6414 * in touch mode. 6415 * 6416 * @see #setFocusable(boolean) 6417 * @attr ref android.R.styleable#View_focusableInTouchMode 6418 */ 6419 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 6420 // Focusable in touch mode should always be set before the focusable flag 6421 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 6422 // which, in touch mode, will not successfully request focus on this view 6423 // because the focusable in touch mode flag is not set 6424 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 6425 if (focusableInTouchMode) { 6426 setFlags(FOCUSABLE, FOCUSABLE_MASK); 6427 } 6428 } 6429 6430 /** 6431 * Set whether this view should have sound effects enabled for events such as 6432 * clicking and touching. 6433 * 6434 * <p>You may wish to disable sound effects for a view if you already play sounds, 6435 * for instance, a dial key that plays dtmf tones. 6436 * 6437 * @param soundEffectsEnabled whether sound effects are enabled for this view. 6438 * @see #isSoundEffectsEnabled() 6439 * @see #playSoundEffect(int) 6440 * @attr ref android.R.styleable#View_soundEffectsEnabled 6441 */ 6442 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 6443 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 6444 } 6445 6446 /** 6447 * @return whether this view should have sound effects enabled for events such as 6448 * clicking and touching. 6449 * 6450 * @see #setSoundEffectsEnabled(boolean) 6451 * @see #playSoundEffect(int) 6452 * @attr ref android.R.styleable#View_soundEffectsEnabled 6453 */ 6454 @ViewDebug.ExportedProperty 6455 public boolean isSoundEffectsEnabled() { 6456 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 6457 } 6458 6459 /** 6460 * Set whether this view should have haptic feedback for events such as 6461 * long presses. 6462 * 6463 * <p>You may wish to disable haptic feedback if your view already controls 6464 * its own haptic feedback. 6465 * 6466 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 6467 * @see #isHapticFeedbackEnabled() 6468 * @see #performHapticFeedback(int) 6469 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6470 */ 6471 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 6472 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 6473 } 6474 6475 /** 6476 * @return whether this view should have haptic feedback enabled for events 6477 * long presses. 6478 * 6479 * @see #setHapticFeedbackEnabled(boolean) 6480 * @see #performHapticFeedback(int) 6481 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6482 */ 6483 @ViewDebug.ExportedProperty 6484 public boolean isHapticFeedbackEnabled() { 6485 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 6486 } 6487 6488 /** 6489 * Returns the layout direction for this view. 6490 * 6491 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 6492 * {@link #LAYOUT_DIRECTION_RTL}, 6493 * {@link #LAYOUT_DIRECTION_INHERIT} or 6494 * {@link #LAYOUT_DIRECTION_LOCALE}. 6495 * 6496 * @attr ref android.R.styleable#View_layoutDirection 6497 * 6498 * @hide 6499 */ 6500 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6501 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 6502 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 6503 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 6504 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 6505 }) 6506 @LayoutDir 6507 public int getRawLayoutDirection() { 6508 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 6509 } 6510 6511 /** 6512 * Set the layout direction for this view. This will propagate a reset of layout direction 6513 * resolution to the view's children and resolve layout direction for this view. 6514 * 6515 * @param layoutDirection the layout direction to set. Should be one of: 6516 * 6517 * {@link #LAYOUT_DIRECTION_LTR}, 6518 * {@link #LAYOUT_DIRECTION_RTL}, 6519 * {@link #LAYOUT_DIRECTION_INHERIT}, 6520 * {@link #LAYOUT_DIRECTION_LOCALE}. 6521 * 6522 * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution 6523 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 6524 * will return the default {@link #LAYOUT_DIRECTION_LTR}. 6525 * 6526 * @attr ref android.R.styleable#View_layoutDirection 6527 */ 6528 @RemotableViewMethod 6529 public void setLayoutDirection(@LayoutDir int layoutDirection) { 6530 if (getRawLayoutDirection() != layoutDirection) { 6531 // Reset the current layout direction and the resolved one 6532 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK; 6533 resetRtlProperties(); 6534 // Set the new layout direction (filtered) 6535 mPrivateFlags2 |= 6536 ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK); 6537 // We need to resolve all RTL properties as they all depend on layout direction 6538 resolveRtlPropertiesIfNeeded(); 6539 requestLayout(); 6540 invalidate(true); 6541 } 6542 } 6543 6544 /** 6545 * Returns the resolved layout direction for this view. 6546 * 6547 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 6548 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL. 6549 * 6550 * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version 6551 * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}. 6552 * 6553 * @attr ref android.R.styleable#View_layoutDirection 6554 */ 6555 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6556 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 6557 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 6558 }) 6559 @ResolvedLayoutDir 6560 public int getLayoutDirection() { 6561 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 6562 if (targetSdkVersion < JELLY_BEAN_MR1) { 6563 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 6564 return LAYOUT_DIRECTION_RESOLVED_DEFAULT; 6565 } 6566 return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) == 6567 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 6568 } 6569 6570 /** 6571 * Indicates whether or not this view's layout is right-to-left. This is resolved from 6572 * layout attribute and/or the inherited value from the parent 6573 * 6574 * @return true if the layout is right-to-left. 6575 * 6576 * @hide 6577 */ 6578 @ViewDebug.ExportedProperty(category = "layout") 6579 public boolean isLayoutRtl() { 6580 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL); 6581 } 6582 6583 /** 6584 * Indicates whether the view is currently tracking transient state that the 6585 * app should not need to concern itself with saving and restoring, but that 6586 * the framework should take special note to preserve when possible. 6587 * 6588 * <p>A view with transient state cannot be trivially rebound from an external 6589 * data source, such as an adapter binding item views in a list. This may be 6590 * because the view is performing an animation, tracking user selection 6591 * of content, or similar.</p> 6592 * 6593 * @return true if the view has transient state 6594 */ 6595 @ViewDebug.ExportedProperty(category = "layout") 6596 public boolean hasTransientState() { 6597 return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE; 6598 } 6599 6600 /** 6601 * Set whether this view is currently tracking transient state that the 6602 * framework should attempt to preserve when possible. This flag is reference counted, 6603 * so every call to setHasTransientState(true) should be paired with a later call 6604 * to setHasTransientState(false). 6605 * 6606 * <p>A view with transient state cannot be trivially rebound from an external 6607 * data source, such as an adapter binding item views in a list. This may be 6608 * because the view is performing an animation, tracking user selection 6609 * of content, or similar.</p> 6610 * 6611 * @param hasTransientState true if this view has transient state 6612 */ 6613 public void setHasTransientState(boolean hasTransientState) { 6614 mTransientStateCount = hasTransientState ? mTransientStateCount + 1 : 6615 mTransientStateCount - 1; 6616 if (mTransientStateCount < 0) { 6617 mTransientStateCount = 0; 6618 Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " + 6619 "unmatched pair of setHasTransientState calls"); 6620 } else if ((hasTransientState && mTransientStateCount == 1) || 6621 (!hasTransientState && mTransientStateCount == 0)) { 6622 // update flag if we've just incremented up from 0 or decremented down to 0 6623 mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) | 6624 (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0); 6625 if (mParent != null) { 6626 try { 6627 mParent.childHasTransientStateChanged(this, hasTransientState); 6628 } catch (AbstractMethodError e) { 6629 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 6630 " does not fully implement ViewParent", e); 6631 } 6632 } 6633 } 6634 } 6635 6636 /** 6637 * Returns true if this view is currently attached to a window. 6638 */ 6639 public boolean isAttachedToWindow() { 6640 return mAttachInfo != null; 6641 } 6642 6643 /** 6644 * Returns true if this view has been through at least one layout since it 6645 * was last attached to or detached from a window. 6646 */ 6647 public boolean isLaidOut() { 6648 return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT; 6649 } 6650 6651 /** 6652 * If this view doesn't do any drawing on its own, set this flag to 6653 * allow further optimizations. By default, this flag is not set on 6654 * View, but could be set on some View subclasses such as ViewGroup. 6655 * 6656 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 6657 * you should clear this flag. 6658 * 6659 * @param willNotDraw whether or not this View draw on its own 6660 */ 6661 public void setWillNotDraw(boolean willNotDraw) { 6662 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 6663 } 6664 6665 /** 6666 * Returns whether or not this View draws on its own. 6667 * 6668 * @return true if this view has nothing to draw, false otherwise 6669 */ 6670 @ViewDebug.ExportedProperty(category = "drawing") 6671 public boolean willNotDraw() { 6672 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 6673 } 6674 6675 /** 6676 * When a View's drawing cache is enabled, drawing is redirected to an 6677 * offscreen bitmap. Some views, like an ImageView, must be able to 6678 * bypass this mechanism if they already draw a single bitmap, to avoid 6679 * unnecessary usage of the memory. 6680 * 6681 * @param willNotCacheDrawing true if this view does not cache its 6682 * drawing, false otherwise 6683 */ 6684 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 6685 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 6686 } 6687 6688 /** 6689 * Returns whether or not this View can cache its drawing or not. 6690 * 6691 * @return true if this view does not cache its drawing, false otherwise 6692 */ 6693 @ViewDebug.ExportedProperty(category = "drawing") 6694 public boolean willNotCacheDrawing() { 6695 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 6696 } 6697 6698 /** 6699 * Indicates whether this view reacts to click events or not. 6700 * 6701 * @return true if the view is clickable, false otherwise 6702 * 6703 * @see #setClickable(boolean) 6704 * @attr ref android.R.styleable#View_clickable 6705 */ 6706 @ViewDebug.ExportedProperty 6707 public boolean isClickable() { 6708 return (mViewFlags & CLICKABLE) == CLICKABLE; 6709 } 6710 6711 /** 6712 * Enables or disables click events for this view. When a view 6713 * is clickable it will change its state to "pressed" on every click. 6714 * Subclasses should set the view clickable to visually react to 6715 * user's clicks. 6716 * 6717 * @param clickable true to make the view clickable, false otherwise 6718 * 6719 * @see #isClickable() 6720 * @attr ref android.R.styleable#View_clickable 6721 */ 6722 public void setClickable(boolean clickable) { 6723 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 6724 } 6725 6726 /** 6727 * Indicates whether this view reacts to long click events or not. 6728 * 6729 * @return true if the view is long clickable, false otherwise 6730 * 6731 * @see #setLongClickable(boolean) 6732 * @attr ref android.R.styleable#View_longClickable 6733 */ 6734 public boolean isLongClickable() { 6735 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 6736 } 6737 6738 /** 6739 * Enables or disables long click events for this view. When a view is long 6740 * clickable it reacts to the user holding down the button for a longer 6741 * duration than a tap. This event can either launch the listener or a 6742 * context menu. 6743 * 6744 * @param longClickable true to make the view long clickable, false otherwise 6745 * @see #isLongClickable() 6746 * @attr ref android.R.styleable#View_longClickable 6747 */ 6748 public void setLongClickable(boolean longClickable) { 6749 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 6750 } 6751 6752 /** 6753 * Sets the pressed state for this view and provides a touch coordinate for 6754 * animation hinting. 6755 * 6756 * @param pressed Pass true to set the View's internal state to "pressed", 6757 * or false to reverts the View's internal state from a 6758 * previously set "pressed" state. 6759 * @param x The x coordinate of the touch that caused the press 6760 * @param y The y coordinate of the touch that caused the press 6761 */ 6762 private void setPressed(boolean pressed, float x, float y) { 6763 if (pressed) { 6764 setHotspot(x, y); 6765 } 6766 6767 setPressed(pressed); 6768 } 6769 6770 /** 6771 * Sets the pressed state for this view. 6772 * 6773 * @see #isClickable() 6774 * @see #setClickable(boolean) 6775 * 6776 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 6777 * the View's internal state from a previously set "pressed" state. 6778 */ 6779 public void setPressed(boolean pressed) { 6780 final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED); 6781 6782 if (pressed) { 6783 mPrivateFlags |= PFLAG_PRESSED; 6784 } else { 6785 mPrivateFlags &= ~PFLAG_PRESSED; 6786 } 6787 6788 if (needsRefresh) { 6789 refreshDrawableState(); 6790 } 6791 dispatchSetPressed(pressed); 6792 } 6793 6794 /** 6795 * Dispatch setPressed to all of this View's children. 6796 * 6797 * @see #setPressed(boolean) 6798 * 6799 * @param pressed The new pressed state 6800 */ 6801 protected void dispatchSetPressed(boolean pressed) { 6802 } 6803 6804 /** 6805 * Indicates whether the view is currently in pressed state. Unless 6806 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 6807 * the pressed state. 6808 * 6809 * @see #setPressed(boolean) 6810 * @see #isClickable() 6811 * @see #setClickable(boolean) 6812 * 6813 * @return true if the view is currently pressed, false otherwise 6814 */ 6815 public boolean isPressed() { 6816 return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED; 6817 } 6818 6819 /** 6820 * Indicates whether this view will save its state (that is, 6821 * whether its {@link #onSaveInstanceState} method will be called). 6822 * 6823 * @return Returns true if the view state saving is enabled, else false. 6824 * 6825 * @see #setSaveEnabled(boolean) 6826 * @attr ref android.R.styleable#View_saveEnabled 6827 */ 6828 public boolean isSaveEnabled() { 6829 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 6830 } 6831 6832 /** 6833 * Controls whether the saving of this view's state is 6834 * enabled (that is, whether its {@link #onSaveInstanceState} method 6835 * will be called). Note that even if freezing is enabled, the 6836 * view still must have an id assigned to it (via {@link #setId(int)}) 6837 * for its state to be saved. This flag can only disable the 6838 * saving of this view; any child views may still have their state saved. 6839 * 6840 * @param enabled Set to false to <em>disable</em> state saving, or true 6841 * (the default) to allow it. 6842 * 6843 * @see #isSaveEnabled() 6844 * @see #setId(int) 6845 * @see #onSaveInstanceState() 6846 * @attr ref android.R.styleable#View_saveEnabled 6847 */ 6848 public void setSaveEnabled(boolean enabled) { 6849 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 6850 } 6851 6852 /** 6853 * Gets whether the framework should discard touches when the view's 6854 * window is obscured by another visible window. 6855 * Refer to the {@link View} security documentation for more details. 6856 * 6857 * @return True if touch filtering is enabled. 6858 * 6859 * @see #setFilterTouchesWhenObscured(boolean) 6860 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 6861 */ 6862 @ViewDebug.ExportedProperty 6863 public boolean getFilterTouchesWhenObscured() { 6864 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 6865 } 6866 6867 /** 6868 * Sets whether the framework should discard touches when the view's 6869 * window is obscured by another visible window. 6870 * Refer to the {@link View} security documentation for more details. 6871 * 6872 * @param enabled True if touch filtering should be enabled. 6873 * 6874 * @see #getFilterTouchesWhenObscured 6875 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 6876 */ 6877 public void setFilterTouchesWhenObscured(boolean enabled) { 6878 setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0, 6879 FILTER_TOUCHES_WHEN_OBSCURED); 6880 } 6881 6882 /** 6883 * Indicates whether the entire hierarchy under this view will save its 6884 * state when a state saving traversal occurs from its parent. The default 6885 * is true; if false, these views will not be saved unless 6886 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 6887 * 6888 * @return Returns true if the view state saving from parent is enabled, else false. 6889 * 6890 * @see #setSaveFromParentEnabled(boolean) 6891 */ 6892 public boolean isSaveFromParentEnabled() { 6893 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 6894 } 6895 6896 /** 6897 * Controls whether the entire hierarchy under this view will save its 6898 * state when a state saving traversal occurs from its parent. The default 6899 * is true; if false, these views will not be saved unless 6900 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 6901 * 6902 * @param enabled Set to false to <em>disable</em> state saving, or true 6903 * (the default) to allow it. 6904 * 6905 * @see #isSaveFromParentEnabled() 6906 * @see #setId(int) 6907 * @see #onSaveInstanceState() 6908 */ 6909 public void setSaveFromParentEnabled(boolean enabled) { 6910 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 6911 } 6912 6913 6914 /** 6915 * Returns whether this View is able to take focus. 6916 * 6917 * @return True if this view can take focus, or false otherwise. 6918 * @attr ref android.R.styleable#View_focusable 6919 */ 6920 @ViewDebug.ExportedProperty(category = "focus") 6921 public final boolean isFocusable() { 6922 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 6923 } 6924 6925 /** 6926 * When a view is focusable, it may not want to take focus when in touch mode. 6927 * For example, a button would like focus when the user is navigating via a D-pad 6928 * so that the user can click on it, but once the user starts touching the screen, 6929 * the button shouldn't take focus 6930 * @return Whether the view is focusable in touch mode. 6931 * @attr ref android.R.styleable#View_focusableInTouchMode 6932 */ 6933 @ViewDebug.ExportedProperty 6934 public final boolean isFocusableInTouchMode() { 6935 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 6936 } 6937 6938 /** 6939 * Find the nearest view in the specified direction that can take focus. 6940 * This does not actually give focus to that view. 6941 * 6942 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 6943 * 6944 * @return The nearest focusable in the specified direction, or null if none 6945 * can be found. 6946 */ 6947 public View focusSearch(@FocusRealDirection int direction) { 6948 if (mParent != null) { 6949 return mParent.focusSearch(this, direction); 6950 } else { 6951 return null; 6952 } 6953 } 6954 6955 /** 6956 * This method is the last chance for the focused view and its ancestors to 6957 * respond to an arrow key. This is called when the focused view did not 6958 * consume the key internally, nor could the view system find a new view in 6959 * the requested direction to give focus to. 6960 * 6961 * @param focused The currently focused view. 6962 * @param direction The direction focus wants to move. One of FOCUS_UP, 6963 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 6964 * @return True if the this view consumed this unhandled move. 6965 */ 6966 public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) { 6967 return false; 6968 } 6969 6970 /** 6971 * If a user manually specified the next view id for a particular direction, 6972 * use the root to look up the view. 6973 * @param root The root view of the hierarchy containing this view. 6974 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 6975 * or FOCUS_BACKWARD. 6976 * @return The user specified next view, or null if there is none. 6977 */ 6978 View findUserSetNextFocus(View root, @FocusDirection int direction) { 6979 switch (direction) { 6980 case FOCUS_LEFT: 6981 if (mNextFocusLeftId == View.NO_ID) return null; 6982 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 6983 case FOCUS_RIGHT: 6984 if (mNextFocusRightId == View.NO_ID) return null; 6985 return findViewInsideOutShouldExist(root, mNextFocusRightId); 6986 case FOCUS_UP: 6987 if (mNextFocusUpId == View.NO_ID) return null; 6988 return findViewInsideOutShouldExist(root, mNextFocusUpId); 6989 case FOCUS_DOWN: 6990 if (mNextFocusDownId == View.NO_ID) return null; 6991 return findViewInsideOutShouldExist(root, mNextFocusDownId); 6992 case FOCUS_FORWARD: 6993 if (mNextFocusForwardId == View.NO_ID) return null; 6994 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 6995 case FOCUS_BACKWARD: { 6996 if (mID == View.NO_ID) return null; 6997 final int id = mID; 6998 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 6999 @Override 7000 public boolean apply(View t) { 7001 return t.mNextFocusForwardId == id; 7002 } 7003 }); 7004 } 7005 } 7006 return null; 7007 } 7008 7009 private View findViewInsideOutShouldExist(View root, int id) { 7010 if (mMatchIdPredicate == null) { 7011 mMatchIdPredicate = new MatchIdPredicate(); 7012 } 7013 mMatchIdPredicate.mId = id; 7014 View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate); 7015 if (result == null) { 7016 Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id); 7017 } 7018 return result; 7019 } 7020 7021 /** 7022 * Find and return all focusable views that are descendants of this view, 7023 * possibly including this view if it is focusable itself. 7024 * 7025 * @param direction The direction of the focus 7026 * @return A list of focusable views 7027 */ 7028 public ArrayList<View> getFocusables(@FocusDirection int direction) { 7029 ArrayList<View> result = new ArrayList<View>(24); 7030 addFocusables(result, direction); 7031 return result; 7032 } 7033 7034 /** 7035 * Add any focusable views that are descendants of this view (possibly 7036 * including this view if it is focusable itself) to views. If we are in touch mode, 7037 * only add views that are also focusable in touch mode. 7038 * 7039 * @param views Focusable views found so far 7040 * @param direction The direction of the focus 7041 */ 7042 public void addFocusables(ArrayList<View> views, @FocusDirection int direction) { 7043 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 7044 } 7045 7046 /** 7047 * Adds any focusable views that are descendants of this view (possibly 7048 * including this view if it is focusable itself) to views. This method 7049 * adds all focusable views regardless if we are in touch mode or 7050 * only views focusable in touch mode if we are in touch mode or 7051 * only views that can take accessibility focus if accessibility is enabeld 7052 * depending on the focusable mode paramater. 7053 * 7054 * @param views Focusable views found so far or null if all we are interested is 7055 * the number of focusables. 7056 * @param direction The direction of the focus. 7057 * @param focusableMode The type of focusables to be added. 7058 * 7059 * @see #FOCUSABLES_ALL 7060 * @see #FOCUSABLES_TOUCH_MODE 7061 */ 7062 public void addFocusables(ArrayList<View> views, @FocusDirection int direction, 7063 @FocusableMode int focusableMode) { 7064 if (views == null) { 7065 return; 7066 } 7067 if (!isFocusable()) { 7068 return; 7069 } 7070 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE 7071 && isInTouchMode() && !isFocusableInTouchMode()) { 7072 return; 7073 } 7074 views.add(this); 7075 } 7076 7077 /** 7078 * Finds the Views that contain given text. The containment is case insensitive. 7079 * The search is performed by either the text that the View renders or the content 7080 * description that describes the view for accessibility purposes and the view does 7081 * not render or both. Clients can specify how the search is to be performed via 7082 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 7083 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 7084 * 7085 * @param outViews The output list of matching Views. 7086 * @param searched The text to match against. 7087 * 7088 * @see #FIND_VIEWS_WITH_TEXT 7089 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 7090 * @see #setContentDescription(CharSequence) 7091 */ 7092 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, 7093 @FindViewFlags int flags) { 7094 if (getAccessibilityNodeProvider() != null) { 7095 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 7096 outViews.add(this); 7097 } 7098 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 7099 && (searched != null && searched.length() > 0) 7100 && (mContentDescription != null && mContentDescription.length() > 0)) { 7101 String searchedLowerCase = searched.toString().toLowerCase(); 7102 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 7103 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 7104 outViews.add(this); 7105 } 7106 } 7107 } 7108 7109 /** 7110 * Find and return all touchable views that are descendants of this view, 7111 * possibly including this view if it is touchable itself. 7112 * 7113 * @return A list of touchable views 7114 */ 7115 public ArrayList<View> getTouchables() { 7116 ArrayList<View> result = new ArrayList<View>(); 7117 addTouchables(result); 7118 return result; 7119 } 7120 7121 /** 7122 * Add any touchable views that are descendants of this view (possibly 7123 * including this view if it is touchable itself) to views. 7124 * 7125 * @param views Touchable views found so far 7126 */ 7127 public void addTouchables(ArrayList<View> views) { 7128 final int viewFlags = mViewFlags; 7129 7130 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 7131 && (viewFlags & ENABLED_MASK) == ENABLED) { 7132 views.add(this); 7133 } 7134 } 7135 7136 /** 7137 * Returns whether this View is accessibility focused. 7138 * 7139 * @return True if this View is accessibility focused. 7140 */ 7141 public boolean isAccessibilityFocused() { 7142 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0; 7143 } 7144 7145 /** 7146 * Call this to try to give accessibility focus to this view. 7147 * 7148 * A view will not actually take focus if {@link AccessibilityManager#isEnabled()} 7149 * returns false or the view is no visible or the view already has accessibility 7150 * focus. 7151 * 7152 * See also {@link #focusSearch(int)}, which is what you call to say that you 7153 * have focus, and you want your parent to look for the next one. 7154 * 7155 * @return Whether this view actually took accessibility focus. 7156 * 7157 * @hide 7158 */ 7159 public boolean requestAccessibilityFocus() { 7160 AccessibilityManager manager = AccessibilityManager.getInstance(mContext); 7161 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 7162 return false; 7163 } 7164 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7165 return false; 7166 } 7167 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) { 7168 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED; 7169 ViewRootImpl viewRootImpl = getViewRootImpl(); 7170 if (viewRootImpl != null) { 7171 viewRootImpl.setAccessibilityFocus(this, null); 7172 } 7173 Rect rect = (mAttachInfo != null) ? mAttachInfo.mTmpInvalRect : new Rect(); 7174 getDrawingRect(rect); 7175 requestRectangleOnScreen(rect, false); 7176 invalidate(); 7177 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); 7178 return true; 7179 } 7180 return false; 7181 } 7182 7183 /** 7184 * Call this to try to clear accessibility focus of this view. 7185 * 7186 * See also {@link #focusSearch(int)}, which is what you call to say that you 7187 * have focus, and you want your parent to look for the next one. 7188 * 7189 * @hide 7190 */ 7191 public void clearAccessibilityFocus() { 7192 clearAccessibilityFocusNoCallbacks(); 7193 // Clear the global reference of accessibility focus if this 7194 // view or any of its descendants had accessibility focus. 7195 ViewRootImpl viewRootImpl = getViewRootImpl(); 7196 if (viewRootImpl != null) { 7197 View focusHost = viewRootImpl.getAccessibilityFocusedHost(); 7198 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 7199 viewRootImpl.setAccessibilityFocus(null, null); 7200 } 7201 } 7202 } 7203 7204 private void sendAccessibilityHoverEvent(int eventType) { 7205 // Since we are not delivering to a client accessibility events from not 7206 // important views (unless the clinet request that) we need to fire the 7207 // event from the deepest view exposed to the client. As a consequence if 7208 // the user crosses a not exposed view the client will see enter and exit 7209 // of the exposed predecessor followed by and enter and exit of that same 7210 // predecessor when entering and exiting the not exposed descendant. This 7211 // is fine since the client has a clear idea which view is hovered at the 7212 // price of a couple more events being sent. This is a simple and 7213 // working solution. 7214 View source = this; 7215 while (true) { 7216 if (source.includeForAccessibility()) { 7217 source.sendAccessibilityEvent(eventType); 7218 return; 7219 } 7220 ViewParent parent = source.getParent(); 7221 if (parent instanceof View) { 7222 source = (View) parent; 7223 } else { 7224 return; 7225 } 7226 } 7227 } 7228 7229 /** 7230 * Clears accessibility focus without calling any callback methods 7231 * normally invoked in {@link #clearAccessibilityFocus()}. This method 7232 * is used for clearing accessibility focus when giving this focus to 7233 * another view. 7234 */ 7235 void clearAccessibilityFocusNoCallbacks() { 7236 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 7237 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 7238 invalidate(); 7239 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); 7240 } 7241 } 7242 7243 /** 7244 * Call this to try to give focus to a specific view or to one of its 7245 * descendants. 7246 * 7247 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7248 * false), or if it is focusable and it is not focusable in touch mode 7249 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7250 * 7251 * See also {@link #focusSearch(int)}, which is what you call to say that you 7252 * have focus, and you want your parent to look for the next one. 7253 * 7254 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 7255 * {@link #FOCUS_DOWN} and <code>null</code>. 7256 * 7257 * @return Whether this view or one of its descendants actually took focus. 7258 */ 7259 public final boolean requestFocus() { 7260 return requestFocus(View.FOCUS_DOWN); 7261 } 7262 7263 /** 7264 * Call this to try to give focus to a specific view or to one of its 7265 * descendants and give it a hint about what direction focus is heading. 7266 * 7267 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7268 * false), or if it is focusable and it is not focusable in touch mode 7269 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7270 * 7271 * See also {@link #focusSearch(int)}, which is what you call to say that you 7272 * have focus, and you want your parent to look for the next one. 7273 * 7274 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 7275 * <code>null</code> set for the previously focused rectangle. 7276 * 7277 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7278 * @return Whether this view or one of its descendants actually took focus. 7279 */ 7280 public final boolean requestFocus(int direction) { 7281 return requestFocus(direction, null); 7282 } 7283 7284 /** 7285 * Call this to try to give focus to a specific view or to one of its descendants 7286 * and give it hints about the direction and a specific rectangle that the focus 7287 * is coming from. The rectangle can help give larger views a finer grained hint 7288 * about where focus is coming from, and therefore, where to show selection, or 7289 * forward focus change internally. 7290 * 7291 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7292 * false), or if it is focusable and it is not focusable in touch mode 7293 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7294 * 7295 * A View will not take focus if it is not visible. 7296 * 7297 * A View will not take focus if one of its parents has 7298 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 7299 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 7300 * 7301 * See also {@link #focusSearch(int)}, which is what you call to say that you 7302 * have focus, and you want your parent to look for the next one. 7303 * 7304 * You may wish to override this method if your custom {@link View} has an internal 7305 * {@link View} that it wishes to forward the request to. 7306 * 7307 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7308 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 7309 * to give a finer grained hint about where focus is coming from. May be null 7310 * if there is no hint. 7311 * @return Whether this view or one of its descendants actually took focus. 7312 */ 7313 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 7314 return requestFocusNoSearch(direction, previouslyFocusedRect); 7315 } 7316 7317 private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) { 7318 // need to be focusable 7319 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 7320 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7321 return false; 7322 } 7323 7324 // need to be focusable in touch mode if in touch mode 7325 if (isInTouchMode() && 7326 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 7327 return false; 7328 } 7329 7330 // need to not have any parents blocking us 7331 if (hasAncestorThatBlocksDescendantFocus()) { 7332 return false; 7333 } 7334 7335 handleFocusGainInternal(direction, previouslyFocusedRect); 7336 return true; 7337 } 7338 7339 /** 7340 * Call this to try to give focus to a specific view or to one of its descendants. This is a 7341 * special variant of {@link #requestFocus() } that will allow views that are not focuable in 7342 * touch mode to request focus when they are touched. 7343 * 7344 * @return Whether this view or one of its descendants actually took focus. 7345 * 7346 * @see #isInTouchMode() 7347 * 7348 */ 7349 public final boolean requestFocusFromTouch() { 7350 // Leave touch mode if we need to 7351 if (isInTouchMode()) { 7352 ViewRootImpl viewRoot = getViewRootImpl(); 7353 if (viewRoot != null) { 7354 viewRoot.ensureTouchMode(false); 7355 } 7356 } 7357 return requestFocus(View.FOCUS_DOWN); 7358 } 7359 7360 /** 7361 * @return Whether any ancestor of this view blocks descendant focus. 7362 */ 7363 private boolean hasAncestorThatBlocksDescendantFocus() { 7364 ViewParent ancestor = mParent; 7365 while (ancestor instanceof ViewGroup) { 7366 final ViewGroup vgAncestor = (ViewGroup) ancestor; 7367 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) { 7368 return true; 7369 } else { 7370 ancestor = vgAncestor.getParent(); 7371 } 7372 } 7373 return false; 7374 } 7375 7376 /** 7377 * Gets the mode for determining whether this View is important for accessibility 7378 * which is if it fires accessibility events and if it is reported to 7379 * accessibility services that query the screen. 7380 * 7381 * @return The mode for determining whether a View is important for accessibility. 7382 * 7383 * @attr ref android.R.styleable#View_importantForAccessibility 7384 * 7385 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 7386 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 7387 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 7388 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 7389 */ 7390 @ViewDebug.ExportedProperty(category = "accessibility", mapping = { 7391 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"), 7392 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"), 7393 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"), 7394 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS, 7395 to = "noHideDescendants") 7396 }) 7397 public int getImportantForAccessibility() { 7398 return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 7399 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 7400 } 7401 7402 /** 7403 * Sets the live region mode for this view. This indicates to accessibility 7404 * services whether they should automatically notify the user about changes 7405 * to the view's content description or text, or to the content descriptions 7406 * or text of the view's children (where applicable). 7407 * <p> 7408 * For example, in a login screen with a TextView that displays an "incorrect 7409 * password" notification, that view should be marked as a live region with 7410 * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 7411 * <p> 7412 * To disable change notifications for this view, use 7413 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region 7414 * mode for most views. 7415 * <p> 7416 * To indicate that the user should be notified of changes, use 7417 * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 7418 * <p> 7419 * If the view's changes should interrupt ongoing speech and notify the user 7420 * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}. 7421 * 7422 * @param mode The live region mode for this view, one of: 7423 * <ul> 7424 * <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE} 7425 * <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE} 7426 * <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE} 7427 * </ul> 7428 * @attr ref android.R.styleable#View_accessibilityLiveRegion 7429 */ 7430 public void setAccessibilityLiveRegion(int mode) { 7431 if (mode != getAccessibilityLiveRegion()) { 7432 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 7433 mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT) 7434 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 7435 notifyViewAccessibilityStateChangedIfNeeded( 7436 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7437 } 7438 } 7439 7440 /** 7441 * Gets the live region mode for this View. 7442 * 7443 * @return The live region mode for the view. 7444 * 7445 * @attr ref android.R.styleable#View_accessibilityLiveRegion 7446 * 7447 * @see #setAccessibilityLiveRegion(int) 7448 */ 7449 public int getAccessibilityLiveRegion() { 7450 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK) 7451 >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 7452 } 7453 7454 /** 7455 * Sets how to determine whether this view is important for accessibility 7456 * which is if it fires accessibility events and if it is reported to 7457 * accessibility services that query the screen. 7458 * 7459 * @param mode How to determine whether this view is important for accessibility. 7460 * 7461 * @attr ref android.R.styleable#View_importantForAccessibility 7462 * 7463 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 7464 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 7465 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 7466 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 7467 */ 7468 public void setImportantForAccessibility(int mode) { 7469 final int oldMode = getImportantForAccessibility(); 7470 if (mode != oldMode) { 7471 // If we're moving between AUTO and another state, we might not need 7472 // to send a subtree changed notification. We'll store the computed 7473 // importance, since we'll need to check it later to make sure. 7474 final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO 7475 || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO; 7476 final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility(); 7477 mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 7478 mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT) 7479 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 7480 if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) { 7481 notifySubtreeAccessibilityStateChangedIfNeeded(); 7482 } else { 7483 notifyViewAccessibilityStateChangedIfNeeded( 7484 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7485 } 7486 } 7487 } 7488 7489 /** 7490 * Computes whether this view should be exposed for accessibility. In 7491 * general, views that are interactive or provide information are exposed 7492 * while views that serve only as containers are hidden. 7493 * <p> 7494 * If an ancestor of this view has importance 7495 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method 7496 * returns <code>false</code>. 7497 * <p> 7498 * Otherwise, the value is computed according to the view's 7499 * {@link #getImportantForAccessibility()} value: 7500 * <ol> 7501 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or 7502 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false 7503 * </code> 7504 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code> 7505 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if 7506 * view satisfies any of the following: 7507 * <ul> 7508 * <li>Is actionable, e.g. {@link #isClickable()}, 7509 * {@link #isLongClickable()}, or {@link #isFocusable()} 7510 * <li>Has an {@link AccessibilityDelegate} 7511 * <li>Has an interaction listener, e.g. {@link OnTouchListener}, 7512 * {@link OnKeyListener}, etc. 7513 * <li>Is an accessibility live region, e.g. 7514 * {@link #getAccessibilityLiveRegion()} is not 7515 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. 7516 * </ul> 7517 * </ol> 7518 * 7519 * @return Whether the view is exposed for accessibility. 7520 * @see #setImportantForAccessibility(int) 7521 * @see #getImportantForAccessibility() 7522 */ 7523 public boolean isImportantForAccessibility() { 7524 final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 7525 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 7526 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO 7527 || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 7528 return false; 7529 } 7530 7531 // Check parent mode to ensure we're not hidden. 7532 ViewParent parent = mParent; 7533 while (parent instanceof View) { 7534 if (((View) parent).getImportantForAccessibility() 7535 == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 7536 return false; 7537 } 7538 parent = parent.getParent(); 7539 } 7540 7541 return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility() 7542 || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null 7543 || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE; 7544 } 7545 7546 /** 7547 * Gets the parent for accessibility purposes. Note that the parent for 7548 * accessibility is not necessary the immediate parent. It is the first 7549 * predecessor that is important for accessibility. 7550 * 7551 * @return The parent for accessibility purposes. 7552 */ 7553 public ViewParent getParentForAccessibility() { 7554 if (mParent instanceof View) { 7555 View parentView = (View) mParent; 7556 if (parentView.includeForAccessibility()) { 7557 return mParent; 7558 } else { 7559 return mParent.getParentForAccessibility(); 7560 } 7561 } 7562 return null; 7563 } 7564 7565 /** 7566 * Adds the children of a given View for accessibility. Since some Views are 7567 * not important for accessibility the children for accessibility are not 7568 * necessarily direct children of the view, rather they are the first level of 7569 * descendants important for accessibility. 7570 * 7571 * @param children The list of children for accessibility. 7572 */ 7573 public void addChildrenForAccessibility(ArrayList<View> children) { 7574 7575 } 7576 7577 /** 7578 * Whether to regard this view for accessibility. A view is regarded for 7579 * accessibility if it is important for accessibility or the querying 7580 * accessibility service has explicitly requested that view not 7581 * important for accessibility are regarded. 7582 * 7583 * @return Whether to regard the view for accessibility. 7584 * 7585 * @hide 7586 */ 7587 public boolean includeForAccessibility() { 7588 if (mAttachInfo != null) { 7589 return (mAttachInfo.mAccessibilityFetchFlags 7590 & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0 7591 || isImportantForAccessibility(); 7592 } 7593 return false; 7594 } 7595 7596 /** 7597 * Returns whether the View is considered actionable from 7598 * accessibility perspective. Such view are important for 7599 * accessibility. 7600 * 7601 * @return True if the view is actionable for accessibility. 7602 * 7603 * @hide 7604 */ 7605 public boolean isActionableForAccessibility() { 7606 return (isClickable() || isLongClickable() || isFocusable()); 7607 } 7608 7609 /** 7610 * Returns whether the View has registered callbacks which makes it 7611 * important for accessibility. 7612 * 7613 * @return True if the view is actionable for accessibility. 7614 */ 7615 private boolean hasListenersForAccessibility() { 7616 ListenerInfo info = getListenerInfo(); 7617 return mTouchDelegate != null || info.mOnKeyListener != null 7618 || info.mOnTouchListener != null || info.mOnGenericMotionListener != null 7619 || info.mOnHoverListener != null || info.mOnDragListener != null; 7620 } 7621 7622 /** 7623 * Notifies that the accessibility state of this view changed. The change 7624 * is local to this view and does not represent structural changes such 7625 * as children and parent. For example, the view became focusable. The 7626 * notification is at at most once every 7627 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 7628 * to avoid unnecessary load to the system. Also once a view has a pending 7629 * notification this method is a NOP until the notification has been sent. 7630 * 7631 * @hide 7632 */ 7633 public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) { 7634 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 7635 return; 7636 } 7637 if (mSendViewStateChangedAccessibilityEvent == null) { 7638 mSendViewStateChangedAccessibilityEvent = 7639 new SendViewStateChangedAccessibilityEvent(); 7640 } 7641 mSendViewStateChangedAccessibilityEvent.runOrPost(changeType); 7642 } 7643 7644 /** 7645 * Notifies that the accessibility state of this view changed. The change 7646 * is *not* local to this view and does represent structural changes such 7647 * as children and parent. For example, the view size changed. The 7648 * notification is at at most once every 7649 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 7650 * to avoid unnecessary load to the system. Also once a view has a pending 7651 * notifucation this method is a NOP until the notification has been sent. 7652 * 7653 * @hide 7654 */ 7655 public void notifySubtreeAccessibilityStateChangedIfNeeded() { 7656 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 7657 return; 7658 } 7659 if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) { 7660 mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 7661 if (mParent != null) { 7662 try { 7663 mParent.notifySubtreeAccessibilityStateChanged( 7664 this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE); 7665 } catch (AbstractMethodError e) { 7666 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 7667 " does not fully implement ViewParent", e); 7668 } 7669 } 7670 } 7671 } 7672 7673 /** 7674 * Reset the flag indicating the accessibility state of the subtree rooted 7675 * at this view changed. 7676 */ 7677 void resetSubtreeAccessibilityStateChanged() { 7678 mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 7679 } 7680 7681 /** 7682 * Performs the specified accessibility action on the view. For 7683 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 7684 * <p> 7685 * If an {@link AccessibilityDelegate} has been specified via calling 7686 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 7687 * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)} 7688 * is responsible for handling this call. 7689 * </p> 7690 * 7691 * @param action The action to perform. 7692 * @param arguments Optional action arguments. 7693 * @return Whether the action was performed. 7694 */ 7695 public boolean performAccessibilityAction(int action, Bundle arguments) { 7696 if (mAccessibilityDelegate != null) { 7697 return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments); 7698 } else { 7699 return performAccessibilityActionInternal(action, arguments); 7700 } 7701 } 7702 7703 /** 7704 * @see #performAccessibilityAction(int, Bundle) 7705 * 7706 * Note: Called from the default {@link AccessibilityDelegate}. 7707 */ 7708 boolean performAccessibilityActionInternal(int action, Bundle arguments) { 7709 switch (action) { 7710 case AccessibilityNodeInfo.ACTION_CLICK: { 7711 if (isClickable()) { 7712 performClick(); 7713 return true; 7714 } 7715 } break; 7716 case AccessibilityNodeInfo.ACTION_LONG_CLICK: { 7717 if (isLongClickable()) { 7718 performLongClick(); 7719 return true; 7720 } 7721 } break; 7722 case AccessibilityNodeInfo.ACTION_FOCUS: { 7723 if (!hasFocus()) { 7724 // Get out of touch mode since accessibility 7725 // wants to move focus around. 7726 getViewRootImpl().ensureTouchMode(false); 7727 return requestFocus(); 7728 } 7729 } break; 7730 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 7731 if (hasFocus()) { 7732 clearFocus(); 7733 return !isFocused(); 7734 } 7735 } break; 7736 case AccessibilityNodeInfo.ACTION_SELECT: { 7737 if (!isSelected()) { 7738 setSelected(true); 7739 return isSelected(); 7740 } 7741 } break; 7742 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: { 7743 if (isSelected()) { 7744 setSelected(false); 7745 return !isSelected(); 7746 } 7747 } break; 7748 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 7749 if (!isAccessibilityFocused()) { 7750 return requestAccessibilityFocus(); 7751 } 7752 } break; 7753 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 7754 if (isAccessibilityFocused()) { 7755 clearAccessibilityFocus(); 7756 return true; 7757 } 7758 } break; 7759 case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { 7760 if (arguments != null) { 7761 final int granularity = arguments.getInt( 7762 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 7763 final boolean extendSelection = arguments.getBoolean( 7764 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 7765 return traverseAtGranularity(granularity, true, extendSelection); 7766 } 7767 } break; 7768 case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { 7769 if (arguments != null) { 7770 final int granularity = arguments.getInt( 7771 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 7772 final boolean extendSelection = arguments.getBoolean( 7773 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 7774 return traverseAtGranularity(granularity, false, extendSelection); 7775 } 7776 } break; 7777 case AccessibilityNodeInfo.ACTION_SET_SELECTION: { 7778 CharSequence text = getIterableTextForAccessibility(); 7779 if (text == null) { 7780 return false; 7781 } 7782 final int start = (arguments != null) ? arguments.getInt( 7783 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1; 7784 final int end = (arguments != null) ? arguments.getInt( 7785 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1; 7786 // Only cursor position can be specified (selection length == 0) 7787 if ((getAccessibilitySelectionStart() != start 7788 || getAccessibilitySelectionEnd() != end) 7789 && (start == end)) { 7790 setAccessibilitySelection(start, end); 7791 notifyViewAccessibilityStateChangedIfNeeded( 7792 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7793 return true; 7794 } 7795 } break; 7796 } 7797 return false; 7798 } 7799 7800 private boolean traverseAtGranularity(int granularity, boolean forward, 7801 boolean extendSelection) { 7802 CharSequence text = getIterableTextForAccessibility(); 7803 if (text == null || text.length() == 0) { 7804 return false; 7805 } 7806 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 7807 if (iterator == null) { 7808 return false; 7809 } 7810 int current = getAccessibilitySelectionEnd(); 7811 if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 7812 current = forward ? 0 : text.length(); 7813 } 7814 final int[] range = forward ? iterator.following(current) : iterator.preceding(current); 7815 if (range == null) { 7816 return false; 7817 } 7818 final int segmentStart = range[0]; 7819 final int segmentEnd = range[1]; 7820 int selectionStart; 7821 int selectionEnd; 7822 if (extendSelection && isAccessibilitySelectionExtendable()) { 7823 selectionStart = getAccessibilitySelectionStart(); 7824 if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 7825 selectionStart = forward ? segmentStart : segmentEnd; 7826 } 7827 selectionEnd = forward ? segmentEnd : segmentStart; 7828 } else { 7829 selectionStart = selectionEnd= forward ? segmentEnd : segmentStart; 7830 } 7831 setAccessibilitySelection(selectionStart, selectionEnd); 7832 final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY 7833 : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY; 7834 sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd); 7835 return true; 7836 } 7837 7838 /** 7839 * Gets the text reported for accessibility purposes. 7840 * 7841 * @return The accessibility text. 7842 * 7843 * @hide 7844 */ 7845 public CharSequence getIterableTextForAccessibility() { 7846 return getContentDescription(); 7847 } 7848 7849 /** 7850 * Gets whether accessibility selection can be extended. 7851 * 7852 * @return If selection is extensible. 7853 * 7854 * @hide 7855 */ 7856 public boolean isAccessibilitySelectionExtendable() { 7857 return false; 7858 } 7859 7860 /** 7861 * @hide 7862 */ 7863 public int getAccessibilitySelectionStart() { 7864 return mAccessibilityCursorPosition; 7865 } 7866 7867 /** 7868 * @hide 7869 */ 7870 public int getAccessibilitySelectionEnd() { 7871 return getAccessibilitySelectionStart(); 7872 } 7873 7874 /** 7875 * @hide 7876 */ 7877 public void setAccessibilitySelection(int start, int end) { 7878 if (start == end && end == mAccessibilityCursorPosition) { 7879 return; 7880 } 7881 if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) { 7882 mAccessibilityCursorPosition = start; 7883 } else { 7884 mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 7885 } 7886 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); 7887 } 7888 7889 private void sendViewTextTraversedAtGranularityEvent(int action, int granularity, 7890 int fromIndex, int toIndex) { 7891 if (mParent == null) { 7892 return; 7893 } 7894 AccessibilityEvent event = AccessibilityEvent.obtain( 7895 AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY); 7896 onInitializeAccessibilityEvent(event); 7897 onPopulateAccessibilityEvent(event); 7898 event.setFromIndex(fromIndex); 7899 event.setToIndex(toIndex); 7900 event.setAction(action); 7901 event.setMovementGranularity(granularity); 7902 mParent.requestSendAccessibilityEvent(this, event); 7903 } 7904 7905 /** 7906 * @hide 7907 */ 7908 public TextSegmentIterator getIteratorForGranularity(int granularity) { 7909 switch (granularity) { 7910 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { 7911 CharSequence text = getIterableTextForAccessibility(); 7912 if (text != null && text.length() > 0) { 7913 CharacterTextSegmentIterator iterator = 7914 CharacterTextSegmentIterator.getInstance( 7915 mContext.getResources().getConfiguration().locale); 7916 iterator.initialize(text.toString()); 7917 return iterator; 7918 } 7919 } break; 7920 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: { 7921 CharSequence text = getIterableTextForAccessibility(); 7922 if (text != null && text.length() > 0) { 7923 WordTextSegmentIterator iterator = 7924 WordTextSegmentIterator.getInstance( 7925 mContext.getResources().getConfiguration().locale); 7926 iterator.initialize(text.toString()); 7927 return iterator; 7928 } 7929 } break; 7930 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: { 7931 CharSequence text = getIterableTextForAccessibility(); 7932 if (text != null && text.length() > 0) { 7933 ParagraphTextSegmentIterator iterator = 7934 ParagraphTextSegmentIterator.getInstance(); 7935 iterator.initialize(text.toString()); 7936 return iterator; 7937 } 7938 } break; 7939 } 7940 return null; 7941 } 7942 7943 /** 7944 * @hide 7945 */ 7946 public void dispatchStartTemporaryDetach() { 7947 onStartTemporaryDetach(); 7948 } 7949 7950 /** 7951 * This is called when a container is going to temporarily detach a child, with 7952 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 7953 * It will either be followed by {@link #onFinishTemporaryDetach()} or 7954 * {@link #onDetachedFromWindow()} when the container is done. 7955 */ 7956 public void onStartTemporaryDetach() { 7957 removeUnsetPressCallback(); 7958 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 7959 } 7960 7961 /** 7962 * @hide 7963 */ 7964 public void dispatchFinishTemporaryDetach() { 7965 onFinishTemporaryDetach(); 7966 } 7967 7968 /** 7969 * Called after {@link #onStartTemporaryDetach} when the container is done 7970 * changing the view. 7971 */ 7972 public void onFinishTemporaryDetach() { 7973 } 7974 7975 /** 7976 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 7977 * for this view's window. Returns null if the view is not currently attached 7978 * to the window. Normally you will not need to use this directly, but 7979 * just use the standard high-level event callbacks like 7980 * {@link #onKeyDown(int, KeyEvent)}. 7981 */ 7982 public KeyEvent.DispatcherState getKeyDispatcherState() { 7983 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 7984 } 7985 7986 /** 7987 * Dispatch a key event before it is processed by any input method 7988 * associated with the view hierarchy. This can be used to intercept 7989 * key events in special situations before the IME consumes them; a 7990 * typical example would be handling the BACK key to update the application's 7991 * UI instead of allowing the IME to see it and close itself. 7992 * 7993 * @param event The key event to be dispatched. 7994 * @return True if the event was handled, false otherwise. 7995 */ 7996 public boolean dispatchKeyEventPreIme(KeyEvent event) { 7997 return onKeyPreIme(event.getKeyCode(), event); 7998 } 7999 8000 /** 8001 * Dispatch a key event to the next view on the focus path. This path runs 8002 * from the top of the view tree down to the currently focused view. If this 8003 * view has focus, it will dispatch to itself. Otherwise it will dispatch 8004 * the next node down the focus path. This method also fires any key 8005 * listeners. 8006 * 8007 * @param event The key event to be dispatched. 8008 * @return True if the event was handled, false otherwise. 8009 */ 8010 public boolean dispatchKeyEvent(KeyEvent event) { 8011 if (mInputEventConsistencyVerifier != null) { 8012 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 8013 } 8014 8015 // Give any attached key listener a first crack at the event. 8016 //noinspection SimplifiableIfStatement 8017 ListenerInfo li = mListenerInfo; 8018 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 8019 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 8020 return true; 8021 } 8022 8023 if (event.dispatch(this, mAttachInfo != null 8024 ? mAttachInfo.mKeyDispatchState : null, this)) { 8025 return true; 8026 } 8027 8028 if (mInputEventConsistencyVerifier != null) { 8029 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8030 } 8031 return false; 8032 } 8033 8034 /** 8035 * Dispatches a key shortcut event. 8036 * 8037 * @param event The key event to be dispatched. 8038 * @return True if the event was handled by the view, false otherwise. 8039 */ 8040 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 8041 return onKeyShortcut(event.getKeyCode(), event); 8042 } 8043 8044 /** 8045 * Pass the touch screen motion event down to the target view, or this 8046 * view if it is the target. 8047 * 8048 * @param event The motion event to be dispatched. 8049 * @return True if the event was handled by the view, false otherwise. 8050 */ 8051 public boolean dispatchTouchEvent(MotionEvent event) { 8052 boolean result = false; 8053 8054 if (mInputEventConsistencyVerifier != null) { 8055 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 8056 } 8057 8058 final int actionMasked = event.getActionMasked(); 8059 if (actionMasked == MotionEvent.ACTION_DOWN) { 8060 // Defensive cleanup for new gesture 8061 stopNestedScroll(); 8062 } 8063 8064 if (onFilterTouchEventForSecurity(event)) { 8065 //noinspection SimplifiableIfStatement 8066 ListenerInfo li = mListenerInfo; 8067 if (li != null && li.mOnTouchListener != null 8068 && (mViewFlags & ENABLED_MASK) == ENABLED 8069 && li.mOnTouchListener.onTouch(this, event)) { 8070 result = true; 8071 } 8072 8073 if (!result && onTouchEvent(event)) { 8074 result = true; 8075 } 8076 } 8077 8078 if (!result && mInputEventConsistencyVerifier != null) { 8079 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8080 } 8081 8082 // Clean up after nested scrolls if this is the end of a gesture; 8083 // also cancel it if we tried an ACTION_DOWN but we didn't want the rest 8084 // of the gesture. 8085 if (actionMasked == MotionEvent.ACTION_UP || 8086 actionMasked == MotionEvent.ACTION_CANCEL || 8087 (actionMasked == MotionEvent.ACTION_DOWN && !result)) { 8088 stopNestedScroll(); 8089 } 8090 8091 return result; 8092 } 8093 8094 /** 8095 * Filter the touch event to apply security policies. 8096 * 8097 * @param event The motion event to be filtered. 8098 * @return True if the event should be dispatched, false if the event should be dropped. 8099 * 8100 * @see #getFilterTouchesWhenObscured 8101 */ 8102 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 8103 //noinspection RedundantIfStatement 8104 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 8105 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 8106 // Window is obscured, drop this touch. 8107 return false; 8108 } 8109 return true; 8110 } 8111 8112 /** 8113 * Pass a trackball motion event down to the focused view. 8114 * 8115 * @param event The motion event to be dispatched. 8116 * @return True if the event was handled by the view, false otherwise. 8117 */ 8118 public boolean dispatchTrackballEvent(MotionEvent event) { 8119 if (mInputEventConsistencyVerifier != null) { 8120 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 8121 } 8122 8123 return onTrackballEvent(event); 8124 } 8125 8126 /** 8127 * Dispatch a generic motion event. 8128 * <p> 8129 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 8130 * are delivered to the view under the pointer. All other generic motion events are 8131 * delivered to the focused view. Hover events are handled specially and are delivered 8132 * to {@link #onHoverEvent(MotionEvent)}. 8133 * </p> 8134 * 8135 * @param event The motion event to be dispatched. 8136 * @return True if the event was handled by the view, false otherwise. 8137 */ 8138 public boolean dispatchGenericMotionEvent(MotionEvent event) { 8139 if (mInputEventConsistencyVerifier != null) { 8140 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 8141 } 8142 8143 final int source = event.getSource(); 8144 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 8145 final int action = event.getAction(); 8146 if (action == MotionEvent.ACTION_HOVER_ENTER 8147 || action == MotionEvent.ACTION_HOVER_MOVE 8148 || action == MotionEvent.ACTION_HOVER_EXIT) { 8149 if (dispatchHoverEvent(event)) { 8150 return true; 8151 } 8152 } else if (dispatchGenericPointerEvent(event)) { 8153 return true; 8154 } 8155 } else if (dispatchGenericFocusedEvent(event)) { 8156 return true; 8157 } 8158 8159 if (dispatchGenericMotionEventInternal(event)) { 8160 return true; 8161 } 8162 8163 if (mInputEventConsistencyVerifier != null) { 8164 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8165 } 8166 return false; 8167 } 8168 8169 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 8170 //noinspection SimplifiableIfStatement 8171 ListenerInfo li = mListenerInfo; 8172 if (li != null && li.mOnGenericMotionListener != null 8173 && (mViewFlags & ENABLED_MASK) == ENABLED 8174 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 8175 return true; 8176 } 8177 8178 if (onGenericMotionEvent(event)) { 8179 return true; 8180 } 8181 8182 if (mInputEventConsistencyVerifier != null) { 8183 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8184 } 8185 return false; 8186 } 8187 8188 /** 8189 * Dispatch a hover event. 8190 * <p> 8191 * Do not call this method directly. 8192 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8193 * </p> 8194 * 8195 * @param event The motion event to be dispatched. 8196 * @return True if the event was handled by the view, false otherwise. 8197 */ 8198 protected boolean dispatchHoverEvent(MotionEvent event) { 8199 ListenerInfo li = mListenerInfo; 8200 //noinspection SimplifiableIfStatement 8201 if (li != null && li.mOnHoverListener != null 8202 && (mViewFlags & ENABLED_MASK) == ENABLED 8203 && li.mOnHoverListener.onHover(this, event)) { 8204 return true; 8205 } 8206 8207 return onHoverEvent(event); 8208 } 8209 8210 /** 8211 * Returns true if the view has a child to which it has recently sent 8212 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 8213 * it does not have a hovered child, then it must be the innermost hovered view. 8214 * @hide 8215 */ 8216 protected boolean hasHoveredChild() { 8217 return false; 8218 } 8219 8220 /** 8221 * Dispatch a generic motion event to the view under the first pointer. 8222 * <p> 8223 * Do not call this method directly. 8224 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8225 * </p> 8226 * 8227 * @param event The motion event to be dispatched. 8228 * @return True if the event was handled by the view, false otherwise. 8229 */ 8230 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 8231 return false; 8232 } 8233 8234 /** 8235 * Dispatch a generic motion event to the currently focused view. 8236 * <p> 8237 * Do not call this method directly. 8238 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8239 * </p> 8240 * 8241 * @param event The motion event to be dispatched. 8242 * @return True if the event was handled by the view, false otherwise. 8243 */ 8244 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 8245 return false; 8246 } 8247 8248 /** 8249 * Dispatch a pointer event. 8250 * <p> 8251 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 8252 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 8253 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 8254 * and should not be expected to handle other pointing device features. 8255 * </p> 8256 * 8257 * @param event The motion event to be dispatched. 8258 * @return True if the event was handled by the view, false otherwise. 8259 * @hide 8260 */ 8261 public final boolean dispatchPointerEvent(MotionEvent event) { 8262 if (event.isTouchEvent()) { 8263 return dispatchTouchEvent(event); 8264 } else { 8265 return dispatchGenericMotionEvent(event); 8266 } 8267 } 8268 8269 /** 8270 * Called when the window containing this view gains or loses window focus. 8271 * ViewGroups should override to route to their children. 8272 * 8273 * @param hasFocus True if the window containing this view now has focus, 8274 * false otherwise. 8275 */ 8276 public void dispatchWindowFocusChanged(boolean hasFocus) { 8277 onWindowFocusChanged(hasFocus); 8278 } 8279 8280 /** 8281 * Called when the window containing this view gains or loses focus. Note 8282 * that this is separate from view focus: to receive key events, both 8283 * your view and its window must have focus. If a window is displayed 8284 * on top of yours that takes input focus, then your own window will lose 8285 * focus but the view focus will remain unchanged. 8286 * 8287 * @param hasWindowFocus True if the window containing this view now has 8288 * focus, false otherwise. 8289 */ 8290 public void onWindowFocusChanged(boolean hasWindowFocus) { 8291 InputMethodManager imm = InputMethodManager.peekInstance(); 8292 if (!hasWindowFocus) { 8293 if (isPressed()) { 8294 setPressed(false); 8295 } 8296 if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 8297 imm.focusOut(this); 8298 } 8299 removeLongPressCallback(); 8300 removeTapCallback(); 8301 onFocusLost(); 8302 } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 8303 imm.focusIn(this); 8304 } 8305 refreshDrawableState(); 8306 } 8307 8308 /** 8309 * Returns true if this view is in a window that currently has window focus. 8310 * Note that this is not the same as the view itself having focus. 8311 * 8312 * @return True if this view is in a window that currently has window focus. 8313 */ 8314 public boolean hasWindowFocus() { 8315 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 8316 } 8317 8318 /** 8319 * Dispatch a view visibility change down the view hierarchy. 8320 * ViewGroups should override to route to their children. 8321 * @param changedView The view whose visibility changed. Could be 'this' or 8322 * an ancestor view. 8323 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 8324 * {@link #INVISIBLE} or {@link #GONE}. 8325 */ 8326 protected void dispatchVisibilityChanged(@NonNull View changedView, 8327 @Visibility int visibility) { 8328 onVisibilityChanged(changedView, visibility); 8329 } 8330 8331 /** 8332 * Called when the visibility of the view or an ancestor of the view is changed. 8333 * @param changedView The view whose visibility changed. Could be 'this' or 8334 * an ancestor view. 8335 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 8336 * {@link #INVISIBLE} or {@link #GONE}. 8337 */ 8338 protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) { 8339 if (visibility == VISIBLE) { 8340 if (mAttachInfo != null) { 8341 initialAwakenScrollBars(); 8342 } else { 8343 mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 8344 } 8345 } 8346 } 8347 8348 /** 8349 * Dispatch a hint about whether this view is displayed. For instance, when 8350 * a View moves out of the screen, it might receives a display hint indicating 8351 * the view is not displayed. Applications should not <em>rely</em> on this hint 8352 * as there is no guarantee that they will receive one. 8353 * 8354 * @param hint A hint about whether or not this view is displayed: 8355 * {@link #VISIBLE} or {@link #INVISIBLE}. 8356 */ 8357 public void dispatchDisplayHint(@Visibility int hint) { 8358 onDisplayHint(hint); 8359 } 8360 8361 /** 8362 * Gives this view a hint about whether is displayed or not. For instance, when 8363 * a View moves out of the screen, it might receives a display hint indicating 8364 * the view is not displayed. Applications should not <em>rely</em> on this hint 8365 * as there is no guarantee that they will receive one. 8366 * 8367 * @param hint A hint about whether or not this view is displayed: 8368 * {@link #VISIBLE} or {@link #INVISIBLE}. 8369 */ 8370 protected void onDisplayHint(@Visibility int hint) { 8371 } 8372 8373 /** 8374 * Dispatch a window visibility change down the view hierarchy. 8375 * ViewGroups should override to route to their children. 8376 * 8377 * @param visibility The new visibility of the window. 8378 * 8379 * @see #onWindowVisibilityChanged(int) 8380 */ 8381 public void dispatchWindowVisibilityChanged(@Visibility int visibility) { 8382 onWindowVisibilityChanged(visibility); 8383 } 8384 8385 /** 8386 * Called when the window containing has change its visibility 8387 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 8388 * that this tells you whether or not your window is being made visible 8389 * to the window manager; this does <em>not</em> tell you whether or not 8390 * your window is obscured by other windows on the screen, even if it 8391 * is itself visible. 8392 * 8393 * @param visibility The new visibility of the window. 8394 */ 8395 protected void onWindowVisibilityChanged(@Visibility int visibility) { 8396 if (visibility == VISIBLE) { 8397 initialAwakenScrollBars(); 8398 } 8399 } 8400 8401 /** 8402 * Returns the current visibility of the window this view is attached to 8403 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 8404 * 8405 * @return Returns the current visibility of the view's window. 8406 */ 8407 @Visibility 8408 public int getWindowVisibility() { 8409 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 8410 } 8411 8412 /** 8413 * Retrieve the overall visible display size in which the window this view is 8414 * attached to has been positioned in. This takes into account screen 8415 * decorations above the window, for both cases where the window itself 8416 * is being position inside of them or the window is being placed under 8417 * then and covered insets are used for the window to position its content 8418 * inside. In effect, this tells you the available area where content can 8419 * be placed and remain visible to users. 8420 * 8421 * <p>This function requires an IPC back to the window manager to retrieve 8422 * the requested information, so should not be used in performance critical 8423 * code like drawing. 8424 * 8425 * @param outRect Filled in with the visible display frame. If the view 8426 * is not attached to a window, this is simply the raw display size. 8427 */ 8428 public void getWindowVisibleDisplayFrame(Rect outRect) { 8429 if (mAttachInfo != null) { 8430 try { 8431 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 8432 } catch (RemoteException e) { 8433 return; 8434 } 8435 // XXX This is really broken, and probably all needs to be done 8436 // in the window manager, and we need to know more about whether 8437 // we want the area behind or in front of the IME. 8438 final Rect insets = mAttachInfo.mVisibleInsets; 8439 outRect.left += insets.left; 8440 outRect.top += insets.top; 8441 outRect.right -= insets.right; 8442 outRect.bottom -= insets.bottom; 8443 return; 8444 } 8445 // The view is not attached to a display so we don't have a context. 8446 // Make a best guess about the display size. 8447 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 8448 d.getRectSize(outRect); 8449 } 8450 8451 /** 8452 * Dispatch a notification about a resource configuration change down 8453 * the view hierarchy. 8454 * ViewGroups should override to route to their children. 8455 * 8456 * @param newConfig The new resource configuration. 8457 * 8458 * @see #onConfigurationChanged(android.content.res.Configuration) 8459 */ 8460 public void dispatchConfigurationChanged(Configuration newConfig) { 8461 onConfigurationChanged(newConfig); 8462 } 8463 8464 /** 8465 * Called when the current configuration of the resources being used 8466 * by the application have changed. You can use this to decide when 8467 * to reload resources that can changed based on orientation and other 8468 * configuration characterstics. You only need to use this if you are 8469 * not relying on the normal {@link android.app.Activity} mechanism of 8470 * recreating the activity instance upon a configuration change. 8471 * 8472 * @param newConfig The new resource configuration. 8473 */ 8474 protected void onConfigurationChanged(Configuration newConfig) { 8475 } 8476 8477 /** 8478 * Private function to aggregate all per-view attributes in to the view 8479 * root. 8480 */ 8481 void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) { 8482 performCollectViewAttributes(attachInfo, visibility); 8483 } 8484 8485 void performCollectViewAttributes(AttachInfo attachInfo, int visibility) { 8486 if ((visibility & VISIBILITY_MASK) == VISIBLE) { 8487 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 8488 attachInfo.mKeepScreenOn = true; 8489 } 8490 attachInfo.mSystemUiVisibility |= mSystemUiVisibility; 8491 ListenerInfo li = mListenerInfo; 8492 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 8493 attachInfo.mHasSystemUiListeners = true; 8494 } 8495 } 8496 } 8497 8498 void needGlobalAttributesUpdate(boolean force) { 8499 final AttachInfo ai = mAttachInfo; 8500 if (ai != null && !ai.mRecomputeGlobalAttributes) { 8501 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 8502 || ai.mHasSystemUiListeners) { 8503 ai.mRecomputeGlobalAttributes = true; 8504 } 8505 } 8506 } 8507 8508 /** 8509 * Returns whether the device is currently in touch mode. Touch mode is entered 8510 * once the user begins interacting with the device by touch, and affects various 8511 * things like whether focus is always visible to the user. 8512 * 8513 * @return Whether the device is in touch mode. 8514 */ 8515 @ViewDebug.ExportedProperty 8516 public boolean isInTouchMode() { 8517 if (mAttachInfo != null) { 8518 return mAttachInfo.mInTouchMode; 8519 } else { 8520 return ViewRootImpl.isInTouchMode(); 8521 } 8522 } 8523 8524 /** 8525 * Returns the context the view is running in, through which it can 8526 * access the current theme, resources, etc. 8527 * 8528 * @return The view's Context. 8529 */ 8530 @ViewDebug.CapturedViewProperty 8531 public final Context getContext() { 8532 return mContext; 8533 } 8534 8535 /** 8536 * Handle a key event before it is processed by any input method 8537 * associated with the view hierarchy. This can be used to intercept 8538 * key events in special situations before the IME consumes them; a 8539 * typical example would be handling the BACK key to update the application's 8540 * UI instead of allowing the IME to see it and close itself. 8541 * 8542 * @param keyCode The value in event.getKeyCode(). 8543 * @param event Description of the key event. 8544 * @return If you handled the event, return true. If you want to allow the 8545 * event to be handled by the next receiver, return false. 8546 */ 8547 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 8548 return false; 8549 } 8550 8551 /** 8552 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 8553 * KeyEvent.Callback.onKeyDown()}: perform press of the view 8554 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 8555 * is released, if the view is enabled and clickable. 8556 * 8557 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8558 * although some may elect to do so in some situations. Do not rely on this to 8559 * catch software key presses. 8560 * 8561 * @param keyCode A key code that represents the button pressed, from 8562 * {@link android.view.KeyEvent}. 8563 * @param event The KeyEvent object that defines the button action. 8564 */ 8565 public boolean onKeyDown(int keyCode, KeyEvent event) { 8566 boolean result = false; 8567 8568 if (KeyEvent.isConfirmKey(keyCode)) { 8569 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 8570 return true; 8571 } 8572 // Long clickable items don't necessarily have to be clickable 8573 if (((mViewFlags & CLICKABLE) == CLICKABLE || 8574 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 8575 (event.getRepeatCount() == 0)) { 8576 setPressed(true); 8577 checkForLongClick(0); 8578 return true; 8579 } 8580 } 8581 return result; 8582 } 8583 8584 /** 8585 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 8586 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 8587 * the event). 8588 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8589 * although some may elect to do so in some situations. Do not rely on this to 8590 * catch software key presses. 8591 */ 8592 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 8593 return false; 8594 } 8595 8596 /** 8597 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 8598 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 8599 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 8600 * {@link KeyEvent#KEYCODE_ENTER} is released. 8601 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8602 * although some may elect to do so in some situations. Do not rely on this to 8603 * catch software key presses. 8604 * 8605 * @param keyCode A key code that represents the button pressed, from 8606 * {@link android.view.KeyEvent}. 8607 * @param event The KeyEvent object that defines the button action. 8608 */ 8609 public boolean onKeyUp(int keyCode, KeyEvent event) { 8610 if (KeyEvent.isConfirmKey(keyCode)) { 8611 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 8612 return true; 8613 } 8614 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 8615 setPressed(false); 8616 8617 if (!mHasPerformedLongPress) { 8618 // This is a tap, so remove the longpress check 8619 removeLongPressCallback(); 8620 return performClick(); 8621 } 8622 } 8623 } 8624 return false; 8625 } 8626 8627 /** 8628 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 8629 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 8630 * the event). 8631 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8632 * although some may elect to do so in some situations. Do not rely on this to 8633 * catch software key presses. 8634 * 8635 * @param keyCode A key code that represents the button pressed, from 8636 * {@link android.view.KeyEvent}. 8637 * @param repeatCount The number of times the action was made. 8638 * @param event The KeyEvent object that defines the button action. 8639 */ 8640 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 8641 return false; 8642 } 8643 8644 /** 8645 * Called on the focused view when a key shortcut event is not handled. 8646 * Override this method to implement local key shortcuts for the View. 8647 * Key shortcuts can also be implemented by setting the 8648 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 8649 * 8650 * @param keyCode The value in event.getKeyCode(). 8651 * @param event Description of the key event. 8652 * @return If you handled the event, return true. If you want to allow the 8653 * event to be handled by the next receiver, return false. 8654 */ 8655 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 8656 return false; 8657 } 8658 8659 /** 8660 * Check whether the called view is a text editor, in which case it 8661 * would make sense to automatically display a soft input window for 8662 * it. Subclasses should override this if they implement 8663 * {@link #onCreateInputConnection(EditorInfo)} to return true if 8664 * a call on that method would return a non-null InputConnection, and 8665 * they are really a first-class editor that the user would normally 8666 * start typing on when the go into a window containing your view. 8667 * 8668 * <p>The default implementation always returns false. This does 8669 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 8670 * will not be called or the user can not otherwise perform edits on your 8671 * view; it is just a hint to the system that this is not the primary 8672 * purpose of this view. 8673 * 8674 * @return Returns true if this view is a text editor, else false. 8675 */ 8676 public boolean onCheckIsTextEditor() { 8677 return false; 8678 } 8679 8680 /** 8681 * Create a new InputConnection for an InputMethod to interact 8682 * with the view. The default implementation returns null, since it doesn't 8683 * support input methods. You can override this to implement such support. 8684 * This is only needed for views that take focus and text input. 8685 * 8686 * <p>When implementing this, you probably also want to implement 8687 * {@link #onCheckIsTextEditor()} to indicate you will return a 8688 * non-null InputConnection.</p> 8689 * 8690 * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo} 8691 * object correctly and in its entirety, so that the connected IME can rely 8692 * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart} 8693 * and {@link android.view.inputmethod.EditorInfo#initialSelEnd} members 8694 * must be filled in with the correct cursor position for IMEs to work correctly 8695 * with your application.</p> 8696 * 8697 * @param outAttrs Fill in with attribute information about the connection. 8698 */ 8699 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 8700 return null; 8701 } 8702 8703 /** 8704 * Called by the {@link android.view.inputmethod.InputMethodManager} 8705 * when a view who is not the current 8706 * input connection target is trying to make a call on the manager. The 8707 * default implementation returns false; you can override this to return 8708 * true for certain views if you are performing InputConnection proxying 8709 * to them. 8710 * @param view The View that is making the InputMethodManager call. 8711 * @return Return true to allow the call, false to reject. 8712 */ 8713 public boolean checkInputConnectionProxy(View view) { 8714 return false; 8715 } 8716 8717 /** 8718 * Show the context menu for this view. It is not safe to hold on to the 8719 * menu after returning from this method. 8720 * 8721 * You should normally not overload this method. Overload 8722 * {@link #onCreateContextMenu(ContextMenu)} or define an 8723 * {@link OnCreateContextMenuListener} to add items to the context menu. 8724 * 8725 * @param menu The context menu to populate 8726 */ 8727 public void createContextMenu(ContextMenu menu) { 8728 ContextMenuInfo menuInfo = getContextMenuInfo(); 8729 8730 // Sets the current menu info so all items added to menu will have 8731 // my extra info set. 8732 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 8733 8734 onCreateContextMenu(menu); 8735 ListenerInfo li = mListenerInfo; 8736 if (li != null && li.mOnCreateContextMenuListener != null) { 8737 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 8738 } 8739 8740 // Clear the extra information so subsequent items that aren't mine don't 8741 // have my extra info. 8742 ((MenuBuilder)menu).setCurrentMenuInfo(null); 8743 8744 if (mParent != null) { 8745 mParent.createContextMenu(menu); 8746 } 8747 } 8748 8749 /** 8750 * Views should implement this if they have extra information to associate 8751 * with the context menu. The return result is supplied as a parameter to 8752 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 8753 * callback. 8754 * 8755 * @return Extra information about the item for which the context menu 8756 * should be shown. This information will vary across different 8757 * subclasses of View. 8758 */ 8759 protected ContextMenuInfo getContextMenuInfo() { 8760 return null; 8761 } 8762 8763 /** 8764 * Views should implement this if the view itself is going to add items to 8765 * the context menu. 8766 * 8767 * @param menu the context menu to populate 8768 */ 8769 protected void onCreateContextMenu(ContextMenu menu) { 8770 } 8771 8772 /** 8773 * Implement this method to handle trackball motion events. The 8774 * <em>relative</em> movement of the trackball since the last event 8775 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 8776 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 8777 * that a movement of 1 corresponds to the user pressing one DPAD key (so 8778 * they will often be fractional values, representing the more fine-grained 8779 * movement information available from a trackball). 8780 * 8781 * @param event The motion event. 8782 * @return True if the event was handled, false otherwise. 8783 */ 8784 public boolean onTrackballEvent(MotionEvent event) { 8785 return false; 8786 } 8787 8788 /** 8789 * Implement this method to handle generic motion events. 8790 * <p> 8791 * Generic motion events describe joystick movements, mouse hovers, track pad 8792 * touches, scroll wheel movements and other input events. The 8793 * {@link MotionEvent#getSource() source} of the motion event specifies 8794 * the class of input that was received. Implementations of this method 8795 * must examine the bits in the source before processing the event. 8796 * The following code example shows how this is done. 8797 * </p><p> 8798 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 8799 * are delivered to the view under the pointer. All other generic motion events are 8800 * delivered to the focused view. 8801 * </p> 8802 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 8803 * if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) { 8804 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 8805 * // process the joystick movement... 8806 * return true; 8807 * } 8808 * } 8809 * if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) { 8810 * switch (event.getAction()) { 8811 * case MotionEvent.ACTION_HOVER_MOVE: 8812 * // process the mouse hover movement... 8813 * return true; 8814 * case MotionEvent.ACTION_SCROLL: 8815 * // process the scroll wheel movement... 8816 * return true; 8817 * } 8818 * } 8819 * return super.onGenericMotionEvent(event); 8820 * }</pre> 8821 * 8822 * @param event The generic motion event being processed. 8823 * @return True if the event was handled, false otherwise. 8824 */ 8825 public boolean onGenericMotionEvent(MotionEvent event) { 8826 return false; 8827 } 8828 8829 /** 8830 * Implement this method to handle hover events. 8831 * <p> 8832 * This method is called whenever a pointer is hovering into, over, or out of the 8833 * bounds of a view and the view is not currently being touched. 8834 * Hover events are represented as pointer events with action 8835 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 8836 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 8837 * </p> 8838 * <ul> 8839 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 8840 * when the pointer enters the bounds of the view.</li> 8841 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 8842 * when the pointer has already entered the bounds of the view and has moved.</li> 8843 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 8844 * when the pointer has exited the bounds of the view or when the pointer is 8845 * about to go down due to a button click, tap, or similar user action that 8846 * causes the view to be touched.</li> 8847 * </ul> 8848 * <p> 8849 * The view should implement this method to return true to indicate that it is 8850 * handling the hover event, such as by changing its drawable state. 8851 * </p><p> 8852 * The default implementation calls {@link #setHovered} to update the hovered state 8853 * of the view when a hover enter or hover exit event is received, if the view 8854 * is enabled and is clickable. The default implementation also sends hover 8855 * accessibility events. 8856 * </p> 8857 * 8858 * @param event The motion event that describes the hover. 8859 * @return True if the view handled the hover event. 8860 * 8861 * @see #isHovered 8862 * @see #setHovered 8863 * @see #onHoverChanged 8864 */ 8865 public boolean onHoverEvent(MotionEvent event) { 8866 // The root view may receive hover (or touch) events that are outside the bounds of 8867 // the window. This code ensures that we only send accessibility events for 8868 // hovers that are actually within the bounds of the root view. 8869 final int action = event.getActionMasked(); 8870 if (!mSendingHoverAccessibilityEvents) { 8871 if ((action == MotionEvent.ACTION_HOVER_ENTER 8872 || action == MotionEvent.ACTION_HOVER_MOVE) 8873 && !hasHoveredChild() 8874 && pointInView(event.getX(), event.getY())) { 8875 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 8876 mSendingHoverAccessibilityEvents = true; 8877 } 8878 } else { 8879 if (action == MotionEvent.ACTION_HOVER_EXIT 8880 || (action == MotionEvent.ACTION_MOVE 8881 && !pointInView(event.getX(), event.getY()))) { 8882 mSendingHoverAccessibilityEvents = false; 8883 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 8884 } 8885 } 8886 8887 if (isHoverable()) { 8888 switch (action) { 8889 case MotionEvent.ACTION_HOVER_ENTER: 8890 setHovered(true); 8891 break; 8892 case MotionEvent.ACTION_HOVER_EXIT: 8893 setHovered(false); 8894 break; 8895 } 8896 8897 // Dispatch the event to onGenericMotionEvent before returning true. 8898 // This is to provide compatibility with existing applications that 8899 // handled HOVER_MOVE events in onGenericMotionEvent and that would 8900 // break because of the new default handling for hoverable views 8901 // in onHoverEvent. 8902 // Note that onGenericMotionEvent will be called by default when 8903 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 8904 dispatchGenericMotionEventInternal(event); 8905 // The event was already handled by calling setHovered(), so always 8906 // return true. 8907 return true; 8908 } 8909 8910 return false; 8911 } 8912 8913 /** 8914 * Returns true if the view should handle {@link #onHoverEvent} 8915 * by calling {@link #setHovered} to change its hovered state. 8916 * 8917 * @return True if the view is hoverable. 8918 */ 8919 private boolean isHoverable() { 8920 final int viewFlags = mViewFlags; 8921 if ((viewFlags & ENABLED_MASK) == DISABLED) { 8922 return false; 8923 } 8924 8925 return (viewFlags & CLICKABLE) == CLICKABLE 8926 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 8927 } 8928 8929 /** 8930 * Returns true if the view is currently hovered. 8931 * 8932 * @return True if the view is currently hovered. 8933 * 8934 * @see #setHovered 8935 * @see #onHoverChanged 8936 */ 8937 @ViewDebug.ExportedProperty 8938 public boolean isHovered() { 8939 return (mPrivateFlags & PFLAG_HOVERED) != 0; 8940 } 8941 8942 /** 8943 * Sets whether the view is currently hovered. 8944 * <p> 8945 * Calling this method also changes the drawable state of the view. This 8946 * enables the view to react to hover by using different drawable resources 8947 * to change its appearance. 8948 * </p><p> 8949 * The {@link #onHoverChanged} method is called when the hovered state changes. 8950 * </p> 8951 * 8952 * @param hovered True if the view is hovered. 8953 * 8954 * @see #isHovered 8955 * @see #onHoverChanged 8956 */ 8957 public void setHovered(boolean hovered) { 8958 if (hovered) { 8959 if ((mPrivateFlags & PFLAG_HOVERED) == 0) { 8960 mPrivateFlags |= PFLAG_HOVERED; 8961 refreshDrawableState(); 8962 onHoverChanged(true); 8963 } 8964 } else { 8965 if ((mPrivateFlags & PFLAG_HOVERED) != 0) { 8966 mPrivateFlags &= ~PFLAG_HOVERED; 8967 refreshDrawableState(); 8968 onHoverChanged(false); 8969 } 8970 } 8971 } 8972 8973 /** 8974 * Implement this method to handle hover state changes. 8975 * <p> 8976 * This method is called whenever the hover state changes as a result of a 8977 * call to {@link #setHovered}. 8978 * </p> 8979 * 8980 * @param hovered The current hover state, as returned by {@link #isHovered}. 8981 * 8982 * @see #isHovered 8983 * @see #setHovered 8984 */ 8985 public void onHoverChanged(boolean hovered) { 8986 } 8987 8988 /** 8989 * Implement this method to handle touch screen motion events. 8990 * <p> 8991 * If this method is used to detect click actions, it is recommended that 8992 * the actions be performed by implementing and calling 8993 * {@link #performClick()}. This will ensure consistent system behavior, 8994 * including: 8995 * <ul> 8996 * <li>obeying click sound preferences 8997 * <li>dispatching OnClickListener calls 8998 * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when 8999 * accessibility features are enabled 9000 * </ul> 9001 * 9002 * @param event The motion event. 9003 * @return True if the event was handled, false otherwise. 9004 */ 9005 public boolean onTouchEvent(MotionEvent event) { 9006 final float x = event.getX(); 9007 final float y = event.getY(); 9008 final int viewFlags = mViewFlags; 9009 9010 if ((viewFlags & ENABLED_MASK) == DISABLED) { 9011 if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { 9012 setPressed(false); 9013 } 9014 // A disabled view that is clickable still consumes the touch 9015 // events, it just doesn't respond to them. 9016 return (((viewFlags & CLICKABLE) == CLICKABLE || 9017 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); 9018 } 9019 9020 if (mTouchDelegate != null) { 9021 if (mTouchDelegate.onTouchEvent(event)) { 9022 return true; 9023 } 9024 } 9025 9026 if (((viewFlags & CLICKABLE) == CLICKABLE || 9027 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { 9028 switch (event.getAction()) { 9029 case MotionEvent.ACTION_UP: 9030 boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; 9031 if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { 9032 // take focus if we don't have it already and we should in 9033 // touch mode. 9034 boolean focusTaken = false; 9035 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 9036 focusTaken = requestFocus(); 9037 } 9038 9039 if (prepressed) { 9040 // The button is being released before we actually 9041 // showed it as pressed. Make it show the pressed 9042 // state now (before scheduling the click) to ensure 9043 // the user sees it. 9044 setPressed(true, x, y); 9045 } 9046 9047 if (!mHasPerformedLongPress) { 9048 // This is a tap, so remove the longpress check 9049 removeLongPressCallback(); 9050 9051 // Only perform take click actions if we were in the pressed state 9052 if (!focusTaken) { 9053 // Use a Runnable and post this rather than calling 9054 // performClick directly. This lets other visual state 9055 // of the view update before click actions start. 9056 if (mPerformClick == null) { 9057 mPerformClick = new PerformClick(); 9058 } 9059 if (!post(mPerformClick)) { 9060 performClick(); 9061 } 9062 } 9063 } 9064 9065 if (mUnsetPressedState == null) { 9066 mUnsetPressedState = new UnsetPressedState(); 9067 } 9068 9069 if (prepressed) { 9070 postDelayed(mUnsetPressedState, 9071 ViewConfiguration.getPressedStateDuration()); 9072 } else if (!post(mUnsetPressedState)) { 9073 // If the post failed, unpress right now 9074 mUnsetPressedState.run(); 9075 } 9076 9077 removeTapCallback(); 9078 } 9079 break; 9080 9081 case MotionEvent.ACTION_DOWN: 9082 mHasPerformedLongPress = false; 9083 9084 if (performButtonActionOnTouchDown(event)) { 9085 break; 9086 } 9087 9088 // Walk up the hierarchy to determine if we're inside a scrolling container. 9089 boolean isInScrollingContainer = isInScrollingContainer(); 9090 9091 // For views inside a scrolling container, delay the pressed feedback for 9092 // a short period in case this is a scroll. 9093 if (isInScrollingContainer) { 9094 mPrivateFlags |= PFLAG_PREPRESSED; 9095 if (mPendingCheckForTap == null) { 9096 mPendingCheckForTap = new CheckForTap(); 9097 } 9098 mPendingCheckForTap.x = event.getX(); 9099 mPendingCheckForTap.y = event.getY(); 9100 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 9101 } else { 9102 // Not inside a scrolling container, so show the feedback right away 9103 setHotspot(x, y); 9104 setPressed(true); 9105 checkForLongClick(0); 9106 } 9107 break; 9108 9109 case MotionEvent.ACTION_CANCEL: 9110 setPressed(false); 9111 removeTapCallback(); 9112 removeLongPressCallback(); 9113 break; 9114 9115 case MotionEvent.ACTION_MOVE: 9116 setHotspot(x, y); 9117 9118 // Be lenient about moving outside of buttons 9119 if (!pointInView(x, y, mTouchSlop)) { 9120 // Outside button 9121 removeTapCallback(); 9122 if ((mPrivateFlags & PFLAG_PRESSED) != 0) { 9123 // Remove any future long press/tap checks 9124 removeLongPressCallback(); 9125 9126 setPressed(false); 9127 } 9128 } 9129 break; 9130 } 9131 9132 return true; 9133 } 9134 9135 return false; 9136 } 9137 9138 private void setHotspot(float x, float y) { 9139 if (mBackground != null) { 9140 mBackground.setHotspot(x, y); 9141 } 9142 } 9143 9144 /** 9145 * @hide 9146 */ 9147 public boolean isInScrollingContainer() { 9148 ViewParent p = getParent(); 9149 while (p != null && p instanceof ViewGroup) { 9150 if (((ViewGroup) p).shouldDelayChildPressedState()) { 9151 return true; 9152 } 9153 p = p.getParent(); 9154 } 9155 return false; 9156 } 9157 9158 /** 9159 * Remove the longpress detection timer. 9160 */ 9161 private void removeLongPressCallback() { 9162 if (mPendingCheckForLongPress != null) { 9163 removeCallbacks(mPendingCheckForLongPress); 9164 } 9165 } 9166 9167 /** 9168 * Remove the pending click action 9169 */ 9170 private void removePerformClickCallback() { 9171 if (mPerformClick != null) { 9172 removeCallbacks(mPerformClick); 9173 } 9174 } 9175 9176 /** 9177 * Remove the prepress detection timer. 9178 */ 9179 private void removeUnsetPressCallback() { 9180 if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) { 9181 setPressed(false); 9182 removeCallbacks(mUnsetPressedState); 9183 } 9184 } 9185 9186 /** 9187 * Remove the tap detection timer. 9188 */ 9189 private void removeTapCallback() { 9190 if (mPendingCheckForTap != null) { 9191 mPrivateFlags &= ~PFLAG_PREPRESSED; 9192 removeCallbacks(mPendingCheckForTap); 9193 } 9194 } 9195 9196 /** 9197 * Cancels a pending long press. Your subclass can use this if you 9198 * want the context menu to come up if the user presses and holds 9199 * at the same place, but you don't want it to come up if they press 9200 * and then move around enough to cause scrolling. 9201 */ 9202 public void cancelLongPress() { 9203 removeLongPressCallback(); 9204 9205 /* 9206 * The prepressed state handled by the tap callback is a display 9207 * construct, but the tap callback will post a long press callback 9208 * less its own timeout. Remove it here. 9209 */ 9210 removeTapCallback(); 9211 } 9212 9213 /** 9214 * Remove the pending callback for sending a 9215 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 9216 */ 9217 private void removeSendViewScrolledAccessibilityEventCallback() { 9218 if (mSendViewScrolledAccessibilityEvent != null) { 9219 removeCallbacks(mSendViewScrolledAccessibilityEvent); 9220 mSendViewScrolledAccessibilityEvent.mIsPending = false; 9221 } 9222 } 9223 9224 /** 9225 * Sets the TouchDelegate for this View. 9226 */ 9227 public void setTouchDelegate(TouchDelegate delegate) { 9228 mTouchDelegate = delegate; 9229 } 9230 9231 /** 9232 * Gets the TouchDelegate for this View. 9233 */ 9234 public TouchDelegate getTouchDelegate() { 9235 return mTouchDelegate; 9236 } 9237 9238 /** 9239 * Set flags controlling behavior of this view. 9240 * 9241 * @param flags Constant indicating the value which should be set 9242 * @param mask Constant indicating the bit range that should be changed 9243 */ 9244 void setFlags(int flags, int mask) { 9245 final boolean accessibilityEnabled = 9246 AccessibilityManager.getInstance(mContext).isEnabled(); 9247 final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility(); 9248 9249 int old = mViewFlags; 9250 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 9251 9252 int changed = mViewFlags ^ old; 9253 if (changed == 0) { 9254 return; 9255 } 9256 int privateFlags = mPrivateFlags; 9257 9258 /* Check if the FOCUSABLE bit has changed */ 9259 if (((changed & FOCUSABLE_MASK) != 0) && 9260 ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) { 9261 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 9262 && ((privateFlags & PFLAG_FOCUSED) != 0)) { 9263 /* Give up focus if we are no longer focusable */ 9264 clearFocus(); 9265 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 9266 && ((privateFlags & PFLAG_FOCUSED) == 0)) { 9267 /* 9268 * Tell the view system that we are now available to take focus 9269 * if no one else already has it. 9270 */ 9271 if (mParent != null) mParent.focusableViewAvailable(this); 9272 } 9273 } 9274 9275 final int newVisibility = flags & VISIBILITY_MASK; 9276 if (newVisibility == VISIBLE) { 9277 if ((changed & VISIBILITY_MASK) != 0) { 9278 /* 9279 * If this view is becoming visible, invalidate it in case it changed while 9280 * it was not visible. Marking it drawn ensures that the invalidation will 9281 * go through. 9282 */ 9283 mPrivateFlags |= PFLAG_DRAWN; 9284 invalidate(true); 9285 9286 needGlobalAttributesUpdate(true); 9287 9288 // a view becoming visible is worth notifying the parent 9289 // about in case nothing has focus. even if this specific view 9290 // isn't focusable, it may contain something that is, so let 9291 // the root view try to give this focus if nothing else does. 9292 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 9293 mParent.focusableViewAvailable(this); 9294 } 9295 } 9296 } 9297 9298 /* Check if the GONE bit has changed */ 9299 if ((changed & GONE) != 0) { 9300 needGlobalAttributesUpdate(false); 9301 requestLayout(); 9302 9303 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 9304 if (hasFocus()) clearFocus(); 9305 clearAccessibilityFocus(); 9306 destroyDrawingCache(); 9307 if (mParent instanceof View) { 9308 // GONE views noop invalidation, so invalidate the parent 9309 ((View) mParent).invalidate(true); 9310 } 9311 // Mark the view drawn to ensure that it gets invalidated properly the next 9312 // time it is visible and gets invalidated 9313 mPrivateFlags |= PFLAG_DRAWN; 9314 } 9315 if (mAttachInfo != null) { 9316 mAttachInfo.mViewVisibilityChanged = true; 9317 } 9318 } 9319 9320 /* Check if the VISIBLE bit has changed */ 9321 if ((changed & INVISIBLE) != 0) { 9322 needGlobalAttributesUpdate(false); 9323 /* 9324 * If this view is becoming invisible, set the DRAWN flag so that 9325 * the next invalidate() will not be skipped. 9326 */ 9327 mPrivateFlags |= PFLAG_DRAWN; 9328 9329 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) { 9330 // root view becoming invisible shouldn't clear focus and accessibility focus 9331 if (getRootView() != this) { 9332 if (hasFocus()) clearFocus(); 9333 clearAccessibilityFocus(); 9334 } 9335 } 9336 if (mAttachInfo != null) { 9337 mAttachInfo.mViewVisibilityChanged = true; 9338 } 9339 } 9340 9341 if ((changed & VISIBILITY_MASK) != 0) { 9342 // If the view is invisible, cleanup its display list to free up resources 9343 if (newVisibility != VISIBLE && mAttachInfo != null) { 9344 cleanupDraw(); 9345 } 9346 9347 if (mParent instanceof ViewGroup) { 9348 ((ViewGroup) mParent).onChildVisibilityChanged(this, 9349 (changed & VISIBILITY_MASK), newVisibility); 9350 ((View) mParent).invalidate(true); 9351 } else if (mParent != null) { 9352 mParent.invalidateChild(this, null); 9353 } 9354 dispatchVisibilityChanged(this, newVisibility); 9355 9356 notifySubtreeAccessibilityStateChangedIfNeeded(); 9357 } 9358 9359 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 9360 destroyDrawingCache(); 9361 } 9362 9363 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 9364 destroyDrawingCache(); 9365 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 9366 invalidateParentCaches(); 9367 } 9368 9369 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 9370 destroyDrawingCache(); 9371 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 9372 } 9373 9374 if ((changed & DRAW_MASK) != 0) { 9375 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 9376 if (mBackground != null) { 9377 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 9378 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 9379 } else { 9380 mPrivateFlags |= PFLAG_SKIP_DRAW; 9381 } 9382 } else { 9383 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 9384 } 9385 requestLayout(); 9386 invalidate(true); 9387 } 9388 9389 if ((changed & KEEP_SCREEN_ON) != 0) { 9390 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 9391 mParent.recomputeViewAttributes(this); 9392 } 9393 } 9394 9395 if (accessibilityEnabled) { 9396 if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0 9397 || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) { 9398 if (oldIncludeForAccessibility != includeForAccessibility()) { 9399 notifySubtreeAccessibilityStateChangedIfNeeded(); 9400 } else { 9401 notifyViewAccessibilityStateChangedIfNeeded( 9402 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9403 } 9404 } else if ((changed & ENABLED_MASK) != 0) { 9405 notifyViewAccessibilityStateChangedIfNeeded( 9406 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9407 } 9408 } 9409 } 9410 9411 /** 9412 * Change the view's z order in the tree, so it's on top of other sibling 9413 * views. This ordering change may affect layout, if the parent container 9414 * uses an order-dependent layout scheme (e.g., LinearLayout). Prior 9415 * to {@link android.os.Build.VERSION_CODES#KITKAT} this 9416 * method should be followed by calls to {@link #requestLayout()} and 9417 * {@link View#invalidate()} on the view's parent to force the parent to redraw 9418 * with the new child ordering. 9419 * 9420 * @see ViewGroup#bringChildToFront(View) 9421 */ 9422 public void bringToFront() { 9423 if (mParent != null) { 9424 mParent.bringChildToFront(this); 9425 } 9426 } 9427 9428 /** 9429 * This is called in response to an internal scroll in this view (i.e., the 9430 * view scrolled its own contents). This is typically as a result of 9431 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 9432 * called. 9433 * 9434 * @param l Current horizontal scroll origin. 9435 * @param t Current vertical scroll origin. 9436 * @param oldl Previous horizontal scroll origin. 9437 * @param oldt Previous vertical scroll origin. 9438 */ 9439 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 9440 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 9441 postSendViewScrolledAccessibilityEventCallback(); 9442 } 9443 9444 mBackgroundSizeChanged = true; 9445 9446 final AttachInfo ai = mAttachInfo; 9447 if (ai != null) { 9448 ai.mViewScrollChanged = true; 9449 } 9450 } 9451 9452 /** 9453 * Interface definition for a callback to be invoked when the layout bounds of a view 9454 * changes due to layout processing. 9455 */ 9456 public interface OnLayoutChangeListener { 9457 /** 9458 * Called when the layout bounds of a view changes due to layout processing. 9459 * 9460 * @param v The view whose bounds have changed. 9461 * @param left The new value of the view's left property. 9462 * @param top The new value of the view's top property. 9463 * @param right The new value of the view's right property. 9464 * @param bottom The new value of the view's bottom property. 9465 * @param oldLeft The previous value of the view's left property. 9466 * @param oldTop The previous value of the view's top property. 9467 * @param oldRight The previous value of the view's right property. 9468 * @param oldBottom The previous value of the view's bottom property. 9469 */ 9470 void onLayoutChange(View v, int left, int top, int right, int bottom, 9471 int oldLeft, int oldTop, int oldRight, int oldBottom); 9472 } 9473 9474 /** 9475 * This is called during layout when the size of this view has changed. If 9476 * you were just added to the view hierarchy, you're called with the old 9477 * values of 0. 9478 * 9479 * @param w Current width of this view. 9480 * @param h Current height of this view. 9481 * @param oldw Old width of this view. 9482 * @param oldh Old height of this view. 9483 */ 9484 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 9485 } 9486 9487 /** 9488 * Called by draw to draw the child views. This may be overridden 9489 * by derived classes to gain control just before its children are drawn 9490 * (but after its own view has been drawn). 9491 * @param canvas the canvas on which to draw the view 9492 */ 9493 protected void dispatchDraw(Canvas canvas) { 9494 9495 } 9496 9497 /** 9498 * Gets the parent of this view. Note that the parent is a 9499 * ViewParent and not necessarily a View. 9500 * 9501 * @return Parent of this view. 9502 */ 9503 public final ViewParent getParent() { 9504 return mParent; 9505 } 9506 9507 /** 9508 * Set the horizontal scrolled position of your view. This will cause a call to 9509 * {@link #onScrollChanged(int, int, int, int)} and the view will be 9510 * invalidated. 9511 * @param value the x position to scroll to 9512 */ 9513 public void setScrollX(int value) { 9514 scrollTo(value, mScrollY); 9515 } 9516 9517 /** 9518 * Set the vertical scrolled position of your view. This will cause a call to 9519 * {@link #onScrollChanged(int, int, int, int)} and the view will be 9520 * invalidated. 9521 * @param value the y position to scroll to 9522 */ 9523 public void setScrollY(int value) { 9524 scrollTo(mScrollX, value); 9525 } 9526 9527 /** 9528 * Return the scrolled left position of this view. This is the left edge of 9529 * the displayed part of your view. You do not need to draw any pixels 9530 * farther left, since those are outside of the frame of your view on 9531 * screen. 9532 * 9533 * @return The left edge of the displayed part of your view, in pixels. 9534 */ 9535 public final int getScrollX() { 9536 return mScrollX; 9537 } 9538 9539 /** 9540 * Return the scrolled top position of this view. This is the top edge of 9541 * the displayed part of your view. You do not need to draw any pixels above 9542 * it, since those are outside of the frame of your view on screen. 9543 * 9544 * @return The top edge of the displayed part of your view, in pixels. 9545 */ 9546 public final int getScrollY() { 9547 return mScrollY; 9548 } 9549 9550 /** 9551 * Return the width of the your view. 9552 * 9553 * @return The width of your view, in pixels. 9554 */ 9555 @ViewDebug.ExportedProperty(category = "layout") 9556 public final int getWidth() { 9557 return mRight - mLeft; 9558 } 9559 9560 /** 9561 * Return the height of your view. 9562 * 9563 * @return The height of your view, in pixels. 9564 */ 9565 @ViewDebug.ExportedProperty(category = "layout") 9566 public final int getHeight() { 9567 return mBottom - mTop; 9568 } 9569 9570 /** 9571 * Return the visible drawing bounds of your view. Fills in the output 9572 * rectangle with the values from getScrollX(), getScrollY(), 9573 * getWidth(), and getHeight(). These bounds do not account for any 9574 * transformation properties currently set on the view, such as 9575 * {@link #setScaleX(float)} or {@link #setRotation(float)}. 9576 * 9577 * @param outRect The (scrolled) drawing bounds of the view. 9578 */ 9579 public void getDrawingRect(Rect outRect) { 9580 outRect.left = mScrollX; 9581 outRect.top = mScrollY; 9582 outRect.right = mScrollX + (mRight - mLeft); 9583 outRect.bottom = mScrollY + (mBottom - mTop); 9584 } 9585 9586 /** 9587 * Like {@link #getMeasuredWidthAndState()}, but only returns the 9588 * raw width component (that is the result is masked by 9589 * {@link #MEASURED_SIZE_MASK}). 9590 * 9591 * @return The raw measured width of this view. 9592 */ 9593 public final int getMeasuredWidth() { 9594 return mMeasuredWidth & MEASURED_SIZE_MASK; 9595 } 9596 9597 /** 9598 * Return the full width measurement information for this view as computed 9599 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 9600 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 9601 * This should be used during measurement and layout calculations only. Use 9602 * {@link #getWidth()} to see how wide a view is after layout. 9603 * 9604 * @return The measured width of this view as a bit mask. 9605 */ 9606 public final int getMeasuredWidthAndState() { 9607 return mMeasuredWidth; 9608 } 9609 9610 /** 9611 * Like {@link #getMeasuredHeightAndState()}, but only returns the 9612 * raw width component (that is the result is masked by 9613 * {@link #MEASURED_SIZE_MASK}). 9614 * 9615 * @return The raw measured height of this view. 9616 */ 9617 public final int getMeasuredHeight() { 9618 return mMeasuredHeight & MEASURED_SIZE_MASK; 9619 } 9620 9621 /** 9622 * Return the full height measurement information for this view as computed 9623 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 9624 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 9625 * This should be used during measurement and layout calculations only. Use 9626 * {@link #getHeight()} to see how wide a view is after layout. 9627 * 9628 * @return The measured width of this view as a bit mask. 9629 */ 9630 public final int getMeasuredHeightAndState() { 9631 return mMeasuredHeight; 9632 } 9633 9634 /** 9635 * Return only the state bits of {@link #getMeasuredWidthAndState()} 9636 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 9637 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 9638 * and the height component is at the shifted bits 9639 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 9640 */ 9641 public final int getMeasuredState() { 9642 return (mMeasuredWidth&MEASURED_STATE_MASK) 9643 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 9644 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 9645 } 9646 9647 /** 9648 * The transform matrix of this view, which is calculated based on the current 9649 * roation, scale, and pivot properties. 9650 * 9651 * @see #getRotation() 9652 * @see #getScaleX() 9653 * @see #getScaleY() 9654 * @see #getPivotX() 9655 * @see #getPivotY() 9656 * @return The current transform matrix for the view 9657 */ 9658 public Matrix getMatrix() { 9659 ensureTransformationInfo(); 9660 final Matrix matrix = mTransformationInfo.mMatrix; 9661 mRenderNode.getMatrix(matrix); 9662 return matrix; 9663 } 9664 9665 /** 9666 * Returns true if the transform matrix is the identity matrix. 9667 * Recomputes the matrix if necessary. 9668 * 9669 * @return True if the transform matrix is the identity matrix, false otherwise. 9670 */ 9671 final boolean hasIdentityMatrix() { 9672 return mRenderNode.hasIdentityMatrix(); 9673 } 9674 9675 void ensureTransformationInfo() { 9676 if (mTransformationInfo == null) { 9677 mTransformationInfo = new TransformationInfo(); 9678 } 9679 } 9680 9681 /** 9682 * Utility method to retrieve the inverse of the current mMatrix property. 9683 * We cache the matrix to avoid recalculating it when transform properties 9684 * have not changed. 9685 * 9686 * @return The inverse of the current matrix of this view. 9687 */ 9688 final Matrix getInverseMatrix() { 9689 ensureTransformationInfo(); 9690 if (mTransformationInfo.mInverseMatrix == null) { 9691 mTransformationInfo.mInverseMatrix = new Matrix(); 9692 } 9693 final Matrix matrix = mTransformationInfo.mInverseMatrix; 9694 mRenderNode.getInverseMatrix(matrix); 9695 return matrix; 9696 } 9697 9698 /** 9699 * Gets the distance along the Z axis from the camera to this view. 9700 * 9701 * @see #setCameraDistance(float) 9702 * 9703 * @return The distance along the Z axis. 9704 */ 9705 public float getCameraDistance() { 9706 final float dpi = mResources.getDisplayMetrics().densityDpi; 9707 return -(mRenderNode.getCameraDistance() * dpi); 9708 } 9709 9710 /** 9711 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 9712 * views are drawn) from the camera to this view. The camera's distance 9713 * affects 3D transformations, for instance rotations around the X and Y 9714 * axis. If the rotationX or rotationY properties are changed and this view is 9715 * large (more than half the size of the screen), it is recommended to always 9716 * use a camera distance that's greater than the height (X axis rotation) or 9717 * the width (Y axis rotation) of this view.</p> 9718 * 9719 * <p>The distance of the camera from the view plane can have an affect on the 9720 * perspective distortion of the view when it is rotated around the x or y axis. 9721 * For example, a large distance will result in a large viewing angle, and there 9722 * will not be much perspective distortion of the view as it rotates. A short 9723 * distance may cause much more perspective distortion upon rotation, and can 9724 * also result in some drawing artifacts if the rotated view ends up partially 9725 * behind the camera (which is why the recommendation is to use a distance at 9726 * least as far as the size of the view, if the view is to be rotated.)</p> 9727 * 9728 * <p>The distance is expressed in "depth pixels." The default distance depends 9729 * on the screen density. For instance, on a medium density display, the 9730 * default distance is 1280. On a high density display, the default distance 9731 * is 1920.</p> 9732 * 9733 * <p>If you want to specify a distance that leads to visually consistent 9734 * results across various densities, use the following formula:</p> 9735 * <pre> 9736 * float scale = context.getResources().getDisplayMetrics().density; 9737 * view.setCameraDistance(distance * scale); 9738 * </pre> 9739 * 9740 * <p>The density scale factor of a high density display is 1.5, 9741 * and 1920 = 1280 * 1.5.</p> 9742 * 9743 * @param distance The distance in "depth pixels", if negative the opposite 9744 * value is used 9745 * 9746 * @see #setRotationX(float) 9747 * @see #setRotationY(float) 9748 */ 9749 public void setCameraDistance(float distance) { 9750 final float dpi = mResources.getDisplayMetrics().densityDpi; 9751 9752 invalidateViewProperty(true, false); 9753 mRenderNode.setCameraDistance(-Math.abs(distance) / dpi); 9754 invalidateViewProperty(false, false); 9755 9756 invalidateParentIfNeededAndWasQuickRejected(); 9757 } 9758 9759 /** 9760 * The degrees that the view is rotated around the pivot point. 9761 * 9762 * @see #setRotation(float) 9763 * @see #getPivotX() 9764 * @see #getPivotY() 9765 * 9766 * @return The degrees of rotation. 9767 */ 9768 @ViewDebug.ExportedProperty(category = "drawing") 9769 public float getRotation() { 9770 return mRenderNode.getRotation(); 9771 } 9772 9773 /** 9774 * Sets the degrees that the view is rotated around the pivot point. Increasing values 9775 * result in clockwise rotation. 9776 * 9777 * @param rotation The degrees of rotation. 9778 * 9779 * @see #getRotation() 9780 * @see #getPivotX() 9781 * @see #getPivotY() 9782 * @see #setRotationX(float) 9783 * @see #setRotationY(float) 9784 * 9785 * @attr ref android.R.styleable#View_rotation 9786 */ 9787 public void setRotation(float rotation) { 9788 if (rotation != getRotation()) { 9789 // Double-invalidation is necessary to capture view's old and new areas 9790 invalidateViewProperty(true, false); 9791 mRenderNode.setRotation(rotation); 9792 invalidateViewProperty(false, true); 9793 9794 invalidateParentIfNeededAndWasQuickRejected(); 9795 notifySubtreeAccessibilityStateChangedIfNeeded(); 9796 } 9797 } 9798 9799 /** 9800 * The degrees that the view is rotated around the vertical axis through the pivot point. 9801 * 9802 * @see #getPivotX() 9803 * @see #getPivotY() 9804 * @see #setRotationY(float) 9805 * 9806 * @return The degrees of Y rotation. 9807 */ 9808 @ViewDebug.ExportedProperty(category = "drawing") 9809 public float getRotationY() { 9810 return mRenderNode.getRotationY(); 9811 } 9812 9813 /** 9814 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 9815 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 9816 * down the y axis. 9817 * 9818 * When rotating large views, it is recommended to adjust the camera distance 9819 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 9820 * 9821 * @param rotationY The degrees of Y rotation. 9822 * 9823 * @see #getRotationY() 9824 * @see #getPivotX() 9825 * @see #getPivotY() 9826 * @see #setRotation(float) 9827 * @see #setRotationX(float) 9828 * @see #setCameraDistance(float) 9829 * 9830 * @attr ref android.R.styleable#View_rotationY 9831 */ 9832 public void setRotationY(float rotationY) { 9833 if (rotationY != getRotationY()) { 9834 invalidateViewProperty(true, false); 9835 mRenderNode.setRotationY(rotationY); 9836 invalidateViewProperty(false, true); 9837 9838 invalidateParentIfNeededAndWasQuickRejected(); 9839 notifySubtreeAccessibilityStateChangedIfNeeded(); 9840 } 9841 } 9842 9843 /** 9844 * The degrees that the view is rotated around the horizontal axis through the pivot point. 9845 * 9846 * @see #getPivotX() 9847 * @see #getPivotY() 9848 * @see #setRotationX(float) 9849 * 9850 * @return The degrees of X rotation. 9851 */ 9852 @ViewDebug.ExportedProperty(category = "drawing") 9853 public float getRotationX() { 9854 return mRenderNode.getRotationX(); 9855 } 9856 9857 /** 9858 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 9859 * Increasing values result in clockwise rotation from the viewpoint of looking down the 9860 * x axis. 9861 * 9862 * When rotating large views, it is recommended to adjust the camera distance 9863 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 9864 * 9865 * @param rotationX The degrees of X rotation. 9866 * 9867 * @see #getRotationX() 9868 * @see #getPivotX() 9869 * @see #getPivotY() 9870 * @see #setRotation(float) 9871 * @see #setRotationY(float) 9872 * @see #setCameraDistance(float) 9873 * 9874 * @attr ref android.R.styleable#View_rotationX 9875 */ 9876 public void setRotationX(float rotationX) { 9877 if (rotationX != getRotationX()) { 9878 invalidateViewProperty(true, false); 9879 mRenderNode.setRotationX(rotationX); 9880 invalidateViewProperty(false, true); 9881 9882 invalidateParentIfNeededAndWasQuickRejected(); 9883 notifySubtreeAccessibilityStateChangedIfNeeded(); 9884 } 9885 } 9886 9887 /** 9888 * The amount that the view is scaled in x around the pivot point, as a proportion of 9889 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 9890 * 9891 * <p>By default, this is 1.0f. 9892 * 9893 * @see #getPivotX() 9894 * @see #getPivotY() 9895 * @return The scaling factor. 9896 */ 9897 @ViewDebug.ExportedProperty(category = "drawing") 9898 public float getScaleX() { 9899 return mRenderNode.getScaleX(); 9900 } 9901 9902 /** 9903 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 9904 * the view's unscaled width. A value of 1 means that no scaling is applied. 9905 * 9906 * @param scaleX The scaling factor. 9907 * @see #getPivotX() 9908 * @see #getPivotY() 9909 * 9910 * @attr ref android.R.styleable#View_scaleX 9911 */ 9912 public void setScaleX(float scaleX) { 9913 if (scaleX != getScaleX()) { 9914 invalidateViewProperty(true, false); 9915 mRenderNode.setScaleX(scaleX); 9916 invalidateViewProperty(false, true); 9917 9918 invalidateParentIfNeededAndWasQuickRejected(); 9919 notifySubtreeAccessibilityStateChangedIfNeeded(); 9920 } 9921 } 9922 9923 /** 9924 * The amount that the view is scaled in y around the pivot point, as a proportion of 9925 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 9926 * 9927 * <p>By default, this is 1.0f. 9928 * 9929 * @see #getPivotX() 9930 * @see #getPivotY() 9931 * @return The scaling factor. 9932 */ 9933 @ViewDebug.ExportedProperty(category = "drawing") 9934 public float getScaleY() { 9935 return mRenderNode.getScaleY(); 9936 } 9937 9938 /** 9939 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 9940 * the view's unscaled width. A value of 1 means that no scaling is applied. 9941 * 9942 * @param scaleY The scaling factor. 9943 * @see #getPivotX() 9944 * @see #getPivotY() 9945 * 9946 * @attr ref android.R.styleable#View_scaleY 9947 */ 9948 public void setScaleY(float scaleY) { 9949 if (scaleY != getScaleY()) { 9950 invalidateViewProperty(true, false); 9951 mRenderNode.setScaleY(scaleY); 9952 invalidateViewProperty(false, true); 9953 9954 invalidateParentIfNeededAndWasQuickRejected(); 9955 notifySubtreeAccessibilityStateChangedIfNeeded(); 9956 } 9957 } 9958 9959 /** 9960 * The x location of the point around which the view is {@link #setRotation(float) rotated} 9961 * and {@link #setScaleX(float) scaled}. 9962 * 9963 * @see #getRotation() 9964 * @see #getScaleX() 9965 * @see #getScaleY() 9966 * @see #getPivotY() 9967 * @return The x location of the pivot point. 9968 * 9969 * @attr ref android.R.styleable#View_transformPivotX 9970 */ 9971 @ViewDebug.ExportedProperty(category = "drawing") 9972 public float getPivotX() { 9973 return mRenderNode.getPivotX(); 9974 } 9975 9976 /** 9977 * Sets the x location of the point around which the view is 9978 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 9979 * By default, the pivot point is centered on the object. 9980 * Setting this property disables this behavior and causes the view to use only the 9981 * explicitly set pivotX and pivotY values. 9982 * 9983 * @param pivotX The x location of the pivot point. 9984 * @see #getRotation() 9985 * @see #getScaleX() 9986 * @see #getScaleY() 9987 * @see #getPivotY() 9988 * 9989 * @attr ref android.R.styleable#View_transformPivotX 9990 */ 9991 public void setPivotX(float pivotX) { 9992 if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) { 9993 invalidateViewProperty(true, false); 9994 mRenderNode.setPivotX(pivotX); 9995 invalidateViewProperty(false, true); 9996 9997 invalidateParentIfNeededAndWasQuickRejected(); 9998 } 9999 } 10000 10001 /** 10002 * The y location of the point around which the view is {@link #setRotation(float) rotated} 10003 * and {@link #setScaleY(float) scaled}. 10004 * 10005 * @see #getRotation() 10006 * @see #getScaleX() 10007 * @see #getScaleY() 10008 * @see #getPivotY() 10009 * @return The y location of the pivot point. 10010 * 10011 * @attr ref android.R.styleable#View_transformPivotY 10012 */ 10013 @ViewDebug.ExportedProperty(category = "drawing") 10014 public float getPivotY() { 10015 return mRenderNode.getPivotY(); 10016 } 10017 10018 /** 10019 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 10020 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 10021 * Setting this property disables this behavior and causes the view to use only the 10022 * explicitly set pivotX and pivotY values. 10023 * 10024 * @param pivotY The y location of the pivot point. 10025 * @see #getRotation() 10026 * @see #getScaleX() 10027 * @see #getScaleY() 10028 * @see #getPivotY() 10029 * 10030 * @attr ref android.R.styleable#View_transformPivotY 10031 */ 10032 public void setPivotY(float pivotY) { 10033 if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) { 10034 invalidateViewProperty(true, false); 10035 mRenderNode.setPivotY(pivotY); 10036 invalidateViewProperty(false, true); 10037 10038 invalidateParentIfNeededAndWasQuickRejected(); 10039 } 10040 } 10041 10042 /** 10043 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 10044 * completely transparent and 1 means the view is completely opaque. 10045 * 10046 * <p>By default this is 1.0f. 10047 * @return The opacity of the view. 10048 */ 10049 @ViewDebug.ExportedProperty(category = "drawing") 10050 public float getAlpha() { 10051 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 10052 } 10053 10054 /** 10055 * Returns whether this View has content which overlaps. 10056 * 10057 * <p>This function, intended to be overridden by specific View types, is an optimization when 10058 * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to 10059 * an offscreen buffer and then composited into place, which can be expensive. If the view has 10060 * no overlapping rendering, the view can draw each primitive with the appropriate alpha value 10061 * directly. An example of overlapping rendering is a TextView with a background image, such as 10062 * a Button. An example of non-overlapping rendering is a TextView with no background, or an 10063 * ImageView with only the foreground image. The default implementation returns true; subclasses 10064 * should override if they have cases which can be optimized.</p> 10065 * 10066 * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas} 10067 * necessitates that a View return true if it uses the methods internally without passing the 10068 * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p> 10069 * 10070 * @return true if the content in this view might overlap, false otherwise. 10071 */ 10072 public boolean hasOverlappingRendering() { 10073 return true; 10074 } 10075 10076 /** 10077 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is 10078 * completely transparent and 1 means the view is completely opaque.</p> 10079 * 10080 * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant 10081 * performance implications, especially for large views. It is best to use the alpha property 10082 * sparingly and transiently, as in the case of fading animations.</p> 10083 * 10084 * <p>For a view with a frequently changing alpha, such as during a fading animation, it is 10085 * strongly recommended for performance reasons to either override 10086 * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a 10087 * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p> 10088 * 10089 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 10090 * responsible for applying the opacity itself.</p> 10091 * 10092 * <p>Note that if the view is backed by a 10093 * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a 10094 * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than 10095 * 1.0 will supercede the alpha of the layer paint.</p> 10096 * 10097 * @param alpha The opacity of the view. 10098 * 10099 * @see #hasOverlappingRendering() 10100 * @see #setLayerType(int, android.graphics.Paint) 10101 * 10102 * @attr ref android.R.styleable#View_alpha 10103 */ 10104 public void setAlpha(float alpha) { 10105 ensureTransformationInfo(); 10106 if (mTransformationInfo.mAlpha != alpha) { 10107 mTransformationInfo.mAlpha = alpha; 10108 if (onSetAlpha((int) (alpha * 255))) { 10109 mPrivateFlags |= PFLAG_ALPHA_SET; 10110 // subclass is handling alpha - don't optimize rendering cache invalidation 10111 invalidateParentCaches(); 10112 invalidate(true); 10113 } else { 10114 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10115 invalidateViewProperty(true, false); 10116 mRenderNode.setAlpha(getFinalAlpha()); 10117 notifyViewAccessibilityStateChangedIfNeeded( 10118 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 10119 } 10120 } 10121 } 10122 10123 /** 10124 * Faster version of setAlpha() which performs the same steps except there are 10125 * no calls to invalidate(). The caller of this function should perform proper invalidation 10126 * on the parent and this object. The return value indicates whether the subclass handles 10127 * alpha (the return value for onSetAlpha()). 10128 * 10129 * @param alpha The new value for the alpha property 10130 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 10131 * the new value for the alpha property is different from the old value 10132 */ 10133 boolean setAlphaNoInvalidation(float alpha) { 10134 ensureTransformationInfo(); 10135 if (mTransformationInfo.mAlpha != alpha) { 10136 mTransformationInfo.mAlpha = alpha; 10137 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 10138 if (subclassHandlesAlpha) { 10139 mPrivateFlags |= PFLAG_ALPHA_SET; 10140 return true; 10141 } else { 10142 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10143 mRenderNode.setAlpha(getFinalAlpha()); 10144 } 10145 } 10146 return false; 10147 } 10148 10149 /** 10150 * This property is hidden and intended only for use by the Fade transition, which 10151 * animates it to produce a visual translucency that does not side-effect (or get 10152 * affected by) the real alpha property. This value is composited with the other 10153 * alpha value (and the AlphaAnimation value, when that is present) to produce 10154 * a final visual translucency result, which is what is passed into the DisplayList. 10155 * 10156 * @hide 10157 */ 10158 public void setTransitionAlpha(float alpha) { 10159 ensureTransformationInfo(); 10160 if (mTransformationInfo.mTransitionAlpha != alpha) { 10161 mTransformationInfo.mTransitionAlpha = alpha; 10162 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10163 invalidateViewProperty(true, false); 10164 mRenderNode.setAlpha(getFinalAlpha()); 10165 } 10166 } 10167 10168 /** 10169 * Calculates the visual alpha of this view, which is a combination of the actual 10170 * alpha value and the transitionAlpha value (if set). 10171 */ 10172 private float getFinalAlpha() { 10173 if (mTransformationInfo != null) { 10174 return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha; 10175 } 10176 return 1; 10177 } 10178 10179 /** 10180 * This property is hidden and intended only for use by the Fade transition, which 10181 * animates it to produce a visual translucency that does not side-effect (or get 10182 * affected by) the real alpha property. This value is composited with the other 10183 * alpha value (and the AlphaAnimation value, when that is present) to produce 10184 * a final visual translucency result, which is what is passed into the DisplayList. 10185 * 10186 * @hide 10187 */ 10188 public float getTransitionAlpha() { 10189 return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1; 10190 } 10191 10192 /** 10193 * Top position of this view relative to its parent. 10194 * 10195 * @return The top of this view, in pixels. 10196 */ 10197 @ViewDebug.CapturedViewProperty 10198 public final int getTop() { 10199 return mTop; 10200 } 10201 10202 /** 10203 * Sets the top position of this view relative to its parent. This method is meant to be called 10204 * by the layout system and should not generally be called otherwise, because the property 10205 * may be changed at any time by the layout. 10206 * 10207 * @param top The top of this view, in pixels. 10208 */ 10209 public final void setTop(int top) { 10210 if (top != mTop) { 10211 final boolean matrixIsIdentity = hasIdentityMatrix(); 10212 if (matrixIsIdentity) { 10213 if (mAttachInfo != null) { 10214 int minTop; 10215 int yLoc; 10216 if (top < mTop) { 10217 minTop = top; 10218 yLoc = top - mTop; 10219 } else { 10220 minTop = mTop; 10221 yLoc = 0; 10222 } 10223 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 10224 } 10225 } else { 10226 // Double-invalidation is necessary to capture view's old and new areas 10227 invalidate(true); 10228 } 10229 10230 int width = mRight - mLeft; 10231 int oldHeight = mBottom - mTop; 10232 10233 mTop = top; 10234 mRenderNode.setTop(mTop); 10235 10236 sizeChange(width, mBottom - mTop, width, oldHeight); 10237 10238 if (!matrixIsIdentity) { 10239 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10240 invalidate(true); 10241 } 10242 mBackgroundSizeChanged = true; 10243 invalidateParentIfNeeded(); 10244 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10245 // View was rejected last time it was drawn by its parent; this may have changed 10246 invalidateParentIfNeeded(); 10247 } 10248 } 10249 } 10250 10251 /** 10252 * Bottom position of this view relative to its parent. 10253 * 10254 * @return The bottom of this view, in pixels. 10255 */ 10256 @ViewDebug.CapturedViewProperty 10257 public final int getBottom() { 10258 return mBottom; 10259 } 10260 10261 /** 10262 * True if this view has changed since the last time being drawn. 10263 * 10264 * @return The dirty state of this view. 10265 */ 10266 public boolean isDirty() { 10267 return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0; 10268 } 10269 10270 /** 10271 * Sets the bottom position of this view relative to its parent. This method is meant to be 10272 * called by the layout system and should not generally be called otherwise, because the 10273 * property may be changed at any time by the layout. 10274 * 10275 * @param bottom The bottom of this view, in pixels. 10276 */ 10277 public final void setBottom(int bottom) { 10278 if (bottom != mBottom) { 10279 final boolean matrixIsIdentity = hasIdentityMatrix(); 10280 if (matrixIsIdentity) { 10281 if (mAttachInfo != null) { 10282 int maxBottom; 10283 if (bottom < mBottom) { 10284 maxBottom = mBottom; 10285 } else { 10286 maxBottom = bottom; 10287 } 10288 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 10289 } 10290 } else { 10291 // Double-invalidation is necessary to capture view's old and new areas 10292 invalidate(true); 10293 } 10294 10295 int width = mRight - mLeft; 10296 int oldHeight = mBottom - mTop; 10297 10298 mBottom = bottom; 10299 mRenderNode.setBottom(mBottom); 10300 10301 sizeChange(width, mBottom - mTop, width, oldHeight); 10302 10303 if (!matrixIsIdentity) { 10304 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10305 invalidate(true); 10306 } 10307 mBackgroundSizeChanged = true; 10308 invalidateParentIfNeeded(); 10309 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10310 // View was rejected last time it was drawn by its parent; this may have changed 10311 invalidateParentIfNeeded(); 10312 } 10313 } 10314 } 10315 10316 /** 10317 * Left position of this view relative to its parent. 10318 * 10319 * @return The left edge of this view, in pixels. 10320 */ 10321 @ViewDebug.CapturedViewProperty 10322 public final int getLeft() { 10323 return mLeft; 10324 } 10325 10326 /** 10327 * Sets the left position of this view relative to its parent. This method is meant to be called 10328 * by the layout system and should not generally be called otherwise, because the property 10329 * may be changed at any time by the layout. 10330 * 10331 * @param left The left of this view, in pixels. 10332 */ 10333 public final void setLeft(int left) { 10334 if (left != mLeft) { 10335 final boolean matrixIsIdentity = hasIdentityMatrix(); 10336 if (matrixIsIdentity) { 10337 if (mAttachInfo != null) { 10338 int minLeft; 10339 int xLoc; 10340 if (left < mLeft) { 10341 minLeft = left; 10342 xLoc = left - mLeft; 10343 } else { 10344 minLeft = mLeft; 10345 xLoc = 0; 10346 } 10347 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 10348 } 10349 } else { 10350 // Double-invalidation is necessary to capture view's old and new areas 10351 invalidate(true); 10352 } 10353 10354 int oldWidth = mRight - mLeft; 10355 int height = mBottom - mTop; 10356 10357 mLeft = left; 10358 mRenderNode.setLeft(left); 10359 10360 sizeChange(mRight - mLeft, height, oldWidth, height); 10361 10362 if (!matrixIsIdentity) { 10363 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10364 invalidate(true); 10365 } 10366 mBackgroundSizeChanged = true; 10367 invalidateParentIfNeeded(); 10368 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10369 // View was rejected last time it was drawn by its parent; this may have changed 10370 invalidateParentIfNeeded(); 10371 } 10372 } 10373 } 10374 10375 /** 10376 * Right position of this view relative to its parent. 10377 * 10378 * @return The right edge of this view, in pixels. 10379 */ 10380 @ViewDebug.CapturedViewProperty 10381 public final int getRight() { 10382 return mRight; 10383 } 10384 10385 /** 10386 * Sets the right position of this view relative to its parent. This method is meant to be called 10387 * by the layout system and should not generally be called otherwise, because the property 10388 * may be changed at any time by the layout. 10389 * 10390 * @param right The right of this view, in pixels. 10391 */ 10392 public final void setRight(int right) { 10393 if (right != mRight) { 10394 final boolean matrixIsIdentity = hasIdentityMatrix(); 10395 if (matrixIsIdentity) { 10396 if (mAttachInfo != null) { 10397 int maxRight; 10398 if (right < mRight) { 10399 maxRight = mRight; 10400 } else { 10401 maxRight = right; 10402 } 10403 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 10404 } 10405 } else { 10406 // Double-invalidation is necessary to capture view's old and new areas 10407 invalidate(true); 10408 } 10409 10410 int oldWidth = mRight - mLeft; 10411 int height = mBottom - mTop; 10412 10413 mRight = right; 10414 mRenderNode.setRight(mRight); 10415 10416 sizeChange(mRight - mLeft, height, oldWidth, height); 10417 10418 if (!matrixIsIdentity) { 10419 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10420 invalidate(true); 10421 } 10422 mBackgroundSizeChanged = true; 10423 invalidateParentIfNeeded(); 10424 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10425 // View was rejected last time it was drawn by its parent; this may have changed 10426 invalidateParentIfNeeded(); 10427 } 10428 } 10429 } 10430 10431 /** 10432 * The visual x position of this view, in pixels. This is equivalent to the 10433 * {@link #setTranslationX(float) translationX} property plus the current 10434 * {@link #getLeft() left} property. 10435 * 10436 * @return The visual x position of this view, in pixels. 10437 */ 10438 @ViewDebug.ExportedProperty(category = "drawing") 10439 public float getX() { 10440 return mLeft + getTranslationX(); 10441 } 10442 10443 /** 10444 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 10445 * {@link #setTranslationX(float) translationX} property to be the difference between 10446 * the x value passed in and the current {@link #getLeft() left} property. 10447 * 10448 * @param x The visual x position of this view, in pixels. 10449 */ 10450 public void setX(float x) { 10451 setTranslationX(x - mLeft); 10452 } 10453 10454 /** 10455 * The visual y position of this view, in pixels. This is equivalent to the 10456 * {@link #setTranslationY(float) translationY} property plus the current 10457 * {@link #getTop() top} property. 10458 * 10459 * @return The visual y position of this view, in pixels. 10460 */ 10461 @ViewDebug.ExportedProperty(category = "drawing") 10462 public float getY() { 10463 return mTop + getTranslationY(); 10464 } 10465 10466 /** 10467 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 10468 * {@link #setTranslationY(float) translationY} property to be the difference between 10469 * the y value passed in and the current {@link #getTop() top} property. 10470 * 10471 * @param y The visual y position of this view, in pixels. 10472 */ 10473 public void setY(float y) { 10474 setTranslationY(y - mTop); 10475 } 10476 10477 /** 10478 * The visual z position of this view, in pixels. This is equivalent to the 10479 * {@link #setTranslationZ(float) translationZ} property plus the current 10480 * {@link #getElevation() elevation} property. 10481 * 10482 * @return The visual z position of this view, in pixels. 10483 */ 10484 @ViewDebug.ExportedProperty(category = "drawing") 10485 public float getZ() { 10486 return getElevation() + getTranslationZ(); 10487 } 10488 10489 /** 10490 * Sets the visual z position of this view, in pixels. This is equivalent to setting the 10491 * {@link #setTranslationZ(float) translationZ} property to be the difference between 10492 * the x value passed in and the current {@link #getElevation() elevation} property. 10493 * 10494 * @param z The visual z position of this view, in pixels. 10495 */ 10496 public void setZ(float z) { 10497 setTranslationZ(z - getElevation()); 10498 } 10499 10500 @ViewDebug.ExportedProperty(category = "drawing") 10501 public float getElevation() { 10502 return mRenderNode.getElevation(); 10503 } 10504 10505 /** 10506 * Sets the base depth location of this view. 10507 * 10508 * @attr ref android.R.styleable#View_elevation 10509 */ 10510 public void setElevation(float elevation) { 10511 if (elevation != getElevation()) { 10512 invalidateViewProperty(true, false); 10513 mRenderNode.setElevation(elevation); 10514 invalidateViewProperty(false, true); 10515 10516 invalidateParentIfNeededAndWasQuickRejected(); 10517 } 10518 } 10519 10520 /** 10521 * The horizontal location of this view relative to its {@link #getLeft() left} position. 10522 * This position is post-layout, in addition to wherever the object's 10523 * layout placed it. 10524 * 10525 * @return The horizontal position of this view relative to its left position, in pixels. 10526 */ 10527 @ViewDebug.ExportedProperty(category = "drawing") 10528 public float getTranslationX() { 10529 return mRenderNode.getTranslationX(); 10530 } 10531 10532 /** 10533 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 10534 * This effectively positions the object post-layout, in addition to wherever the object's 10535 * layout placed it. 10536 * 10537 * @param translationX The horizontal position of this view relative to its left position, 10538 * in pixels. 10539 * 10540 * @attr ref android.R.styleable#View_translationX 10541 */ 10542 public void setTranslationX(float translationX) { 10543 if (translationX != getTranslationX()) { 10544 invalidateViewProperty(true, false); 10545 mRenderNode.setTranslationX(translationX); 10546 invalidateViewProperty(false, true); 10547 10548 invalidateParentIfNeededAndWasQuickRejected(); 10549 notifySubtreeAccessibilityStateChangedIfNeeded(); 10550 } 10551 } 10552 10553 /** 10554 * The vertical location of this view relative to its {@link #getTop() top} position. 10555 * This position is post-layout, in addition to wherever the object's 10556 * layout placed it. 10557 * 10558 * @return The vertical position of this view relative to its top position, 10559 * in pixels. 10560 */ 10561 @ViewDebug.ExportedProperty(category = "drawing") 10562 public float getTranslationY() { 10563 return mRenderNode.getTranslationY(); 10564 } 10565 10566 /** 10567 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 10568 * This effectively positions the object post-layout, in addition to wherever the object's 10569 * layout placed it. 10570 * 10571 * @param translationY The vertical position of this view relative to its top position, 10572 * in pixels. 10573 * 10574 * @attr ref android.R.styleable#View_translationY 10575 */ 10576 public void setTranslationY(float translationY) { 10577 if (translationY != getTranslationY()) { 10578 invalidateViewProperty(true, false); 10579 mRenderNode.setTranslationY(translationY); 10580 invalidateViewProperty(false, true); 10581 10582 invalidateParentIfNeededAndWasQuickRejected(); 10583 } 10584 } 10585 10586 /** 10587 * The depth location of this view relative to its {@link #getElevation() elevation}. 10588 * 10589 * @return The depth of this view relative to its elevation. 10590 */ 10591 @ViewDebug.ExportedProperty(category = "drawing") 10592 public float getTranslationZ() { 10593 return mRenderNode.getTranslationZ(); 10594 } 10595 10596 /** 10597 * Sets the depth location of this view relative to its {@link #getElevation() elevation}. 10598 * 10599 * @attr ref android.R.styleable#View_translationZ 10600 */ 10601 public void setTranslationZ(float translationZ) { 10602 if (translationZ != getTranslationZ()) { 10603 invalidateViewProperty(true, false); 10604 mRenderNode.setTranslationZ(translationZ); 10605 invalidateViewProperty(false, true); 10606 10607 invalidateParentIfNeededAndWasQuickRejected(); 10608 } 10609 } 10610 10611 /** 10612 * Returns a ValueAnimator which can animate a clipping circle. 10613 * <p> 10614 * The View will be clipped to the animating circle. 10615 * <p> 10616 * Any shadow cast by the View will respect the circular clip from this animator. 10617 * 10618 * @param centerX The x coordinate of the center of the animating circle. 10619 * @param centerY The y coordinate of the center of the animating circle. 10620 * @param startRadius The starting radius of the animating circle. 10621 * @param endRadius The ending radius of the animating circle. 10622 */ 10623 public final ValueAnimator createRevealAnimator(int centerX, int centerY, 10624 float startRadius, float endRadius) { 10625 return RevealAnimator.ofRevealCircle(this, centerX, centerY, 10626 startRadius, endRadius, false); 10627 } 10628 10629 /** 10630 * Returns a ValueAnimator which can animate a clearing circle. 10631 * <p> 10632 * The View is prevented from drawing within the circle, so the content 10633 * behind the View shows through. 10634 * 10635 * @param centerX The x coordinate of the center of the animating circle. 10636 * @param centerY The y coordinate of the center of the animating circle. 10637 * @param startRadius The starting radius of the animating circle. 10638 * @param endRadius The ending radius of the animating circle. 10639 * 10640 * @hide 10641 */ 10642 public final ValueAnimator createClearCircleAnimator(int centerX, int centerY, 10643 float startRadius, float endRadius) { 10644 return RevealAnimator.ofRevealCircle(this, centerX, centerY, 10645 startRadius, endRadius, true); 10646 } 10647 10648 /** 10649 * Returns the current StateListAnimator if exists. 10650 * 10651 * @return StateListAnimator or null if it does not exists 10652 * @see #setStateListAnimator(android.animation.StateListAnimator) 10653 */ 10654 public StateListAnimator getStateListAnimator() { 10655 return mStateListAnimator; 10656 } 10657 10658 /** 10659 * Attaches the provided StateListAnimator to this View. 10660 * <p> 10661 * Any previously attached StateListAnimator will be detached. 10662 * 10663 * @param stateListAnimator The StateListAnimator to update the view 10664 * @see {@link android.animation.StateListAnimator} 10665 */ 10666 public void setStateListAnimator(StateListAnimator stateListAnimator) { 10667 if (mStateListAnimator == stateListAnimator) { 10668 return; 10669 } 10670 if (mStateListAnimator != null) { 10671 mStateListAnimator.setTarget(null); 10672 } 10673 mStateListAnimator = stateListAnimator; 10674 if (stateListAnimator != null) { 10675 stateListAnimator.setTarget(this); 10676 if (isAttachedToWindow()) { 10677 stateListAnimator.setState(getDrawableState()); 10678 } 10679 } 10680 } 10681 10682 /** 10683 * Sets the {@link Outline} of the view, which defines the shape of the shadow it 10684 * casts, and enables outline clipping. 10685 * <p> 10686 * By default, a View queries its Outline from its background drawable, via 10687 * {@link Drawable#getOutline(Outline)}. Manually setting the Outline with this method allows 10688 * this behavior to be overridden. 10689 * <p> 10690 * If the outline is {@link Outline#isEmpty()} or is <code>null</code>, 10691 * shadows will not be cast. 10692 * <p> 10693 * Only outlines that return true from {@link Outline#canClip()} may be used for clipping. 10694 * 10695 * @param outline The new outline of the view. 10696 * 10697 * @see #setClipToOutline(boolean) 10698 * @see #getClipToOutline() 10699 */ 10700 public void setOutline(@Nullable Outline outline) { 10701 mPrivateFlags3 |= PFLAG3_OUTLINE_DEFINED; 10702 10703 if (outline == null || outline.isEmpty()) { 10704 if (mOutline != null) { 10705 mOutline.setEmpty(); 10706 } 10707 } else { 10708 // always copy the path since caller may reuse 10709 if (mOutline == null) { 10710 mOutline = new Outline(); 10711 } 10712 mOutline.set(outline); 10713 } 10714 mRenderNode.setOutline(mOutline); 10715 } 10716 10717 /** 10718 * Returns whether the Outline should be used to clip the contents of the View. 10719 * <p> 10720 * Note that this flag will only be respected if the View's Outline returns true from 10721 * {@link Outline#canClip()}. 10722 * 10723 * @see #setOutline(Outline) 10724 * @see #setClipToOutline(boolean) 10725 */ 10726 public final boolean getClipToOutline() { 10727 return mRenderNode.getClipToOutline(); 10728 } 10729 10730 /** 10731 * Sets whether the View's Outline should be used to clip the contents of the View. 10732 * <p> 10733 * Note that this flag will only be respected if the View's Outline returns true from 10734 * {@link Outline#canClip()}. 10735 * 10736 * @see #setOutline(Outline) 10737 * @see #getClipToOutline() 10738 */ 10739 public void setClipToOutline(boolean clipToOutline) { 10740 damageInParent(); 10741 if (getClipToOutline() != clipToOutline) { 10742 mRenderNode.setClipToOutline(clipToOutline); 10743 } 10744 } 10745 10746 private void queryOutlineFromBackgroundIfUndefined() { 10747 if ((mPrivateFlags3 & PFLAG3_OUTLINE_DEFINED) == 0) { 10748 // Outline not currently defined, query from background 10749 if (mOutline == null) { 10750 mOutline = new Outline(); 10751 } else { 10752 //invalidate outline, to ensure background calculates it 10753 mOutline.setEmpty(); 10754 } 10755 if (mBackground.getOutline(mOutline)) { 10756 if (mOutline.isEmpty()) { 10757 throw new IllegalStateException("Background drawable failed to build outline"); 10758 } 10759 mRenderNode.setOutline(mOutline); 10760 } else { 10761 mRenderNode.setOutline(null); 10762 } 10763 notifySubtreeAccessibilityStateChangedIfNeeded(); 10764 } 10765 } 10766 10767 /** 10768 * Private API to be used for reveal animation 10769 * 10770 * @hide 10771 */ 10772 public void setRevealClip(boolean shouldClip, boolean inverseClip, 10773 float x, float y, float radius) { 10774 mRenderNode.setRevealClip(shouldClip, inverseClip, x, y, radius); 10775 // TODO: Handle this invalidate in a better way, or purely in native. 10776 invalidate(); 10777 } 10778 10779 /** 10780 * Hit rectangle in parent's coordinates 10781 * 10782 * @param outRect The hit rectangle of the view. 10783 */ 10784 public void getHitRect(Rect outRect) { 10785 if (hasIdentityMatrix() || mAttachInfo == null) { 10786 outRect.set(mLeft, mTop, mRight, mBottom); 10787 } else { 10788 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 10789 tmpRect.set(0, 0, getWidth(), getHeight()); 10790 getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect) 10791 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 10792 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 10793 } 10794 } 10795 10796 /** 10797 * Determines whether the given point, in local coordinates is inside the view. 10798 */ 10799 /*package*/ final boolean pointInView(float localX, float localY) { 10800 return localX >= 0 && localX < (mRight - mLeft) 10801 && localY >= 0 && localY < (mBottom - mTop); 10802 } 10803 10804 /** 10805 * Utility method to determine whether the given point, in local coordinates, 10806 * is inside the view, where the area of the view is expanded by the slop factor. 10807 * This method is called while processing touch-move events to determine if the event 10808 * is still within the view. 10809 * 10810 * @hide 10811 */ 10812 public boolean pointInView(float localX, float localY, float slop) { 10813 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 10814 localY < ((mBottom - mTop) + slop); 10815 } 10816 10817 /** 10818 * When a view has focus and the user navigates away from it, the next view is searched for 10819 * starting from the rectangle filled in by this method. 10820 * 10821 * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)}) 10822 * of the view. However, if your view maintains some idea of internal selection, 10823 * such as a cursor, or a selected row or column, you should override this method and 10824 * fill in a more specific rectangle. 10825 * 10826 * @param r The rectangle to fill in, in this view's coordinates. 10827 */ 10828 public void getFocusedRect(Rect r) { 10829 getDrawingRect(r); 10830 } 10831 10832 /** 10833 * If some part of this view is not clipped by any of its parents, then 10834 * return that area in r in global (root) coordinates. To convert r to local 10835 * coordinates (without taking possible View rotations into account), offset 10836 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 10837 * If the view is completely clipped or translated out, return false. 10838 * 10839 * @param r If true is returned, r holds the global coordinates of the 10840 * visible portion of this view. 10841 * @param globalOffset If true is returned, globalOffset holds the dx,dy 10842 * between this view and its root. globalOffet may be null. 10843 * @return true if r is non-empty (i.e. part of the view is visible at the 10844 * root level. 10845 */ 10846 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 10847 int width = mRight - mLeft; 10848 int height = mBottom - mTop; 10849 if (width > 0 && height > 0) { 10850 r.set(0, 0, width, height); 10851 if (globalOffset != null) { 10852 globalOffset.set(-mScrollX, -mScrollY); 10853 } 10854 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 10855 } 10856 return false; 10857 } 10858 10859 public final boolean getGlobalVisibleRect(Rect r) { 10860 return getGlobalVisibleRect(r, null); 10861 } 10862 10863 public final boolean getLocalVisibleRect(Rect r) { 10864 final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point(); 10865 if (getGlobalVisibleRect(r, offset)) { 10866 r.offset(-offset.x, -offset.y); // make r local 10867 return true; 10868 } 10869 return false; 10870 } 10871 10872 /** 10873 * Offset this view's vertical location by the specified number of pixels. 10874 * 10875 * @param offset the number of pixels to offset the view by 10876 */ 10877 public void offsetTopAndBottom(int offset) { 10878 if (offset != 0) { 10879 final boolean matrixIsIdentity = hasIdentityMatrix(); 10880 if (matrixIsIdentity) { 10881 if (isHardwareAccelerated()) { 10882 invalidateViewProperty(false, false); 10883 } else { 10884 final ViewParent p = mParent; 10885 if (p != null && mAttachInfo != null) { 10886 final Rect r = mAttachInfo.mTmpInvalRect; 10887 int minTop; 10888 int maxBottom; 10889 int yLoc; 10890 if (offset < 0) { 10891 minTop = mTop + offset; 10892 maxBottom = mBottom; 10893 yLoc = offset; 10894 } else { 10895 minTop = mTop; 10896 maxBottom = mBottom + offset; 10897 yLoc = 0; 10898 } 10899 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 10900 p.invalidateChild(this, r); 10901 } 10902 } 10903 } else { 10904 invalidateViewProperty(false, false); 10905 } 10906 10907 mTop += offset; 10908 mBottom += offset; 10909 mRenderNode.offsetTopAndBottom(offset); 10910 if (isHardwareAccelerated()) { 10911 invalidateViewProperty(false, false); 10912 } else { 10913 if (!matrixIsIdentity) { 10914 invalidateViewProperty(false, true); 10915 } 10916 invalidateParentIfNeeded(); 10917 } 10918 notifySubtreeAccessibilityStateChangedIfNeeded(); 10919 } 10920 } 10921 10922 /** 10923 * Offset this view's horizontal location by the specified amount of pixels. 10924 * 10925 * @param offset the number of pixels to offset the view by 10926 */ 10927 public void offsetLeftAndRight(int offset) { 10928 if (offset != 0) { 10929 final boolean matrixIsIdentity = hasIdentityMatrix(); 10930 if (matrixIsIdentity) { 10931 if (isHardwareAccelerated()) { 10932 invalidateViewProperty(false, false); 10933 } else { 10934 final ViewParent p = mParent; 10935 if (p != null && mAttachInfo != null) { 10936 final Rect r = mAttachInfo.mTmpInvalRect; 10937 int minLeft; 10938 int maxRight; 10939 if (offset < 0) { 10940 minLeft = mLeft + offset; 10941 maxRight = mRight; 10942 } else { 10943 minLeft = mLeft; 10944 maxRight = mRight + offset; 10945 } 10946 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 10947 p.invalidateChild(this, r); 10948 } 10949 } 10950 } else { 10951 invalidateViewProperty(false, false); 10952 } 10953 10954 mLeft += offset; 10955 mRight += offset; 10956 mRenderNode.offsetLeftAndRight(offset); 10957 if (isHardwareAccelerated()) { 10958 invalidateViewProperty(false, false); 10959 } else { 10960 if (!matrixIsIdentity) { 10961 invalidateViewProperty(false, true); 10962 } 10963 invalidateParentIfNeeded(); 10964 } 10965 notifySubtreeAccessibilityStateChangedIfNeeded(); 10966 } 10967 } 10968 10969 /** 10970 * Get the LayoutParams associated with this view. All views should have 10971 * layout parameters. These supply parameters to the <i>parent</i> of this 10972 * view specifying how it should be arranged. There are many subclasses of 10973 * ViewGroup.LayoutParams, and these correspond to the different subclasses 10974 * of ViewGroup that are responsible for arranging their children. 10975 * 10976 * This method may return null if this View is not attached to a parent 10977 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 10978 * was not invoked successfully. When a View is attached to a parent 10979 * ViewGroup, this method must not return null. 10980 * 10981 * @return The LayoutParams associated with this view, or null if no 10982 * parameters have been set yet 10983 */ 10984 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 10985 public ViewGroup.LayoutParams getLayoutParams() { 10986 return mLayoutParams; 10987 } 10988 10989 /** 10990 * Set the layout parameters associated with this view. These supply 10991 * parameters to the <i>parent</i> of this view specifying how it should be 10992 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 10993 * correspond to the different subclasses of ViewGroup that are responsible 10994 * for arranging their children. 10995 * 10996 * @param params The layout parameters for this view, cannot be null 10997 */ 10998 public void setLayoutParams(ViewGroup.LayoutParams params) { 10999 if (params == null) { 11000 throw new NullPointerException("Layout parameters cannot be null"); 11001 } 11002 mLayoutParams = params; 11003 resolveLayoutParams(); 11004 if (mParent instanceof ViewGroup) { 11005 ((ViewGroup) mParent).onSetLayoutParams(this, params); 11006 } 11007 requestLayout(); 11008 } 11009 11010 /** 11011 * Resolve the layout parameters depending on the resolved layout direction 11012 * 11013 * @hide 11014 */ 11015 public void resolveLayoutParams() { 11016 if (mLayoutParams != null) { 11017 mLayoutParams.resolveLayoutDirection(getLayoutDirection()); 11018 } 11019 } 11020 11021 /** 11022 * Set the scrolled position of your view. This will cause a call to 11023 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11024 * invalidated. 11025 * @param x the x position to scroll to 11026 * @param y the y position to scroll to 11027 */ 11028 public void scrollTo(int x, int y) { 11029 if (mScrollX != x || mScrollY != y) { 11030 int oldX = mScrollX; 11031 int oldY = mScrollY; 11032 mScrollX = x; 11033 mScrollY = y; 11034 invalidateParentCaches(); 11035 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 11036 if (!awakenScrollBars()) { 11037 postInvalidateOnAnimation(); 11038 } 11039 } 11040 } 11041 11042 /** 11043 * Move the scrolled position of your view. This will cause a call to 11044 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11045 * invalidated. 11046 * @param x the amount of pixels to scroll by horizontally 11047 * @param y the amount of pixels to scroll by vertically 11048 */ 11049 public void scrollBy(int x, int y) { 11050 scrollTo(mScrollX + x, mScrollY + y); 11051 } 11052 11053 /** 11054 * <p>Trigger the scrollbars to draw. When invoked this method starts an 11055 * animation to fade the scrollbars out after a default delay. If a subclass 11056 * provides animated scrolling, the start delay should equal the duration 11057 * of the scrolling animation.</p> 11058 * 11059 * <p>The animation starts only if at least one of the scrollbars is 11060 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 11061 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11062 * this method returns true, and false otherwise. If the animation is 11063 * started, this method calls {@link #invalidate()}; in that case the 11064 * caller should not call {@link #invalidate()}.</p> 11065 * 11066 * <p>This method should be invoked every time a subclass directly updates 11067 * the scroll parameters.</p> 11068 * 11069 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 11070 * and {@link #scrollTo(int, int)}.</p> 11071 * 11072 * @return true if the animation is played, false otherwise 11073 * 11074 * @see #awakenScrollBars(int) 11075 * @see #scrollBy(int, int) 11076 * @see #scrollTo(int, int) 11077 * @see #isHorizontalScrollBarEnabled() 11078 * @see #isVerticalScrollBarEnabled() 11079 * @see #setHorizontalScrollBarEnabled(boolean) 11080 * @see #setVerticalScrollBarEnabled(boolean) 11081 */ 11082 protected boolean awakenScrollBars() { 11083 return mScrollCache != null && 11084 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 11085 } 11086 11087 /** 11088 * Trigger the scrollbars to draw. 11089 * This method differs from awakenScrollBars() only in its default duration. 11090 * initialAwakenScrollBars() will show the scroll bars for longer than 11091 * usual to give the user more of a chance to notice them. 11092 * 11093 * @return true if the animation is played, false otherwise. 11094 */ 11095 private boolean initialAwakenScrollBars() { 11096 return mScrollCache != null && 11097 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 11098 } 11099 11100 /** 11101 * <p> 11102 * Trigger the scrollbars to draw. When invoked this method starts an 11103 * animation to fade the scrollbars out after a fixed delay. If a subclass 11104 * provides animated scrolling, the start delay should equal the duration of 11105 * the scrolling animation. 11106 * </p> 11107 * 11108 * <p> 11109 * The animation starts only if at least one of the scrollbars is enabled, 11110 * as specified by {@link #isHorizontalScrollBarEnabled()} and 11111 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11112 * this method returns true, and false otherwise. If the animation is 11113 * started, this method calls {@link #invalidate()}; in that case the caller 11114 * should not call {@link #invalidate()}. 11115 * </p> 11116 * 11117 * <p> 11118 * This method should be invoked everytime a subclass directly updates the 11119 * scroll parameters. 11120 * </p> 11121 * 11122 * @param startDelay the delay, in milliseconds, after which the animation 11123 * should start; when the delay is 0, the animation starts 11124 * immediately 11125 * @return true if the animation is played, false otherwise 11126 * 11127 * @see #scrollBy(int, int) 11128 * @see #scrollTo(int, int) 11129 * @see #isHorizontalScrollBarEnabled() 11130 * @see #isVerticalScrollBarEnabled() 11131 * @see #setHorizontalScrollBarEnabled(boolean) 11132 * @see #setVerticalScrollBarEnabled(boolean) 11133 */ 11134 protected boolean awakenScrollBars(int startDelay) { 11135 return awakenScrollBars(startDelay, true); 11136 } 11137 11138 /** 11139 * <p> 11140 * Trigger the scrollbars to draw. When invoked this method starts an 11141 * animation to fade the scrollbars out after a fixed delay. If a subclass 11142 * provides animated scrolling, the start delay should equal the duration of 11143 * the scrolling animation. 11144 * </p> 11145 * 11146 * <p> 11147 * The animation starts only if at least one of the scrollbars is enabled, 11148 * as specified by {@link #isHorizontalScrollBarEnabled()} and 11149 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11150 * this method returns true, and false otherwise. If the animation is 11151 * started, this method calls {@link #invalidate()} if the invalidate parameter 11152 * is set to true; in that case the caller 11153 * should not call {@link #invalidate()}. 11154 * </p> 11155 * 11156 * <p> 11157 * This method should be invoked everytime a subclass directly updates the 11158 * scroll parameters. 11159 * </p> 11160 * 11161 * @param startDelay the delay, in milliseconds, after which the animation 11162 * should start; when the delay is 0, the animation starts 11163 * immediately 11164 * 11165 * @param invalidate Wheter this method should call invalidate 11166 * 11167 * @return true if the animation is played, false otherwise 11168 * 11169 * @see #scrollBy(int, int) 11170 * @see #scrollTo(int, int) 11171 * @see #isHorizontalScrollBarEnabled() 11172 * @see #isVerticalScrollBarEnabled() 11173 * @see #setHorizontalScrollBarEnabled(boolean) 11174 * @see #setVerticalScrollBarEnabled(boolean) 11175 */ 11176 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 11177 final ScrollabilityCache scrollCache = mScrollCache; 11178 11179 if (scrollCache == null || !scrollCache.fadeScrollBars) { 11180 return false; 11181 } 11182 11183 if (scrollCache.scrollBar == null) { 11184 scrollCache.scrollBar = new ScrollBarDrawable(); 11185 } 11186 11187 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 11188 11189 if (invalidate) { 11190 // Invalidate to show the scrollbars 11191 postInvalidateOnAnimation(); 11192 } 11193 11194 if (scrollCache.state == ScrollabilityCache.OFF) { 11195 // FIXME: this is copied from WindowManagerService. 11196 // We should get this value from the system when it 11197 // is possible to do so. 11198 final int KEY_REPEAT_FIRST_DELAY = 750; 11199 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 11200 } 11201 11202 // Tell mScrollCache when we should start fading. This may 11203 // extend the fade start time if one was already scheduled 11204 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 11205 scrollCache.fadeStartTime = fadeStartTime; 11206 scrollCache.state = ScrollabilityCache.ON; 11207 11208 // Schedule our fader to run, unscheduling any old ones first 11209 if (mAttachInfo != null) { 11210 mAttachInfo.mHandler.removeCallbacks(scrollCache); 11211 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 11212 } 11213 11214 return true; 11215 } 11216 11217 return false; 11218 } 11219 11220 /** 11221 * Do not invalidate views which are not visible and which are not running an animation. They 11222 * will not get drawn and they should not set dirty flags as if they will be drawn 11223 */ 11224 private boolean skipInvalidate() { 11225 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 11226 (!(mParent instanceof ViewGroup) || 11227 !((ViewGroup) mParent).isViewTransitioning(this)); 11228 } 11229 11230 /** 11231 * Mark the area defined by dirty as needing to be drawn. If the view is 11232 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 11233 * point in the future. 11234 * <p> 11235 * This must be called from a UI thread. To call from a non-UI thread, call 11236 * {@link #postInvalidate()}. 11237 * <p> 11238 * <b>WARNING:</b> In API 19 and below, this method may be destructive to 11239 * {@code dirty}. 11240 * 11241 * @param dirty the rectangle representing the bounds of the dirty region 11242 */ 11243 public void invalidate(Rect dirty) { 11244 final int scrollX = mScrollX; 11245 final int scrollY = mScrollY; 11246 invalidateInternal(dirty.left - scrollX, dirty.top - scrollY, 11247 dirty.right - scrollX, dirty.bottom - scrollY, true, false); 11248 } 11249 11250 /** 11251 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The 11252 * coordinates of the dirty rect are relative to the view. If the view is 11253 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 11254 * point in the future. 11255 * <p> 11256 * This must be called from a UI thread. To call from a non-UI thread, call 11257 * {@link #postInvalidate()}. 11258 * 11259 * @param l the left position of the dirty region 11260 * @param t the top position of the dirty region 11261 * @param r the right position of the dirty region 11262 * @param b the bottom position of the dirty region 11263 */ 11264 public void invalidate(int l, int t, int r, int b) { 11265 final int scrollX = mScrollX; 11266 final int scrollY = mScrollY; 11267 invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false); 11268 } 11269 11270 /** 11271 * Invalidate the whole view. If the view is visible, 11272 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 11273 * the future. 11274 * <p> 11275 * This must be called from a UI thread. To call from a non-UI thread, call 11276 * {@link #postInvalidate()}. 11277 */ 11278 public void invalidate() { 11279 invalidate(true); 11280 } 11281 11282 /** 11283 * This is where the invalidate() work actually happens. A full invalidate() 11284 * causes the drawing cache to be invalidated, but this function can be 11285 * called with invalidateCache set to false to skip that invalidation step 11286 * for cases that do not need it (for example, a component that remains at 11287 * the same dimensions with the same content). 11288 * 11289 * @param invalidateCache Whether the drawing cache for this view should be 11290 * invalidated as well. This is usually true for a full 11291 * invalidate, but may be set to false if the View's contents or 11292 * dimensions have not changed. 11293 */ 11294 void invalidate(boolean invalidateCache) { 11295 invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true); 11296 } 11297 11298 void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache, 11299 boolean fullInvalidate) { 11300 if (skipInvalidate()) { 11301 return; 11302 } 11303 11304 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) 11305 || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) 11306 || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED 11307 || (fullInvalidate && isOpaque() != mLastIsOpaque)) { 11308 if (fullInvalidate) { 11309 mLastIsOpaque = isOpaque(); 11310 mPrivateFlags &= ~PFLAG_DRAWN; 11311 } 11312 11313 mPrivateFlags |= PFLAG_DIRTY; 11314 11315 if (invalidateCache) { 11316 mPrivateFlags |= PFLAG_INVALIDATED; 11317 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 11318 } 11319 11320 // Propagate the damage rectangle to the parent view. 11321 final AttachInfo ai = mAttachInfo; 11322 final ViewParent p = mParent; 11323 if (p != null && ai != null && l < r && t < b) { 11324 final Rect damage = ai.mTmpInvalRect; 11325 damage.set(l, t, r, b); 11326 p.invalidateChild(this, damage); 11327 } 11328 11329 // Damage the entire projection receiver, if necessary. 11330 if (mBackground != null && mBackground.isProjected()) { 11331 final View receiver = getProjectionReceiver(); 11332 if (receiver != null) { 11333 receiver.damageInParent(); 11334 } 11335 } 11336 11337 // Damage the entire IsolatedZVolume recieving this view's shadow. 11338 if (isHardwareAccelerated() && getZ() != 0) { 11339 damageShadowReceiver(); 11340 } 11341 } 11342 } 11343 11344 /** 11345 * @return this view's projection receiver, or {@code null} if none exists 11346 */ 11347 private View getProjectionReceiver() { 11348 ViewParent p = getParent(); 11349 while (p != null && p instanceof View) { 11350 final View v = (View) p; 11351 if (v.isProjectionReceiver()) { 11352 return v; 11353 } 11354 p = p.getParent(); 11355 } 11356 11357 return null; 11358 } 11359 11360 /** 11361 * @return whether the view is a projection receiver 11362 */ 11363 private boolean isProjectionReceiver() { 11364 return mBackground != null; 11365 } 11366 11367 /** 11368 * Damage area of the screen that can be covered by this View's shadow. 11369 * 11370 * This method will guarantee that any changes to shadows cast by a View 11371 * are damaged on the screen for future redraw. 11372 */ 11373 private void damageShadowReceiver() { 11374 final AttachInfo ai = mAttachInfo; 11375 if (ai != null) { 11376 ViewParent p = getParent(); 11377 if (p != null && p instanceof ViewGroup) { 11378 final ViewGroup vg = (ViewGroup) p; 11379 vg.damageInParent(); 11380 } 11381 } 11382 } 11383 11384 /** 11385 * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to 11386 * set any flags or handle all of the cases handled by the default invalidation methods. 11387 * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate 11388 * dirty rect. This method calls into fast invalidation methods in ViewGroup that 11389 * walk up the hierarchy, transforming the dirty rect as necessary. 11390 * 11391 * The method also handles normal invalidation logic if display list properties are not 11392 * being used in this view. The invalidateParent and forceRedraw flags are used by that 11393 * backup approach, to handle these cases used in the various property-setting methods. 11394 * 11395 * @param invalidateParent Force a call to invalidateParentCaches() if display list properties 11396 * are not being used in this view 11397 * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display 11398 * list properties are not being used in this view 11399 */ 11400 void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) { 11401 if (!isHardwareAccelerated() 11402 || !mRenderNode.isValid() 11403 || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) { 11404 if (invalidateParent) { 11405 invalidateParentCaches(); 11406 } 11407 if (forceRedraw) { 11408 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 11409 } 11410 invalidate(false); 11411 } else { 11412 damageInParent(); 11413 } 11414 if (isHardwareAccelerated() && invalidateParent && getZ() != 0) { 11415 damageShadowReceiver(); 11416 } 11417 } 11418 11419 /** 11420 * Tells the parent view to damage this view's bounds. 11421 * 11422 * @hide 11423 */ 11424 protected void damageInParent() { 11425 final AttachInfo ai = mAttachInfo; 11426 final ViewParent p = mParent; 11427 if (p != null && ai != null) { 11428 final Rect r = ai.mTmpInvalRect; 11429 r.set(0, 0, mRight - mLeft, mBottom - mTop); 11430 if (mParent instanceof ViewGroup) { 11431 ((ViewGroup) mParent).damageChild(this, r); 11432 } else { 11433 mParent.invalidateChild(this, r); 11434 } 11435 } 11436 } 11437 11438 /** 11439 * Utility method to transform a given Rect by the current matrix of this view. 11440 */ 11441 void transformRect(final Rect rect) { 11442 if (!getMatrix().isIdentity()) { 11443 RectF boundingRect = mAttachInfo.mTmpTransformRect; 11444 boundingRect.set(rect); 11445 getMatrix().mapRect(boundingRect); 11446 rect.set((int) Math.floor(boundingRect.left), 11447 (int) Math.floor(boundingRect.top), 11448 (int) Math.ceil(boundingRect.right), 11449 (int) Math.ceil(boundingRect.bottom)); 11450 } 11451 } 11452 11453 /** 11454 * Used to indicate that the parent of this view should clear its caches. This functionality 11455 * is used to force the parent to rebuild its display list (when hardware-accelerated), 11456 * which is necessary when various parent-managed properties of the view change, such as 11457 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 11458 * clears the parent caches and does not causes an invalidate event. 11459 * 11460 * @hide 11461 */ 11462 protected void invalidateParentCaches() { 11463 if (mParent instanceof View) { 11464 ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED; 11465 } 11466 } 11467 11468 /** 11469 * Used to indicate that the parent of this view should be invalidated. This functionality 11470 * is used to force the parent to rebuild its display list (when hardware-accelerated), 11471 * which is necessary when various parent-managed properties of the view change, such as 11472 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 11473 * an invalidation event to the parent. 11474 * 11475 * @hide 11476 */ 11477 protected void invalidateParentIfNeeded() { 11478 if (isHardwareAccelerated() && mParent instanceof View) { 11479 ((View) mParent).invalidate(true); 11480 } 11481 } 11482 11483 /** 11484 * @hide 11485 */ 11486 protected void invalidateParentIfNeededAndWasQuickRejected() { 11487 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) { 11488 // View was rejected last time it was drawn by its parent; this may have changed 11489 invalidateParentIfNeeded(); 11490 } 11491 } 11492 11493 /** 11494 * Indicates whether this View is opaque. An opaque View guarantees that it will 11495 * draw all the pixels overlapping its bounds using a fully opaque color. 11496 * 11497 * Subclasses of View should override this method whenever possible to indicate 11498 * whether an instance is opaque. Opaque Views are treated in a special way by 11499 * the View hierarchy, possibly allowing it to perform optimizations during 11500 * invalidate/draw passes. 11501 * 11502 * @return True if this View is guaranteed to be fully opaque, false otherwise. 11503 */ 11504 @ViewDebug.ExportedProperty(category = "drawing") 11505 public boolean isOpaque() { 11506 return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK && 11507 getFinalAlpha() >= 1.0f; 11508 } 11509 11510 /** 11511 * @hide 11512 */ 11513 protected void computeOpaqueFlags() { 11514 // Opaque if: 11515 // - Has a background 11516 // - Background is opaque 11517 // - Doesn't have scrollbars or scrollbars overlay 11518 11519 if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) { 11520 mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND; 11521 } else { 11522 mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND; 11523 } 11524 11525 final int flags = mViewFlags; 11526 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 11527 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY || 11528 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) { 11529 mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS; 11530 } else { 11531 mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS; 11532 } 11533 } 11534 11535 /** 11536 * @hide 11537 */ 11538 protected boolean hasOpaqueScrollbars() { 11539 return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS; 11540 } 11541 11542 /** 11543 * @return A handler associated with the thread running the View. This 11544 * handler can be used to pump events in the UI events queue. 11545 */ 11546 public Handler getHandler() { 11547 final AttachInfo attachInfo = mAttachInfo; 11548 if (attachInfo != null) { 11549 return attachInfo.mHandler; 11550 } 11551 return null; 11552 } 11553 11554 /** 11555 * Gets the view root associated with the View. 11556 * @return The view root, or null if none. 11557 * @hide 11558 */ 11559 public ViewRootImpl getViewRootImpl() { 11560 if (mAttachInfo != null) { 11561 return mAttachInfo.mViewRootImpl; 11562 } 11563 return null; 11564 } 11565 11566 /** 11567 * @hide 11568 */ 11569 public HardwareRenderer getHardwareRenderer() { 11570 return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null; 11571 } 11572 11573 /** 11574 * <p>Causes the Runnable to be added to the message queue. 11575 * The runnable will be run on the user interface thread.</p> 11576 * 11577 * @param action The Runnable that will be executed. 11578 * 11579 * @return Returns true if the Runnable was successfully placed in to the 11580 * message queue. Returns false on failure, usually because the 11581 * looper processing the message queue is exiting. 11582 * 11583 * @see #postDelayed 11584 * @see #removeCallbacks 11585 */ 11586 public boolean post(Runnable action) { 11587 final AttachInfo attachInfo = mAttachInfo; 11588 if (attachInfo != null) { 11589 return attachInfo.mHandler.post(action); 11590 } 11591 // Assume that post will succeed later 11592 ViewRootImpl.getRunQueue().post(action); 11593 return true; 11594 } 11595 11596 /** 11597 * <p>Causes the Runnable to be added to the message queue, to be run 11598 * after the specified amount of time elapses. 11599 * The runnable will be run on the user interface thread.</p> 11600 * 11601 * @param action The Runnable that will be executed. 11602 * @param delayMillis The delay (in milliseconds) until the Runnable 11603 * will be executed. 11604 * 11605 * @return true if the Runnable was successfully placed in to the 11606 * message queue. Returns false on failure, usually because the 11607 * looper processing the message queue is exiting. Note that a 11608 * result of true does not mean the Runnable will be processed -- 11609 * if the looper is quit before the delivery time of the message 11610 * occurs then the message will be dropped. 11611 * 11612 * @see #post 11613 * @see #removeCallbacks 11614 */ 11615 public boolean postDelayed(Runnable action, long delayMillis) { 11616 final AttachInfo attachInfo = mAttachInfo; 11617 if (attachInfo != null) { 11618 return attachInfo.mHandler.postDelayed(action, delayMillis); 11619 } 11620 // Assume that post will succeed later 11621 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 11622 return true; 11623 } 11624 11625 /** 11626 * <p>Causes the Runnable to execute on the next animation time step. 11627 * The runnable will be run on the user interface thread.</p> 11628 * 11629 * @param action The Runnable that will be executed. 11630 * 11631 * @see #postOnAnimationDelayed 11632 * @see #removeCallbacks 11633 */ 11634 public void postOnAnimation(Runnable action) { 11635 final AttachInfo attachInfo = mAttachInfo; 11636 if (attachInfo != null) { 11637 attachInfo.mViewRootImpl.mChoreographer.postCallback( 11638 Choreographer.CALLBACK_ANIMATION, action, null); 11639 } else { 11640 // Assume that post will succeed later 11641 ViewRootImpl.getRunQueue().post(action); 11642 } 11643 } 11644 11645 /** 11646 * <p>Causes the Runnable to execute on the next animation time step, 11647 * after the specified amount of time elapses. 11648 * The runnable will be run on the user interface thread.</p> 11649 * 11650 * @param action The Runnable that will be executed. 11651 * @param delayMillis The delay (in milliseconds) until the Runnable 11652 * will be executed. 11653 * 11654 * @see #postOnAnimation 11655 * @see #removeCallbacks 11656 */ 11657 public void postOnAnimationDelayed(Runnable action, long delayMillis) { 11658 final AttachInfo attachInfo = mAttachInfo; 11659 if (attachInfo != null) { 11660 attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 11661 Choreographer.CALLBACK_ANIMATION, action, null, delayMillis); 11662 } else { 11663 // Assume that post will succeed later 11664 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 11665 } 11666 } 11667 11668 /** 11669 * <p>Removes the specified Runnable from the message queue.</p> 11670 * 11671 * @param action The Runnable to remove from the message handling queue 11672 * 11673 * @return true if this view could ask the Handler to remove the Runnable, 11674 * false otherwise. When the returned value is true, the Runnable 11675 * may or may not have been actually removed from the message queue 11676 * (for instance, if the Runnable was not in the queue already.) 11677 * 11678 * @see #post 11679 * @see #postDelayed 11680 * @see #postOnAnimation 11681 * @see #postOnAnimationDelayed 11682 */ 11683 public boolean removeCallbacks(Runnable action) { 11684 if (action != null) { 11685 final AttachInfo attachInfo = mAttachInfo; 11686 if (attachInfo != null) { 11687 attachInfo.mHandler.removeCallbacks(action); 11688 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 11689 Choreographer.CALLBACK_ANIMATION, action, null); 11690 } 11691 // Assume that post will succeed later 11692 ViewRootImpl.getRunQueue().removeCallbacks(action); 11693 } 11694 return true; 11695 } 11696 11697 /** 11698 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 11699 * Use this to invalidate the View from a non-UI thread.</p> 11700 * 11701 * <p>This method can be invoked from outside of the UI thread 11702 * only when this View is attached to a window.</p> 11703 * 11704 * @see #invalidate() 11705 * @see #postInvalidateDelayed(long) 11706 */ 11707 public void postInvalidate() { 11708 postInvalidateDelayed(0); 11709 } 11710 11711 /** 11712 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 11713 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 11714 * 11715 * <p>This method can be invoked from outside of the UI thread 11716 * only when this View is attached to a window.</p> 11717 * 11718 * @param left The left coordinate of the rectangle to invalidate. 11719 * @param top The top coordinate of the rectangle to invalidate. 11720 * @param right The right coordinate of the rectangle to invalidate. 11721 * @param bottom The bottom coordinate of the rectangle to invalidate. 11722 * 11723 * @see #invalidate(int, int, int, int) 11724 * @see #invalidate(Rect) 11725 * @see #postInvalidateDelayed(long, int, int, int, int) 11726 */ 11727 public void postInvalidate(int left, int top, int right, int bottom) { 11728 postInvalidateDelayed(0, left, top, right, bottom); 11729 } 11730 11731 /** 11732 * <p>Cause an invalidate to happen on a subsequent cycle through the event 11733 * loop. Waits for the specified amount of time.</p> 11734 * 11735 * <p>This method can be invoked from outside of the UI thread 11736 * only when this View is attached to a window.</p> 11737 * 11738 * @param delayMilliseconds the duration in milliseconds to delay the 11739 * invalidation by 11740 * 11741 * @see #invalidate() 11742 * @see #postInvalidate() 11743 */ 11744 public void postInvalidateDelayed(long delayMilliseconds) { 11745 // We try only with the AttachInfo because there's no point in invalidating 11746 // if we are not attached to our window 11747 final AttachInfo attachInfo = mAttachInfo; 11748 if (attachInfo != null) { 11749 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); 11750 } 11751 } 11752 11753 /** 11754 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 11755 * through the event loop. Waits for the specified amount of time.</p> 11756 * 11757 * <p>This method can be invoked from outside of the UI thread 11758 * only when this View is attached to a window.</p> 11759 * 11760 * @param delayMilliseconds the duration in milliseconds to delay the 11761 * invalidation by 11762 * @param left The left coordinate of the rectangle to invalidate. 11763 * @param top The top coordinate of the rectangle to invalidate. 11764 * @param right The right coordinate of the rectangle to invalidate. 11765 * @param bottom The bottom coordinate of the rectangle to invalidate. 11766 * 11767 * @see #invalidate(int, int, int, int) 11768 * @see #invalidate(Rect) 11769 * @see #postInvalidate(int, int, int, int) 11770 */ 11771 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 11772 int right, int bottom) { 11773 11774 // We try only with the AttachInfo because there's no point in invalidating 11775 // if we are not attached to our window 11776 final AttachInfo attachInfo = mAttachInfo; 11777 if (attachInfo != null) { 11778 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 11779 info.target = this; 11780 info.left = left; 11781 info.top = top; 11782 info.right = right; 11783 info.bottom = bottom; 11784 11785 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); 11786 } 11787 } 11788 11789 /** 11790 * <p>Cause an invalidate to happen on the next animation time step, typically the 11791 * next display frame.</p> 11792 * 11793 * <p>This method can be invoked from outside of the UI thread 11794 * only when this View is attached to a window.</p> 11795 * 11796 * @see #invalidate() 11797 */ 11798 public void postInvalidateOnAnimation() { 11799 // We try only with the AttachInfo because there's no point in invalidating 11800 // if we are not attached to our window 11801 final AttachInfo attachInfo = mAttachInfo; 11802 if (attachInfo != null) { 11803 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); 11804 } 11805 } 11806 11807 /** 11808 * <p>Cause an invalidate of the specified area to happen on the next animation 11809 * time step, typically the next display frame.</p> 11810 * 11811 * <p>This method can be invoked from outside of the UI thread 11812 * only when this View is attached to a window.</p> 11813 * 11814 * @param left The left coordinate of the rectangle to invalidate. 11815 * @param top The top coordinate of the rectangle to invalidate. 11816 * @param right The right coordinate of the rectangle to invalidate. 11817 * @param bottom The bottom coordinate of the rectangle to invalidate. 11818 * 11819 * @see #invalidate(int, int, int, int) 11820 * @see #invalidate(Rect) 11821 */ 11822 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { 11823 // We try only with the AttachInfo because there's no point in invalidating 11824 // if we are not attached to our window 11825 final AttachInfo attachInfo = mAttachInfo; 11826 if (attachInfo != null) { 11827 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 11828 info.target = this; 11829 info.left = left; 11830 info.top = top; 11831 info.right = right; 11832 info.bottom = bottom; 11833 11834 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); 11835 } 11836 } 11837 11838 /** 11839 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 11840 * This event is sent at most once every 11841 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 11842 */ 11843 private void postSendViewScrolledAccessibilityEventCallback() { 11844 if (mSendViewScrolledAccessibilityEvent == null) { 11845 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 11846 } 11847 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 11848 mSendViewScrolledAccessibilityEvent.mIsPending = true; 11849 postDelayed(mSendViewScrolledAccessibilityEvent, 11850 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 11851 } 11852 } 11853 11854 /** 11855 * Called by a parent to request that a child update its values for mScrollX 11856 * and mScrollY if necessary. This will typically be done if the child is 11857 * animating a scroll using a {@link android.widget.Scroller Scroller} 11858 * object. 11859 */ 11860 public void computeScroll() { 11861 } 11862 11863 /** 11864 * <p>Indicate whether the horizontal edges are faded when the view is 11865 * scrolled horizontally.</p> 11866 * 11867 * @return true if the horizontal edges should are faded on scroll, false 11868 * otherwise 11869 * 11870 * @see #setHorizontalFadingEdgeEnabled(boolean) 11871 * 11872 * @attr ref android.R.styleable#View_requiresFadingEdge 11873 */ 11874 public boolean isHorizontalFadingEdgeEnabled() { 11875 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 11876 } 11877 11878 /** 11879 * <p>Define whether the horizontal edges should be faded when this view 11880 * is scrolled horizontally.</p> 11881 * 11882 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 11883 * be faded when the view is scrolled 11884 * horizontally 11885 * 11886 * @see #isHorizontalFadingEdgeEnabled() 11887 * 11888 * @attr ref android.R.styleable#View_requiresFadingEdge 11889 */ 11890 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 11891 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 11892 if (horizontalFadingEdgeEnabled) { 11893 initScrollCache(); 11894 } 11895 11896 mViewFlags ^= FADING_EDGE_HORIZONTAL; 11897 } 11898 } 11899 11900 /** 11901 * <p>Indicate whether the vertical edges are faded when the view is 11902 * scrolled horizontally.</p> 11903 * 11904 * @return true if the vertical edges should are faded on scroll, false 11905 * otherwise 11906 * 11907 * @see #setVerticalFadingEdgeEnabled(boolean) 11908 * 11909 * @attr ref android.R.styleable#View_requiresFadingEdge 11910 */ 11911 public boolean isVerticalFadingEdgeEnabled() { 11912 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 11913 } 11914 11915 /** 11916 * <p>Define whether the vertical edges should be faded when this view 11917 * is scrolled vertically.</p> 11918 * 11919 * @param verticalFadingEdgeEnabled true if the vertical edges should 11920 * be faded when the view is scrolled 11921 * vertically 11922 * 11923 * @see #isVerticalFadingEdgeEnabled() 11924 * 11925 * @attr ref android.R.styleable#View_requiresFadingEdge 11926 */ 11927 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 11928 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 11929 if (verticalFadingEdgeEnabled) { 11930 initScrollCache(); 11931 } 11932 11933 mViewFlags ^= FADING_EDGE_VERTICAL; 11934 } 11935 } 11936 11937 /** 11938 * Returns the strength, or intensity, of the top faded edge. The strength is 11939 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11940 * returns 0.0 or 1.0 but no value in between. 11941 * 11942 * Subclasses should override this method to provide a smoother fade transition 11943 * when scrolling occurs. 11944 * 11945 * @return the intensity of the top fade as a float between 0.0f and 1.0f 11946 */ 11947 protected float getTopFadingEdgeStrength() { 11948 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 11949 } 11950 11951 /** 11952 * Returns the strength, or intensity, of the bottom faded edge. The strength is 11953 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11954 * returns 0.0 or 1.0 but no value in between. 11955 * 11956 * Subclasses should override this method to provide a smoother fade transition 11957 * when scrolling occurs. 11958 * 11959 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 11960 */ 11961 protected float getBottomFadingEdgeStrength() { 11962 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 11963 computeVerticalScrollRange() ? 1.0f : 0.0f; 11964 } 11965 11966 /** 11967 * Returns the strength, or intensity, of the left faded edge. The strength is 11968 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11969 * returns 0.0 or 1.0 but no value in between. 11970 * 11971 * Subclasses should override this method to provide a smoother fade transition 11972 * when scrolling occurs. 11973 * 11974 * @return the intensity of the left fade as a float between 0.0f and 1.0f 11975 */ 11976 protected float getLeftFadingEdgeStrength() { 11977 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 11978 } 11979 11980 /** 11981 * Returns the strength, or intensity, of the right faded edge. The strength is 11982 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11983 * returns 0.0 or 1.0 but no value in between. 11984 * 11985 * Subclasses should override this method to provide a smoother fade transition 11986 * when scrolling occurs. 11987 * 11988 * @return the intensity of the right fade as a float between 0.0f and 1.0f 11989 */ 11990 protected float getRightFadingEdgeStrength() { 11991 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 11992 computeHorizontalScrollRange() ? 1.0f : 0.0f; 11993 } 11994 11995 /** 11996 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 11997 * scrollbar is not drawn by default.</p> 11998 * 11999 * @return true if the horizontal scrollbar should be painted, false 12000 * otherwise 12001 * 12002 * @see #setHorizontalScrollBarEnabled(boolean) 12003 */ 12004 public boolean isHorizontalScrollBarEnabled() { 12005 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 12006 } 12007 12008 /** 12009 * <p>Define whether the horizontal scrollbar should be drawn or not. The 12010 * scrollbar is not drawn by default.</p> 12011 * 12012 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 12013 * be painted 12014 * 12015 * @see #isHorizontalScrollBarEnabled() 12016 */ 12017 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 12018 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 12019 mViewFlags ^= SCROLLBARS_HORIZONTAL; 12020 computeOpaqueFlags(); 12021 resolvePadding(); 12022 } 12023 } 12024 12025 /** 12026 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 12027 * scrollbar is not drawn by default.</p> 12028 * 12029 * @return true if the vertical scrollbar should be painted, false 12030 * otherwise 12031 * 12032 * @see #setVerticalScrollBarEnabled(boolean) 12033 */ 12034 public boolean isVerticalScrollBarEnabled() { 12035 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 12036 } 12037 12038 /** 12039 * <p>Define whether the vertical scrollbar should be drawn or not. The 12040 * scrollbar is not drawn by default.</p> 12041 * 12042 * @param verticalScrollBarEnabled true if the vertical scrollbar should 12043 * be painted 12044 * 12045 * @see #isVerticalScrollBarEnabled() 12046 */ 12047 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 12048 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 12049 mViewFlags ^= SCROLLBARS_VERTICAL; 12050 computeOpaqueFlags(); 12051 resolvePadding(); 12052 } 12053 } 12054 12055 /** 12056 * @hide 12057 */ 12058 protected void recomputePadding() { 12059 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 12060 } 12061 12062 /** 12063 * Define whether scrollbars will fade when the view is not scrolling. 12064 * 12065 * @param fadeScrollbars wheter to enable fading 12066 * 12067 * @attr ref android.R.styleable#View_fadeScrollbars 12068 */ 12069 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 12070 initScrollCache(); 12071 final ScrollabilityCache scrollabilityCache = mScrollCache; 12072 scrollabilityCache.fadeScrollBars = fadeScrollbars; 12073 if (fadeScrollbars) { 12074 scrollabilityCache.state = ScrollabilityCache.OFF; 12075 } else { 12076 scrollabilityCache.state = ScrollabilityCache.ON; 12077 } 12078 } 12079 12080 /** 12081 * 12082 * Returns true if scrollbars will fade when this view is not scrolling 12083 * 12084 * @return true if scrollbar fading is enabled 12085 * 12086 * @attr ref android.R.styleable#View_fadeScrollbars 12087 */ 12088 public boolean isScrollbarFadingEnabled() { 12089 return mScrollCache != null && mScrollCache.fadeScrollBars; 12090 } 12091 12092 /** 12093 * 12094 * Returns the delay before scrollbars fade. 12095 * 12096 * @return the delay before scrollbars fade 12097 * 12098 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 12099 */ 12100 public int getScrollBarDefaultDelayBeforeFade() { 12101 return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() : 12102 mScrollCache.scrollBarDefaultDelayBeforeFade; 12103 } 12104 12105 /** 12106 * Define the delay before scrollbars fade. 12107 * 12108 * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade 12109 * 12110 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 12111 */ 12112 public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) { 12113 getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade; 12114 } 12115 12116 /** 12117 * 12118 * Returns the scrollbar fade duration. 12119 * 12120 * @return the scrollbar fade duration 12121 * 12122 * @attr ref android.R.styleable#View_scrollbarFadeDuration 12123 */ 12124 public int getScrollBarFadeDuration() { 12125 return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() : 12126 mScrollCache.scrollBarFadeDuration; 12127 } 12128 12129 /** 12130 * Define the scrollbar fade duration. 12131 * 12132 * @param scrollBarFadeDuration - the scrollbar fade duration 12133 * 12134 * @attr ref android.R.styleable#View_scrollbarFadeDuration 12135 */ 12136 public void setScrollBarFadeDuration(int scrollBarFadeDuration) { 12137 getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration; 12138 } 12139 12140 /** 12141 * 12142 * Returns the scrollbar size. 12143 * 12144 * @return the scrollbar size 12145 * 12146 * @attr ref android.R.styleable#View_scrollbarSize 12147 */ 12148 public int getScrollBarSize() { 12149 return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() : 12150 mScrollCache.scrollBarSize; 12151 } 12152 12153 /** 12154 * Define the scrollbar size. 12155 * 12156 * @param scrollBarSize - the scrollbar size 12157 * 12158 * @attr ref android.R.styleable#View_scrollbarSize 12159 */ 12160 public void setScrollBarSize(int scrollBarSize) { 12161 getScrollCache().scrollBarSize = scrollBarSize; 12162 } 12163 12164 /** 12165 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 12166 * inset. When inset, they add to the padding of the view. And the scrollbars 12167 * can be drawn inside the padding area or on the edge of the view. For example, 12168 * if a view has a background drawable and you want to draw the scrollbars 12169 * inside the padding specified by the drawable, you can use 12170 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 12171 * appear at the edge of the view, ignoring the padding, then you can use 12172 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 12173 * @param style the style of the scrollbars. Should be one of 12174 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 12175 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 12176 * @see #SCROLLBARS_INSIDE_OVERLAY 12177 * @see #SCROLLBARS_INSIDE_INSET 12178 * @see #SCROLLBARS_OUTSIDE_OVERLAY 12179 * @see #SCROLLBARS_OUTSIDE_INSET 12180 * 12181 * @attr ref android.R.styleable#View_scrollbarStyle 12182 */ 12183 public void setScrollBarStyle(@ScrollBarStyle int style) { 12184 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 12185 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 12186 computeOpaqueFlags(); 12187 resolvePadding(); 12188 } 12189 } 12190 12191 /** 12192 * <p>Returns the current scrollbar style.</p> 12193 * @return the current scrollbar style 12194 * @see #SCROLLBARS_INSIDE_OVERLAY 12195 * @see #SCROLLBARS_INSIDE_INSET 12196 * @see #SCROLLBARS_OUTSIDE_OVERLAY 12197 * @see #SCROLLBARS_OUTSIDE_INSET 12198 * 12199 * @attr ref android.R.styleable#View_scrollbarStyle 12200 */ 12201 @ViewDebug.ExportedProperty(mapping = { 12202 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 12203 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 12204 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 12205 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 12206 }) 12207 @ScrollBarStyle 12208 public int getScrollBarStyle() { 12209 return mViewFlags & SCROLLBARS_STYLE_MASK; 12210 } 12211 12212 /** 12213 * <p>Compute the horizontal range that the horizontal scrollbar 12214 * represents.</p> 12215 * 12216 * <p>The range is expressed in arbitrary units that must be the same as the 12217 * units used by {@link #computeHorizontalScrollExtent()} and 12218 * {@link #computeHorizontalScrollOffset()}.</p> 12219 * 12220 * <p>The default range is the drawing width of this view.</p> 12221 * 12222 * @return the total horizontal range represented by the horizontal 12223 * scrollbar 12224 * 12225 * @see #computeHorizontalScrollExtent() 12226 * @see #computeHorizontalScrollOffset() 12227 * @see android.widget.ScrollBarDrawable 12228 */ 12229 protected int computeHorizontalScrollRange() { 12230 return getWidth(); 12231 } 12232 12233 /** 12234 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 12235 * within the horizontal range. This value is used to compute the position 12236 * of the thumb within the scrollbar's track.</p> 12237 * 12238 * <p>The range is expressed in arbitrary units that must be the same as the 12239 * units used by {@link #computeHorizontalScrollRange()} and 12240 * {@link #computeHorizontalScrollExtent()}.</p> 12241 * 12242 * <p>The default offset is the scroll offset of this view.</p> 12243 * 12244 * @return the horizontal offset of the scrollbar's thumb 12245 * 12246 * @see #computeHorizontalScrollRange() 12247 * @see #computeHorizontalScrollExtent() 12248 * @see android.widget.ScrollBarDrawable 12249 */ 12250 protected int computeHorizontalScrollOffset() { 12251 return mScrollX; 12252 } 12253 12254 /** 12255 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 12256 * within the horizontal range. This value is used to compute the length 12257 * of the thumb within the scrollbar's track.</p> 12258 * 12259 * <p>The range is expressed in arbitrary units that must be the same as the 12260 * units used by {@link #computeHorizontalScrollRange()} and 12261 * {@link #computeHorizontalScrollOffset()}.</p> 12262 * 12263 * <p>The default extent is the drawing width of this view.</p> 12264 * 12265 * @return the horizontal extent of the scrollbar's thumb 12266 * 12267 * @see #computeHorizontalScrollRange() 12268 * @see #computeHorizontalScrollOffset() 12269 * @see android.widget.ScrollBarDrawable 12270 */ 12271 protected int computeHorizontalScrollExtent() { 12272 return getWidth(); 12273 } 12274 12275 /** 12276 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 12277 * 12278 * <p>The range is expressed in arbitrary units that must be the same as the 12279 * units used by {@link #computeVerticalScrollExtent()} and 12280 * {@link #computeVerticalScrollOffset()}.</p> 12281 * 12282 * @return the total vertical range represented by the vertical scrollbar 12283 * 12284 * <p>The default range is the drawing height of this view.</p> 12285 * 12286 * @see #computeVerticalScrollExtent() 12287 * @see #computeVerticalScrollOffset() 12288 * @see android.widget.ScrollBarDrawable 12289 */ 12290 protected int computeVerticalScrollRange() { 12291 return getHeight(); 12292 } 12293 12294 /** 12295 * <p>Compute the vertical offset of the vertical scrollbar's thumb 12296 * within the horizontal range. This value is used to compute the position 12297 * of the thumb within the scrollbar's track.</p> 12298 * 12299 * <p>The range is expressed in arbitrary units that must be the same as the 12300 * units used by {@link #computeVerticalScrollRange()} and 12301 * {@link #computeVerticalScrollExtent()}.</p> 12302 * 12303 * <p>The default offset is the scroll offset of this view.</p> 12304 * 12305 * @return the vertical offset of the scrollbar's thumb 12306 * 12307 * @see #computeVerticalScrollRange() 12308 * @see #computeVerticalScrollExtent() 12309 * @see android.widget.ScrollBarDrawable 12310 */ 12311 protected int computeVerticalScrollOffset() { 12312 return mScrollY; 12313 } 12314 12315 /** 12316 * <p>Compute the vertical extent of the vertical scrollbar's thumb 12317 * within the vertical range. This value is used to compute the length 12318 * of the thumb within the scrollbar's track.</p> 12319 * 12320 * <p>The range is expressed in arbitrary units that must be the same as the 12321 * units used by {@link #computeVerticalScrollRange()} and 12322 * {@link #computeVerticalScrollOffset()}.</p> 12323 * 12324 * <p>The default extent is the drawing height of this view.</p> 12325 * 12326 * @return the vertical extent of the scrollbar's thumb 12327 * 12328 * @see #computeVerticalScrollRange() 12329 * @see #computeVerticalScrollOffset() 12330 * @see android.widget.ScrollBarDrawable 12331 */ 12332 protected int computeVerticalScrollExtent() { 12333 return getHeight(); 12334 } 12335 12336 /** 12337 * Check if this view can be scrolled horizontally in a certain direction. 12338 * 12339 * @param direction Negative to check scrolling left, positive to check scrolling right. 12340 * @return true if this view can be scrolled in the specified direction, false otherwise. 12341 */ 12342 public boolean canScrollHorizontally(int direction) { 12343 final int offset = computeHorizontalScrollOffset(); 12344 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 12345 if (range == 0) return false; 12346 if (direction < 0) { 12347 return offset > 0; 12348 } else { 12349 return offset < range - 1; 12350 } 12351 } 12352 12353 /** 12354 * Check if this view can be scrolled vertically in a certain direction. 12355 * 12356 * @param direction Negative to check scrolling up, positive to check scrolling down. 12357 * @return true if this view can be scrolled in the specified direction, false otherwise. 12358 */ 12359 public boolean canScrollVertically(int direction) { 12360 final int offset = computeVerticalScrollOffset(); 12361 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 12362 if (range == 0) return false; 12363 if (direction < 0) { 12364 return offset > 0; 12365 } else { 12366 return offset < range - 1; 12367 } 12368 } 12369 12370 /** 12371 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 12372 * scrollbars are painted only if they have been awakened first.</p> 12373 * 12374 * @param canvas the canvas on which to draw the scrollbars 12375 * 12376 * @see #awakenScrollBars(int) 12377 */ 12378 protected final void onDrawScrollBars(Canvas canvas) { 12379 // scrollbars are drawn only when the animation is running 12380 final ScrollabilityCache cache = mScrollCache; 12381 if (cache != null) { 12382 12383 int state = cache.state; 12384 12385 if (state == ScrollabilityCache.OFF) { 12386 return; 12387 } 12388 12389 boolean invalidate = false; 12390 12391 if (state == ScrollabilityCache.FADING) { 12392 // We're fading -- get our fade interpolation 12393 if (cache.interpolatorValues == null) { 12394 cache.interpolatorValues = new float[1]; 12395 } 12396 12397 float[] values = cache.interpolatorValues; 12398 12399 // Stops the animation if we're done 12400 if (cache.scrollBarInterpolator.timeToValues(values) == 12401 Interpolator.Result.FREEZE_END) { 12402 cache.state = ScrollabilityCache.OFF; 12403 } else { 12404 cache.scrollBar.setAlpha(Math.round(values[0])); 12405 } 12406 12407 // This will make the scroll bars inval themselves after 12408 // drawing. We only want this when we're fading so that 12409 // we prevent excessive redraws 12410 invalidate = true; 12411 } else { 12412 // We're just on -- but we may have been fading before so 12413 // reset alpha 12414 cache.scrollBar.setAlpha(255); 12415 } 12416 12417 12418 final int viewFlags = mViewFlags; 12419 12420 final boolean drawHorizontalScrollBar = 12421 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 12422 final boolean drawVerticalScrollBar = 12423 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 12424 && !isVerticalScrollBarHidden(); 12425 12426 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 12427 final int width = mRight - mLeft; 12428 final int height = mBottom - mTop; 12429 12430 final ScrollBarDrawable scrollBar = cache.scrollBar; 12431 12432 final int scrollX = mScrollX; 12433 final int scrollY = mScrollY; 12434 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 12435 12436 int left; 12437 int top; 12438 int right; 12439 int bottom; 12440 12441 if (drawHorizontalScrollBar) { 12442 int size = scrollBar.getSize(false); 12443 if (size <= 0) { 12444 size = cache.scrollBarSize; 12445 } 12446 12447 scrollBar.setParameters(computeHorizontalScrollRange(), 12448 computeHorizontalScrollOffset(), 12449 computeHorizontalScrollExtent(), false); 12450 final int verticalScrollBarGap = drawVerticalScrollBar ? 12451 getVerticalScrollbarWidth() : 0; 12452 top = scrollY + height - size - (mUserPaddingBottom & inside); 12453 left = scrollX + (mPaddingLeft & inside); 12454 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 12455 bottom = top + size; 12456 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 12457 if (invalidate) { 12458 invalidate(left, top, right, bottom); 12459 } 12460 } 12461 12462 if (drawVerticalScrollBar) { 12463 int size = scrollBar.getSize(true); 12464 if (size <= 0) { 12465 size = cache.scrollBarSize; 12466 } 12467 12468 scrollBar.setParameters(computeVerticalScrollRange(), 12469 computeVerticalScrollOffset(), 12470 computeVerticalScrollExtent(), true); 12471 int verticalScrollbarPosition = mVerticalScrollbarPosition; 12472 if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) { 12473 verticalScrollbarPosition = isLayoutRtl() ? 12474 SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT; 12475 } 12476 switch (verticalScrollbarPosition) { 12477 default: 12478 case SCROLLBAR_POSITION_RIGHT: 12479 left = scrollX + width - size - (mUserPaddingRight & inside); 12480 break; 12481 case SCROLLBAR_POSITION_LEFT: 12482 left = scrollX + (mUserPaddingLeft & inside); 12483 break; 12484 } 12485 top = scrollY + (mPaddingTop & inside); 12486 right = left + size; 12487 bottom = scrollY + height - (mUserPaddingBottom & inside); 12488 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 12489 if (invalidate) { 12490 invalidate(left, top, right, bottom); 12491 } 12492 } 12493 } 12494 } 12495 } 12496 12497 /** 12498 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 12499 * FastScroller is visible. 12500 * @return whether to temporarily hide the vertical scrollbar 12501 * @hide 12502 */ 12503 protected boolean isVerticalScrollBarHidden() { 12504 return false; 12505 } 12506 12507 /** 12508 * <p>Draw the horizontal scrollbar if 12509 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 12510 * 12511 * @param canvas the canvas on which to draw the scrollbar 12512 * @param scrollBar the scrollbar's drawable 12513 * 12514 * @see #isHorizontalScrollBarEnabled() 12515 * @see #computeHorizontalScrollRange() 12516 * @see #computeHorizontalScrollExtent() 12517 * @see #computeHorizontalScrollOffset() 12518 * @see android.widget.ScrollBarDrawable 12519 * @hide 12520 */ 12521 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 12522 int l, int t, int r, int b) { 12523 scrollBar.setBounds(l, t, r, b); 12524 scrollBar.draw(canvas); 12525 } 12526 12527 /** 12528 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 12529 * returns true.</p> 12530 * 12531 * @param canvas the canvas on which to draw the scrollbar 12532 * @param scrollBar the scrollbar's drawable 12533 * 12534 * @see #isVerticalScrollBarEnabled() 12535 * @see #computeVerticalScrollRange() 12536 * @see #computeVerticalScrollExtent() 12537 * @see #computeVerticalScrollOffset() 12538 * @see android.widget.ScrollBarDrawable 12539 * @hide 12540 */ 12541 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 12542 int l, int t, int r, int b) { 12543 scrollBar.setBounds(l, t, r, b); 12544 scrollBar.draw(canvas); 12545 } 12546 12547 /** 12548 * Implement this to do your drawing. 12549 * 12550 * @param canvas the canvas on which the background will be drawn 12551 */ 12552 protected void onDraw(Canvas canvas) { 12553 } 12554 12555 /* 12556 * Caller is responsible for calling requestLayout if necessary. 12557 * (This allows addViewInLayout to not request a new layout.) 12558 */ 12559 void assignParent(ViewParent parent) { 12560 if (mParent == null) { 12561 mParent = parent; 12562 } else if (parent == null) { 12563 mParent = null; 12564 } else { 12565 throw new RuntimeException("view " + this + " being added, but" 12566 + " it already has a parent"); 12567 } 12568 } 12569 12570 /** 12571 * This is called when the view is attached to a window. At this point it 12572 * has a Surface and will start drawing. Note that this function is 12573 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 12574 * however it may be called any time before the first onDraw -- including 12575 * before or after {@link #onMeasure(int, int)}. 12576 * 12577 * @see #onDetachedFromWindow() 12578 */ 12579 protected void onAttachedToWindow() { 12580 if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 12581 mParent.requestTransparentRegion(this); 12582 } 12583 12584 if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { 12585 initialAwakenScrollBars(); 12586 mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 12587 } 12588 12589 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 12590 12591 jumpDrawablesToCurrentState(); 12592 12593 resetSubtreeAccessibilityStateChanged(); 12594 12595 if (isFocused()) { 12596 InputMethodManager imm = InputMethodManager.peekInstance(); 12597 imm.focusIn(this); 12598 } 12599 } 12600 12601 /** 12602 * Resolve all RTL related properties. 12603 * 12604 * @return true if resolution of RTL properties has been done 12605 * 12606 * @hide 12607 */ 12608 public boolean resolveRtlPropertiesIfNeeded() { 12609 if (!needRtlPropertiesResolution()) return false; 12610 12611 // Order is important here: LayoutDirection MUST be resolved first 12612 if (!isLayoutDirectionResolved()) { 12613 resolveLayoutDirection(); 12614 resolveLayoutParams(); 12615 } 12616 // ... then we can resolve the others properties depending on the resolved LayoutDirection. 12617 if (!isTextDirectionResolved()) { 12618 resolveTextDirection(); 12619 } 12620 if (!isTextAlignmentResolved()) { 12621 resolveTextAlignment(); 12622 } 12623 // Should resolve Drawables before Padding because we need the layout direction of the 12624 // Drawable to correctly resolve Padding. 12625 if (!isDrawablesResolved()) { 12626 resolveDrawables(); 12627 } 12628 if (!isPaddingResolved()) { 12629 resolvePadding(); 12630 } 12631 onRtlPropertiesChanged(getLayoutDirection()); 12632 return true; 12633 } 12634 12635 /** 12636 * Reset resolution of all RTL related properties. 12637 * 12638 * @hide 12639 */ 12640 public void resetRtlProperties() { 12641 resetResolvedLayoutDirection(); 12642 resetResolvedTextDirection(); 12643 resetResolvedTextAlignment(); 12644 resetResolvedPadding(); 12645 resetResolvedDrawables(); 12646 } 12647 12648 /** 12649 * @see #onScreenStateChanged(int) 12650 */ 12651 void dispatchScreenStateChanged(int screenState) { 12652 onScreenStateChanged(screenState); 12653 } 12654 12655 /** 12656 * This method is called whenever the state of the screen this view is 12657 * attached to changes. A state change will usually occurs when the screen 12658 * turns on or off (whether it happens automatically or the user does it 12659 * manually.) 12660 * 12661 * @param screenState The new state of the screen. Can be either 12662 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF} 12663 */ 12664 public void onScreenStateChanged(int screenState) { 12665 } 12666 12667 /** 12668 * Return true if the application tag in the AndroidManifest has set "supportRtl" to true 12669 */ 12670 private boolean hasRtlSupport() { 12671 return mContext.getApplicationInfo().hasRtlSupport(); 12672 } 12673 12674 /** 12675 * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or 12676 * RTL not supported) 12677 */ 12678 private boolean isRtlCompatibilityMode() { 12679 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 12680 return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport(); 12681 } 12682 12683 /** 12684 * @return true if RTL properties need resolution. 12685 * 12686 */ 12687 private boolean needRtlPropertiesResolution() { 12688 return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED; 12689 } 12690 12691 /** 12692 * Called when any RTL property (layout direction or text direction or text alignment) has 12693 * been changed. 12694 * 12695 * Subclasses need to override this method to take care of cached information that depends on the 12696 * resolved layout direction, or to inform child views that inherit their layout direction. 12697 * 12698 * The default implementation does nothing. 12699 * 12700 * @param layoutDirection the direction of the layout 12701 * 12702 * @see #LAYOUT_DIRECTION_LTR 12703 * @see #LAYOUT_DIRECTION_RTL 12704 */ 12705 public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) { 12706 } 12707 12708 /** 12709 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 12710 * that the parent directionality can and will be resolved before its children. 12711 * 12712 * @return true if resolution has been done, false otherwise. 12713 * 12714 * @hide 12715 */ 12716 public boolean resolveLayoutDirection() { 12717 // Clear any previous layout direction resolution 12718 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 12719 12720 if (hasRtlSupport()) { 12721 // Set resolved depending on layout direction 12722 switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> 12723 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) { 12724 case LAYOUT_DIRECTION_INHERIT: 12725 // We cannot resolve yet. LTR is by default and let the resolution happen again 12726 // later to get the correct resolved value 12727 if (!canResolveLayoutDirection()) return false; 12728 12729 // Parent has not yet resolved, LTR is still the default 12730 try { 12731 if (!mParent.isLayoutDirectionResolved()) return false; 12732 12733 if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 12734 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12735 } 12736 } catch (AbstractMethodError e) { 12737 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 12738 " does not fully implement ViewParent", e); 12739 } 12740 break; 12741 case LAYOUT_DIRECTION_RTL: 12742 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12743 break; 12744 case LAYOUT_DIRECTION_LOCALE: 12745 if((LAYOUT_DIRECTION_RTL == 12746 TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) { 12747 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12748 } 12749 break; 12750 default: 12751 // Nothing to do, LTR by default 12752 } 12753 } 12754 12755 // Set to resolved 12756 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 12757 return true; 12758 } 12759 12760 /** 12761 * Check if layout direction resolution can be done. 12762 * 12763 * @return true if layout direction resolution can be done otherwise return false. 12764 */ 12765 public boolean canResolveLayoutDirection() { 12766 switch (getRawLayoutDirection()) { 12767 case LAYOUT_DIRECTION_INHERIT: 12768 if (mParent != null) { 12769 try { 12770 return mParent.canResolveLayoutDirection(); 12771 } catch (AbstractMethodError e) { 12772 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 12773 " does not fully implement ViewParent", e); 12774 } 12775 } 12776 return false; 12777 12778 default: 12779 return true; 12780 } 12781 } 12782 12783 /** 12784 * Reset the resolved layout direction. Layout direction will be resolved during a call to 12785 * {@link #onMeasure(int, int)}. 12786 * 12787 * @hide 12788 */ 12789 public void resetResolvedLayoutDirection() { 12790 // Reset the current resolved bits 12791 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 12792 } 12793 12794 /** 12795 * @return true if the layout direction is inherited. 12796 * 12797 * @hide 12798 */ 12799 public boolean isLayoutDirectionInherited() { 12800 return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT); 12801 } 12802 12803 /** 12804 * @return true if layout direction has been resolved. 12805 */ 12806 public boolean isLayoutDirectionResolved() { 12807 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED; 12808 } 12809 12810 /** 12811 * Return if padding has been resolved 12812 * 12813 * @hide 12814 */ 12815 boolean isPaddingResolved() { 12816 return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED; 12817 } 12818 12819 /** 12820 * Resolves padding depending on layout direction, if applicable, and 12821 * recomputes internal padding values to adjust for scroll bars. 12822 * 12823 * @hide 12824 */ 12825 public void resolvePadding() { 12826 final int resolvedLayoutDirection = getLayoutDirection(); 12827 12828 if (!isRtlCompatibilityMode()) { 12829 // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account. 12830 // If start / end padding are defined, they will be resolved (hence overriding) to 12831 // left / right or right / left depending on the resolved layout direction. 12832 // If start / end padding are not defined, use the left / right ones. 12833 if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) { 12834 Rect padding = sThreadLocal.get(); 12835 if (padding == null) { 12836 padding = new Rect(); 12837 sThreadLocal.set(padding); 12838 } 12839 mBackground.getPadding(padding); 12840 if (!mLeftPaddingDefined) { 12841 mUserPaddingLeftInitial = padding.left; 12842 } 12843 if (!mRightPaddingDefined) { 12844 mUserPaddingRightInitial = padding.right; 12845 } 12846 } 12847 switch (resolvedLayoutDirection) { 12848 case LAYOUT_DIRECTION_RTL: 12849 if (mUserPaddingStart != UNDEFINED_PADDING) { 12850 mUserPaddingRight = mUserPaddingStart; 12851 } else { 12852 mUserPaddingRight = mUserPaddingRightInitial; 12853 } 12854 if (mUserPaddingEnd != UNDEFINED_PADDING) { 12855 mUserPaddingLeft = mUserPaddingEnd; 12856 } else { 12857 mUserPaddingLeft = mUserPaddingLeftInitial; 12858 } 12859 break; 12860 case LAYOUT_DIRECTION_LTR: 12861 default: 12862 if (mUserPaddingStart != UNDEFINED_PADDING) { 12863 mUserPaddingLeft = mUserPaddingStart; 12864 } else { 12865 mUserPaddingLeft = mUserPaddingLeftInitial; 12866 } 12867 if (mUserPaddingEnd != UNDEFINED_PADDING) { 12868 mUserPaddingRight = mUserPaddingEnd; 12869 } else { 12870 mUserPaddingRight = mUserPaddingRightInitial; 12871 } 12872 } 12873 12874 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 12875 } 12876 12877 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 12878 onRtlPropertiesChanged(resolvedLayoutDirection); 12879 12880 mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED; 12881 } 12882 12883 /** 12884 * Reset the resolved layout direction. 12885 * 12886 * @hide 12887 */ 12888 public void resetResolvedPadding() { 12889 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 12890 } 12891 12892 /** 12893 * This is called when the view is detached from a window. At this point it 12894 * no longer has a surface for drawing. 12895 * 12896 * @see #onAttachedToWindow() 12897 */ 12898 protected void onDetachedFromWindow() { 12899 } 12900 12901 /** 12902 * This is a framework-internal mirror of onDetachedFromWindow() that's called 12903 * after onDetachedFromWindow(). 12904 * 12905 * If you override this you *MUST* call super.onDetachedFromWindowInternal()! 12906 * The super method should be called at the end of the overriden method to ensure 12907 * subclasses are destroyed first 12908 * 12909 * @hide 12910 */ 12911 protected void onDetachedFromWindowInternal() { 12912 mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT; 12913 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 12914 12915 removeUnsetPressCallback(); 12916 removeLongPressCallback(); 12917 removePerformClickCallback(); 12918 removeSendViewScrolledAccessibilityEventCallback(); 12919 stopNestedScroll(); 12920 12921 destroyDrawingCache(); 12922 destroyLayer(false); 12923 12924 cleanupDraw(); 12925 mCurrentAnimation = null; 12926 } 12927 12928 private void cleanupDraw() { 12929 resetDisplayList(); 12930 if (mAttachInfo != null) { 12931 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 12932 } 12933 } 12934 12935 /** 12936 * This method ensures the hardware renderer is in a valid state 12937 * before executing the specified action. 12938 * 12939 * This method will attempt to set a valid state even if the window 12940 * the renderer is attached to was destroyed. 12941 * 12942 * This method is not guaranteed to work. If the hardware renderer 12943 * does not exist or cannot be put in a valid state, this method 12944 * will not executed the specified action. 12945 * 12946 * The specified action is executed synchronously. 12947 * 12948 * @param action The action to execute after the renderer is in a valid state 12949 * 12950 * @return True if the specified Runnable was executed, false otherwise 12951 * 12952 * @hide 12953 */ 12954 public boolean executeHardwareAction(Runnable action) { 12955 //noinspection SimplifiableIfStatement 12956 if (mAttachInfo != null && mAttachInfo.mHardwareRenderer != null) { 12957 return mAttachInfo.mHardwareRenderer.safelyRun(action); 12958 } 12959 return false; 12960 } 12961 12962 void invalidateInheritedLayoutMode(int layoutModeOfRoot) { 12963 } 12964 12965 /** 12966 * @return The number of times this view has been attached to a window 12967 */ 12968 protected int getWindowAttachCount() { 12969 return mWindowAttachCount; 12970 } 12971 12972 /** 12973 * Retrieve a unique token identifying the window this view is attached to. 12974 * @return Return the window's token for use in 12975 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 12976 */ 12977 public IBinder getWindowToken() { 12978 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 12979 } 12980 12981 /** 12982 * Retrieve the {@link WindowId} for the window this view is 12983 * currently attached to. 12984 */ 12985 public WindowId getWindowId() { 12986 if (mAttachInfo == null) { 12987 return null; 12988 } 12989 if (mAttachInfo.mWindowId == null) { 12990 try { 12991 mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId( 12992 mAttachInfo.mWindowToken); 12993 mAttachInfo.mWindowId = new WindowId( 12994 mAttachInfo.mIWindowId); 12995 } catch (RemoteException e) { 12996 } 12997 } 12998 return mAttachInfo.mWindowId; 12999 } 13000 13001 /** 13002 * Retrieve a unique token identifying the top-level "real" window of 13003 * the window that this view is attached to. That is, this is like 13004 * {@link #getWindowToken}, except if the window this view in is a panel 13005 * window (attached to another containing window), then the token of 13006 * the containing window is returned instead. 13007 * 13008 * @return Returns the associated window token, either 13009 * {@link #getWindowToken()} or the containing window's token. 13010 */ 13011 public IBinder getApplicationWindowToken() { 13012 AttachInfo ai = mAttachInfo; 13013 if (ai != null) { 13014 IBinder appWindowToken = ai.mPanelParentWindowToken; 13015 if (appWindowToken == null) { 13016 appWindowToken = ai.mWindowToken; 13017 } 13018 return appWindowToken; 13019 } 13020 return null; 13021 } 13022 13023 /** 13024 * Gets the logical display to which the view's window has been attached. 13025 * 13026 * @return The logical display, or null if the view is not currently attached to a window. 13027 */ 13028 public Display getDisplay() { 13029 return mAttachInfo != null ? mAttachInfo.mDisplay : null; 13030 } 13031 13032 /** 13033 * Retrieve private session object this view hierarchy is using to 13034 * communicate with the window manager. 13035 * @return the session object to communicate with the window manager 13036 */ 13037 /*package*/ IWindowSession getWindowSession() { 13038 return mAttachInfo != null ? mAttachInfo.mSession : null; 13039 } 13040 13041 /** 13042 * @param info the {@link android.view.View.AttachInfo} to associated with 13043 * this view 13044 */ 13045 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 13046 //System.out.println("Attached! " + this); 13047 mAttachInfo = info; 13048 if (mOverlay != null) { 13049 mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility); 13050 } 13051 mWindowAttachCount++; 13052 // We will need to evaluate the drawable state at least once. 13053 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 13054 if (mFloatingTreeObserver != null) { 13055 info.mTreeObserver.merge(mFloatingTreeObserver); 13056 mFloatingTreeObserver = null; 13057 } 13058 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) { 13059 mAttachInfo.mScrollContainers.add(this); 13060 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 13061 } 13062 performCollectViewAttributes(mAttachInfo, visibility); 13063 onAttachedToWindow(); 13064 13065 ListenerInfo li = mListenerInfo; 13066 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 13067 li != null ? li.mOnAttachStateChangeListeners : null; 13068 if (listeners != null && listeners.size() > 0) { 13069 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 13070 // perform the dispatching. The iterator is a safe guard against listeners that 13071 // could mutate the list by calling the various add/remove methods. This prevents 13072 // the array from being modified while we iterate it. 13073 for (OnAttachStateChangeListener listener : listeners) { 13074 listener.onViewAttachedToWindow(this); 13075 } 13076 } 13077 13078 int vis = info.mWindowVisibility; 13079 if (vis != GONE) { 13080 onWindowVisibilityChanged(vis); 13081 } 13082 if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) { 13083 // If nobody has evaluated the drawable state yet, then do it now. 13084 refreshDrawableState(); 13085 } 13086 needGlobalAttributesUpdate(false); 13087 } 13088 13089 void dispatchDetachedFromWindow() { 13090 AttachInfo info = mAttachInfo; 13091 if (info != null) { 13092 int vis = info.mWindowVisibility; 13093 if (vis != GONE) { 13094 onWindowVisibilityChanged(GONE); 13095 } 13096 } 13097 13098 onDetachedFromWindow(); 13099 onDetachedFromWindowInternal(); 13100 13101 ListenerInfo li = mListenerInfo; 13102 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 13103 li != null ? li.mOnAttachStateChangeListeners : null; 13104 if (listeners != null && listeners.size() > 0) { 13105 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 13106 // perform the dispatching. The iterator is a safe guard against listeners that 13107 // could mutate the list by calling the various add/remove methods. This prevents 13108 // the array from being modified while we iterate it. 13109 for (OnAttachStateChangeListener listener : listeners) { 13110 listener.onViewDetachedFromWindow(this); 13111 } 13112 } 13113 13114 if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 13115 mAttachInfo.mScrollContainers.remove(this); 13116 mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED; 13117 } 13118 13119 mAttachInfo = null; 13120 if (mOverlay != null) { 13121 mOverlay.getOverlayView().dispatchDetachedFromWindow(); 13122 } 13123 } 13124 13125 /** 13126 * Cancel any deferred high-level input events that were previously posted to the event queue. 13127 * 13128 * <p>Many views post high-level events such as click handlers to the event queue 13129 * to run deferred in order to preserve a desired user experience - clearing visible 13130 * pressed states before executing, etc. This method will abort any events of this nature 13131 * that are currently in flight.</p> 13132 * 13133 * <p>Custom views that generate their own high-level deferred input events should override 13134 * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p> 13135 * 13136 * <p>This will also cancel pending input events for any child views.</p> 13137 * 13138 * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases. 13139 * This will not impact newer events posted after this call that may occur as a result of 13140 * lower-level input events still waiting in the queue. If you are trying to prevent 13141 * double-submitted events for the duration of some sort of asynchronous transaction 13142 * you should also take other steps to protect against unexpected double inputs e.g. calling 13143 * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when 13144 * the transaction completes, tracking already submitted transaction IDs, etc.</p> 13145 */ 13146 public final void cancelPendingInputEvents() { 13147 dispatchCancelPendingInputEvents(); 13148 } 13149 13150 /** 13151 * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight. 13152 * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling. 13153 */ 13154 void dispatchCancelPendingInputEvents() { 13155 mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER; 13156 onCancelPendingInputEvents(); 13157 if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) { 13158 throw new SuperNotCalledException("View " + getClass().getSimpleName() + 13159 " did not call through to super.onCancelPendingInputEvents()"); 13160 } 13161 } 13162 13163 /** 13164 * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or 13165 * a parent view. 13166 * 13167 * <p>This method is responsible for removing any pending high-level input events that were 13168 * posted to the event queue to run later. Custom view classes that post their own deferred 13169 * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or 13170 * {@link android.os.Handler} should override this method, call 13171 * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate. 13172 * </p> 13173 */ 13174 public void onCancelPendingInputEvents() { 13175 removePerformClickCallback(); 13176 cancelLongPress(); 13177 mPrivateFlags3 |= PFLAG3_CALLED_SUPER; 13178 } 13179 13180 /** 13181 * Store this view hierarchy's frozen state into the given container. 13182 * 13183 * @param container The SparseArray in which to save the view's state. 13184 * 13185 * @see #restoreHierarchyState(android.util.SparseArray) 13186 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13187 * @see #onSaveInstanceState() 13188 */ 13189 public void saveHierarchyState(SparseArray<Parcelable> container) { 13190 dispatchSaveInstanceState(container); 13191 } 13192 13193 /** 13194 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 13195 * this view and its children. May be overridden to modify how freezing happens to a 13196 * view's children; for example, some views may want to not store state for their children. 13197 * 13198 * @param container The SparseArray in which to save the view's state. 13199 * 13200 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13201 * @see #saveHierarchyState(android.util.SparseArray) 13202 * @see #onSaveInstanceState() 13203 */ 13204 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 13205 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 13206 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 13207 Parcelable state = onSaveInstanceState(); 13208 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 13209 throw new IllegalStateException( 13210 "Derived class did not call super.onSaveInstanceState()"); 13211 } 13212 if (state != null) { 13213 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 13214 // + ": " + state); 13215 container.put(mID, state); 13216 } 13217 } 13218 } 13219 13220 /** 13221 * Hook allowing a view to generate a representation of its internal state 13222 * that can later be used to create a new instance with that same state. 13223 * This state should only contain information that is not persistent or can 13224 * not be reconstructed later. For example, you will never store your 13225 * current position on screen because that will be computed again when a 13226 * new instance of the view is placed in its view hierarchy. 13227 * <p> 13228 * Some examples of things you may store here: the current cursor position 13229 * in a text view (but usually not the text itself since that is stored in a 13230 * content provider or other persistent storage), the currently selected 13231 * item in a list view. 13232 * 13233 * @return Returns a Parcelable object containing the view's current dynamic 13234 * state, or null if there is nothing interesting to save. The 13235 * default implementation returns null. 13236 * @see #onRestoreInstanceState(android.os.Parcelable) 13237 * @see #saveHierarchyState(android.util.SparseArray) 13238 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13239 * @see #setSaveEnabled(boolean) 13240 */ 13241 protected Parcelable onSaveInstanceState() { 13242 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 13243 return BaseSavedState.EMPTY_STATE; 13244 } 13245 13246 /** 13247 * Restore this view hierarchy's frozen state from the given container. 13248 * 13249 * @param container The SparseArray which holds previously frozen states. 13250 * 13251 * @see #saveHierarchyState(android.util.SparseArray) 13252 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13253 * @see #onRestoreInstanceState(android.os.Parcelable) 13254 */ 13255 public void restoreHierarchyState(SparseArray<Parcelable> container) { 13256 dispatchRestoreInstanceState(container); 13257 } 13258 13259 /** 13260 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 13261 * state for this view and its children. May be overridden to modify how restoring 13262 * happens to a view's children; for example, some views may want to not store state 13263 * for their children. 13264 * 13265 * @param container The SparseArray which holds previously saved state. 13266 * 13267 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13268 * @see #restoreHierarchyState(android.util.SparseArray) 13269 * @see #onRestoreInstanceState(android.os.Parcelable) 13270 */ 13271 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 13272 if (mID != NO_ID) { 13273 Parcelable state = container.get(mID); 13274 if (state != null) { 13275 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 13276 // + ": " + state); 13277 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 13278 onRestoreInstanceState(state); 13279 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 13280 throw new IllegalStateException( 13281 "Derived class did not call super.onRestoreInstanceState()"); 13282 } 13283 } 13284 } 13285 } 13286 13287 /** 13288 * Hook allowing a view to re-apply a representation of its internal state that had previously 13289 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 13290 * null state. 13291 * 13292 * @param state The frozen state that had previously been returned by 13293 * {@link #onSaveInstanceState}. 13294 * 13295 * @see #onSaveInstanceState() 13296 * @see #restoreHierarchyState(android.util.SparseArray) 13297 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13298 */ 13299 protected void onRestoreInstanceState(Parcelable state) { 13300 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 13301 if (state != BaseSavedState.EMPTY_STATE && state != null) { 13302 throw new IllegalArgumentException("Wrong state class, expecting View State but " 13303 + "received " + state.getClass().toString() + " instead. This usually happens " 13304 + "when two views of different type have the same id in the same hierarchy. " 13305 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 13306 + "other views do not use the same id."); 13307 } 13308 } 13309 13310 /** 13311 * <p>Return the time at which the drawing of the view hierarchy started.</p> 13312 * 13313 * @return the drawing start time in milliseconds 13314 */ 13315 public long getDrawingTime() { 13316 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 13317 } 13318 13319 /** 13320 * <p>Enables or disables the duplication of the parent's state into this view. When 13321 * duplication is enabled, this view gets its drawable state from its parent rather 13322 * than from its own internal properties.</p> 13323 * 13324 * <p>Note: in the current implementation, setting this property to true after the 13325 * view was added to a ViewGroup might have no effect at all. This property should 13326 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 13327 * 13328 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 13329 * property is enabled, an exception will be thrown.</p> 13330 * 13331 * <p>Note: if the child view uses and updates additionnal states which are unknown to the 13332 * parent, these states should not be affected by this method.</p> 13333 * 13334 * @param enabled True to enable duplication of the parent's drawable state, false 13335 * to disable it. 13336 * 13337 * @see #getDrawableState() 13338 * @see #isDuplicateParentStateEnabled() 13339 */ 13340 public void setDuplicateParentStateEnabled(boolean enabled) { 13341 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 13342 } 13343 13344 /** 13345 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 13346 * 13347 * @return True if this view's drawable state is duplicated from the parent, 13348 * false otherwise 13349 * 13350 * @see #getDrawableState() 13351 * @see #setDuplicateParentStateEnabled(boolean) 13352 */ 13353 public boolean isDuplicateParentStateEnabled() { 13354 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 13355 } 13356 13357 /** 13358 * <p>Specifies the type of layer backing this view. The layer can be 13359 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13360 * {@link #LAYER_TYPE_HARDWARE}.</p> 13361 * 13362 * <p>A layer is associated with an optional {@link android.graphics.Paint} 13363 * instance that controls how the layer is composed on screen. The following 13364 * properties of the paint are taken into account when composing the layer:</p> 13365 * <ul> 13366 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 13367 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 13368 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 13369 * </ul> 13370 * 13371 * <p>If this view has an alpha value set to < 1.0 by calling 13372 * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded 13373 * by this view's alpha value.</p> 13374 * 13375 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE}, 13376 * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE} 13377 * for more information on when and how to use layers.</p> 13378 * 13379 * @param layerType The type of layer to use with this view, must be one of 13380 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13381 * {@link #LAYER_TYPE_HARDWARE} 13382 * @param paint The paint used to compose the layer. This argument is optional 13383 * and can be null. It is ignored when the layer type is 13384 * {@link #LAYER_TYPE_NONE} 13385 * 13386 * @see #getLayerType() 13387 * @see #LAYER_TYPE_NONE 13388 * @see #LAYER_TYPE_SOFTWARE 13389 * @see #LAYER_TYPE_HARDWARE 13390 * @see #setAlpha(float) 13391 * 13392 * @attr ref android.R.styleable#View_layerType 13393 */ 13394 public void setLayerType(int layerType, Paint paint) { 13395 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 13396 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 13397 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 13398 } 13399 13400 if (layerType == mLayerType) { 13401 setLayerPaint(paint); 13402 return; 13403 } 13404 13405 // Destroy any previous software drawing cache if needed 13406 switch (mLayerType) { 13407 case LAYER_TYPE_HARDWARE: 13408 destroyLayer(false); 13409 // fall through - non-accelerated views may use software layer mechanism instead 13410 case LAYER_TYPE_SOFTWARE: 13411 destroyDrawingCache(); 13412 break; 13413 default: 13414 break; 13415 } 13416 13417 mLayerType = layerType; 13418 final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE; 13419 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 13420 mLocalDirtyRect = layerDisabled ? null : new Rect(); 13421 13422 invalidateParentCaches(); 13423 invalidate(true); 13424 } 13425 13426 /** 13427 * Updates the {@link Paint} object used with the current layer (used only if the current 13428 * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint 13429 * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time 13430 * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to 13431 * ensure that the view gets redrawn immediately. 13432 * 13433 * <p>A layer is associated with an optional {@link android.graphics.Paint} 13434 * instance that controls how the layer is composed on screen. The following 13435 * properties of the paint are taken into account when composing the layer:</p> 13436 * <ul> 13437 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 13438 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 13439 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 13440 * </ul> 13441 * 13442 * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the 13443 * alpha value of the layer's paint is superceded by this view's alpha value.</p> 13444 * 13445 * @param paint The paint used to compose the layer. This argument is optional 13446 * and can be null. It is ignored when the layer type is 13447 * {@link #LAYER_TYPE_NONE} 13448 * 13449 * @see #setLayerType(int, android.graphics.Paint) 13450 */ 13451 public void setLayerPaint(Paint paint) { 13452 int layerType = getLayerType(); 13453 if (layerType != LAYER_TYPE_NONE) { 13454 mLayerPaint = paint == null ? new Paint() : paint; 13455 if (layerType == LAYER_TYPE_HARDWARE) { 13456 HardwareLayer layer = getHardwareLayer(); 13457 if (layer != null) { 13458 layer.setLayerPaint(mLayerPaint); 13459 } 13460 invalidateViewProperty(false, false); 13461 } else { 13462 invalidate(); 13463 } 13464 } 13465 } 13466 13467 /** 13468 * Indicates whether this view has a static layer. A view with layer type 13469 * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are 13470 * dynamic. 13471 */ 13472 boolean hasStaticLayer() { 13473 return true; 13474 } 13475 13476 /** 13477 * Indicates what type of layer is currently associated with this view. By default 13478 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 13479 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 13480 * for more information on the different types of layers. 13481 * 13482 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13483 * {@link #LAYER_TYPE_HARDWARE} 13484 * 13485 * @see #setLayerType(int, android.graphics.Paint) 13486 * @see #buildLayer() 13487 * @see #LAYER_TYPE_NONE 13488 * @see #LAYER_TYPE_SOFTWARE 13489 * @see #LAYER_TYPE_HARDWARE 13490 */ 13491 public int getLayerType() { 13492 return mLayerType; 13493 } 13494 13495 /** 13496 * Forces this view's layer to be created and this view to be rendered 13497 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 13498 * invoking this method will have no effect. 13499 * 13500 * This method can for instance be used to render a view into its layer before 13501 * starting an animation. If this view is complex, rendering into the layer 13502 * before starting the animation will avoid skipping frames. 13503 * 13504 * @throws IllegalStateException If this view is not attached to a window 13505 * 13506 * @see #setLayerType(int, android.graphics.Paint) 13507 */ 13508 public void buildLayer() { 13509 if (mLayerType == LAYER_TYPE_NONE) return; 13510 13511 final AttachInfo attachInfo = mAttachInfo; 13512 if (attachInfo == null) { 13513 throw new IllegalStateException("This view must be attached to a window first"); 13514 } 13515 13516 switch (mLayerType) { 13517 case LAYER_TYPE_HARDWARE: 13518 getHardwareLayer(); 13519 // TODO: We need a better way to handle this case 13520 // If views have registered pre-draw listeners they need 13521 // to be notified before we build the layer. Those listeners 13522 // may however rely on other events to happen first so we 13523 // cannot just invoke them here until they don't cancel the 13524 // current frame 13525 if (!attachInfo.mTreeObserver.hasOnPreDrawListeners()) { 13526 attachInfo.mViewRootImpl.dispatchFlushHardwareLayerUpdates(); 13527 } 13528 break; 13529 case LAYER_TYPE_SOFTWARE: 13530 buildDrawingCache(true); 13531 break; 13532 } 13533 } 13534 13535 /** 13536 * <p>Returns a hardware layer that can be used to draw this view again 13537 * without executing its draw method.</p> 13538 * 13539 * @return A HardwareLayer ready to render, or null if an error occurred. 13540 */ 13541 HardwareLayer getHardwareLayer() { 13542 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null || 13543 !mAttachInfo.mHardwareRenderer.isEnabled()) { 13544 return null; 13545 } 13546 13547 final int width = mRight - mLeft; 13548 final int height = mBottom - mTop; 13549 13550 if (width == 0 || height == 0) { 13551 return null; 13552 } 13553 13554 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) { 13555 if (mHardwareLayer == null) { 13556 mHardwareLayer = mAttachInfo.mHardwareRenderer.createDisplayListLayer( 13557 width, height); 13558 mLocalDirtyRect.set(0, 0, width, height); 13559 } else if (mHardwareLayer.isValid()) { 13560 // This should not be necessary but applications that change 13561 // the parameters of their background drawable without calling 13562 // this.setBackground(Drawable) can leave the view in a bad state 13563 // (for instance isOpaque() returns true, but the background is 13564 // not opaque.) 13565 computeOpaqueFlags(); 13566 13567 if (mHardwareLayer.prepare(width, height, isOpaque())) { 13568 mLocalDirtyRect.set(0, 0, width, height); 13569 } 13570 } 13571 13572 // The layer is not valid if the underlying GPU resources cannot be allocated 13573 mHardwareLayer.flushChanges(); 13574 if (!mHardwareLayer.isValid()) { 13575 return null; 13576 } 13577 13578 mHardwareLayer.setLayerPaint(mLayerPaint); 13579 RenderNode displayList = mHardwareLayer.startRecording(); 13580 updateDisplayListIfDirty(displayList, true); 13581 mHardwareLayer.endRecording(mLocalDirtyRect); 13582 mLocalDirtyRect.setEmpty(); 13583 } 13584 13585 return mHardwareLayer; 13586 } 13587 13588 /** 13589 * Destroys this View's hardware layer if possible. 13590 * 13591 * @return True if the layer was destroyed, false otherwise. 13592 * 13593 * @see #setLayerType(int, android.graphics.Paint) 13594 * @see #LAYER_TYPE_HARDWARE 13595 */ 13596 boolean destroyLayer(boolean valid) { 13597 if (mHardwareLayer != null) { 13598 mHardwareLayer.destroy(); 13599 mHardwareLayer = null; 13600 13601 invalidate(true); 13602 invalidateParentCaches(); 13603 return true; 13604 } 13605 return false; 13606 } 13607 13608 /** 13609 * Destroys all hardware rendering resources. This method is invoked 13610 * when the system needs to reclaim resources. Upon execution of this 13611 * method, you should free any OpenGL resources created by the view. 13612 * 13613 * Note: you <strong>must</strong> call 13614 * <code>super.destroyHardwareResources()</code> when overriding 13615 * this method. 13616 * 13617 * @hide 13618 */ 13619 protected void destroyHardwareResources() { 13620 resetDisplayList(); 13621 destroyLayer(true); 13622 } 13623 13624 /** 13625 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 13626 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 13627 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 13628 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 13629 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 13630 * null.</p> 13631 * 13632 * <p>Enabling the drawing cache is similar to 13633 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 13634 * acceleration is turned off. When hardware acceleration is turned on, enabling the 13635 * drawing cache has no effect on rendering because the system uses a different mechanism 13636 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 13637 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 13638 * for information on how to enable software and hardware layers.</p> 13639 * 13640 * <p>This API can be used to manually generate 13641 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 13642 * {@link #getDrawingCache()}.</p> 13643 * 13644 * @param enabled true to enable the drawing cache, false otherwise 13645 * 13646 * @see #isDrawingCacheEnabled() 13647 * @see #getDrawingCache() 13648 * @see #buildDrawingCache() 13649 * @see #setLayerType(int, android.graphics.Paint) 13650 */ 13651 public void setDrawingCacheEnabled(boolean enabled) { 13652 mCachingFailed = false; 13653 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 13654 } 13655 13656 /** 13657 * <p>Indicates whether the drawing cache is enabled for this view.</p> 13658 * 13659 * @return true if the drawing cache is enabled 13660 * 13661 * @see #setDrawingCacheEnabled(boolean) 13662 * @see #getDrawingCache() 13663 */ 13664 @ViewDebug.ExportedProperty(category = "drawing") 13665 public boolean isDrawingCacheEnabled() { 13666 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 13667 } 13668 13669 /** 13670 * Debugging utility which recursively outputs the dirty state of a view and its 13671 * descendants. 13672 * 13673 * @hide 13674 */ 13675 @SuppressWarnings({"UnusedDeclaration"}) 13676 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 13677 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) + 13678 ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" + 13679 (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) + 13680 ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")"); 13681 if (clear) { 13682 mPrivateFlags &= clearMask; 13683 } 13684 if (this instanceof ViewGroup) { 13685 ViewGroup parent = (ViewGroup) this; 13686 final int count = parent.getChildCount(); 13687 for (int i = 0; i < count; i++) { 13688 final View child = parent.getChildAt(i); 13689 child.outputDirtyFlags(indent + " ", clear, clearMask); 13690 } 13691 } 13692 } 13693 13694 /** 13695 * This method is used by ViewGroup to cause its children to restore or recreate their 13696 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 13697 * to recreate its own display list, which would happen if it went through the normal 13698 * draw/dispatchDraw mechanisms. 13699 * 13700 * @hide 13701 */ 13702 protected void dispatchGetDisplayList() {} 13703 13704 /** 13705 * A view that is not attached or hardware accelerated cannot create a display list. 13706 * This method checks these conditions and returns the appropriate result. 13707 * 13708 * @return true if view has the ability to create a display list, false otherwise. 13709 * 13710 * @hide 13711 */ 13712 public boolean canHaveDisplayList() { 13713 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 13714 } 13715 13716 /** 13717 * Returns a DisplayList. If the incoming displayList is null, one will be created. 13718 * Otherwise, the same display list will be returned (after having been rendered into 13719 * along the way, depending on the invalidation state of the view). 13720 * 13721 * @param renderNode The previous version of this displayList, could be null. 13722 * @param isLayer Whether the requester of the display list is a layer. If so, 13723 * the view will avoid creating a layer inside the resulting display list. 13724 * @return A new or reused DisplayList object. 13725 */ 13726 private void updateDisplayListIfDirty(@NonNull RenderNode renderNode, boolean isLayer) { 13727 if (renderNode == null) { 13728 throw new IllegalArgumentException("RenderNode must not be null"); 13729 } 13730 if (!canHaveDisplayList()) { 13731 // can't populate RenderNode, don't try 13732 return; 13733 } 13734 13735 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 13736 || !renderNode.isValid() 13737 || (!isLayer && mRecreateDisplayList)) { 13738 // Don't need to recreate the display list, just need to tell our 13739 // children to restore/recreate theirs 13740 if (renderNode.isValid() 13741 && !isLayer 13742 && !mRecreateDisplayList) { 13743 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13744 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13745 dispatchGetDisplayList(); 13746 13747 return; // no work needed 13748 } 13749 13750 if (!isLayer) { 13751 // If we got here, we're recreating it. Mark it as such to ensure that 13752 // we copy in child display lists into ours in drawChild() 13753 mRecreateDisplayList = true; 13754 } 13755 13756 boolean caching = false; 13757 int width = mRight - mLeft; 13758 int height = mBottom - mTop; 13759 int layerType = getLayerType(); 13760 13761 final HardwareCanvas canvas = renderNode.start(width, height); 13762 13763 try { 13764 if (!isLayer && layerType != LAYER_TYPE_NONE) { 13765 if (layerType == LAYER_TYPE_HARDWARE) { 13766 final HardwareLayer layer = getHardwareLayer(); 13767 if (layer != null && layer.isValid()) { 13768 canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint); 13769 } else { 13770 canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint, 13771 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | 13772 Canvas.CLIP_TO_LAYER_SAVE_FLAG); 13773 } 13774 caching = true; 13775 } else { 13776 buildDrawingCache(true); 13777 Bitmap cache = getDrawingCache(true); 13778 if (cache != null) { 13779 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 13780 caching = true; 13781 } 13782 } 13783 } else { 13784 13785 computeScroll(); 13786 13787 canvas.translate(-mScrollX, -mScrollY); 13788 if (!isLayer) { 13789 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13790 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13791 } 13792 13793 // Fast path for layouts with no backgrounds 13794 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 13795 dispatchDraw(canvas); 13796 if (mOverlay != null && !mOverlay.isEmpty()) { 13797 mOverlay.getOverlayView().draw(canvas); 13798 } 13799 } else { 13800 draw(canvas); 13801 } 13802 } 13803 } finally { 13804 renderNode.end(canvas); 13805 renderNode.setCaching(caching); 13806 if (isLayer) { 13807 renderNode.setLeftTopRightBottom(0, 0, width, height); 13808 } else { 13809 setDisplayListProperties(renderNode); 13810 } 13811 } 13812 } else if (!isLayer) { 13813 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13814 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13815 } 13816 } 13817 13818 /** 13819 * Returns a RenderNode with View draw content recorded, which can be 13820 * used to draw this view again without executing its draw method. 13821 * 13822 * @return A RenderNode ready to replay, or null if caching is not enabled. 13823 * 13824 * @hide 13825 */ 13826 public RenderNode getDisplayList() { 13827 updateDisplayListIfDirty(mRenderNode, false); 13828 return mRenderNode; 13829 } 13830 13831 private void resetDisplayList() { 13832 if (mRenderNode.isValid()) { 13833 mRenderNode.destroyDisplayListData(); 13834 } 13835 13836 if (mBackgroundDisplayList != null && mBackgroundDisplayList.isValid()) { 13837 mBackgroundDisplayList.destroyDisplayListData(); 13838 } 13839 } 13840 13841 /** 13842 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 13843 * 13844 * @return A non-scaled bitmap representing this view or null if cache is disabled. 13845 * 13846 * @see #getDrawingCache(boolean) 13847 */ 13848 public Bitmap getDrawingCache() { 13849 return getDrawingCache(false); 13850 } 13851 13852 /** 13853 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 13854 * is null when caching is disabled. If caching is enabled and the cache is not ready, 13855 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 13856 * draw from the cache when the cache is enabled. To benefit from the cache, you must 13857 * request the drawing cache by calling this method and draw it on screen if the 13858 * returned bitmap is not null.</p> 13859 * 13860 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 13861 * this method will create a bitmap of the same size as this view. Because this bitmap 13862 * will be drawn scaled by the parent ViewGroup, the result on screen might show 13863 * scaling artifacts. To avoid such artifacts, you should call this method by setting 13864 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 13865 * size than the view. This implies that your application must be able to handle this 13866 * size.</p> 13867 * 13868 * @param autoScale Indicates whether the generated bitmap should be scaled based on 13869 * the current density of the screen when the application is in compatibility 13870 * mode. 13871 * 13872 * @return A bitmap representing this view or null if cache is disabled. 13873 * 13874 * @see #setDrawingCacheEnabled(boolean) 13875 * @see #isDrawingCacheEnabled() 13876 * @see #buildDrawingCache(boolean) 13877 * @see #destroyDrawingCache() 13878 */ 13879 public Bitmap getDrawingCache(boolean autoScale) { 13880 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 13881 return null; 13882 } 13883 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 13884 buildDrawingCache(autoScale); 13885 } 13886 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 13887 } 13888 13889 /** 13890 * <p>Frees the resources used by the drawing cache. If you call 13891 * {@link #buildDrawingCache()} manually without calling 13892 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 13893 * should cleanup the cache with this method afterwards.</p> 13894 * 13895 * @see #setDrawingCacheEnabled(boolean) 13896 * @see #buildDrawingCache() 13897 * @see #getDrawingCache() 13898 */ 13899 public void destroyDrawingCache() { 13900 if (mDrawingCache != null) { 13901 mDrawingCache.recycle(); 13902 mDrawingCache = null; 13903 } 13904 if (mUnscaledDrawingCache != null) { 13905 mUnscaledDrawingCache.recycle(); 13906 mUnscaledDrawingCache = null; 13907 } 13908 } 13909 13910 /** 13911 * Setting a solid background color for the drawing cache's bitmaps will improve 13912 * performance and memory usage. Note, though that this should only be used if this 13913 * view will always be drawn on top of a solid color. 13914 * 13915 * @param color The background color to use for the drawing cache's bitmap 13916 * 13917 * @see #setDrawingCacheEnabled(boolean) 13918 * @see #buildDrawingCache() 13919 * @see #getDrawingCache() 13920 */ 13921 public void setDrawingCacheBackgroundColor(int color) { 13922 if (color != mDrawingCacheBackgroundColor) { 13923 mDrawingCacheBackgroundColor = color; 13924 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 13925 } 13926 } 13927 13928 /** 13929 * @see #setDrawingCacheBackgroundColor(int) 13930 * 13931 * @return The background color to used for the drawing cache's bitmap 13932 */ 13933 public int getDrawingCacheBackgroundColor() { 13934 return mDrawingCacheBackgroundColor; 13935 } 13936 13937 /** 13938 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 13939 * 13940 * @see #buildDrawingCache(boolean) 13941 */ 13942 public void buildDrawingCache() { 13943 buildDrawingCache(false); 13944 } 13945 13946 /** 13947 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 13948 * 13949 * <p>If you call {@link #buildDrawingCache()} manually without calling 13950 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 13951 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 13952 * 13953 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 13954 * this method will create a bitmap of the same size as this view. Because this bitmap 13955 * will be drawn scaled by the parent ViewGroup, the result on screen might show 13956 * scaling artifacts. To avoid such artifacts, you should call this method by setting 13957 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 13958 * size than the view. This implies that your application must be able to handle this 13959 * size.</p> 13960 * 13961 * <p>You should avoid calling this method when hardware acceleration is enabled. If 13962 * you do not need the drawing cache bitmap, calling this method will increase memory 13963 * usage and cause the view to be rendered in software once, thus negatively impacting 13964 * performance.</p> 13965 * 13966 * @see #getDrawingCache() 13967 * @see #destroyDrawingCache() 13968 */ 13969 public void buildDrawingCache(boolean autoScale) { 13970 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ? 13971 mDrawingCache == null : mUnscaledDrawingCache == null)) { 13972 mCachingFailed = false; 13973 13974 int width = mRight - mLeft; 13975 int height = mBottom - mTop; 13976 13977 final AttachInfo attachInfo = mAttachInfo; 13978 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 13979 13980 if (autoScale && scalingRequired) { 13981 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 13982 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 13983 } 13984 13985 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 13986 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 13987 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 13988 13989 final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4); 13990 final long drawingCacheSize = 13991 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize(); 13992 if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) { 13993 if (width > 0 && height > 0) { 13994 Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs " 13995 + projectedBitmapSize + " bytes, only " 13996 + drawingCacheSize + " available"); 13997 } 13998 destroyDrawingCache(); 13999 mCachingFailed = true; 14000 return; 14001 } 14002 14003 boolean clear = true; 14004 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 14005 14006 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 14007 Bitmap.Config quality; 14008 if (!opaque) { 14009 // Never pick ARGB_4444 because it looks awful 14010 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 14011 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 14012 case DRAWING_CACHE_QUALITY_AUTO: 14013 case DRAWING_CACHE_QUALITY_LOW: 14014 case DRAWING_CACHE_QUALITY_HIGH: 14015 default: 14016 quality = Bitmap.Config.ARGB_8888; 14017 break; 14018 } 14019 } else { 14020 // Optimization for translucent windows 14021 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 14022 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 14023 } 14024 14025 // Try to cleanup memory 14026 if (bitmap != null) bitmap.recycle(); 14027 14028 try { 14029 bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 14030 width, height, quality); 14031 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 14032 if (autoScale) { 14033 mDrawingCache = bitmap; 14034 } else { 14035 mUnscaledDrawingCache = bitmap; 14036 } 14037 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 14038 } catch (OutOfMemoryError e) { 14039 // If there is not enough memory to create the bitmap cache, just 14040 // ignore the issue as bitmap caches are not required to draw the 14041 // view hierarchy 14042 if (autoScale) { 14043 mDrawingCache = null; 14044 } else { 14045 mUnscaledDrawingCache = null; 14046 } 14047 mCachingFailed = true; 14048 return; 14049 } 14050 14051 clear = drawingCacheBackgroundColor != 0; 14052 } 14053 14054 Canvas canvas; 14055 if (attachInfo != null) { 14056 canvas = attachInfo.mCanvas; 14057 if (canvas == null) { 14058 canvas = new Canvas(); 14059 } 14060 canvas.setBitmap(bitmap); 14061 // Temporarily clobber the cached Canvas in case one of our children 14062 // is also using a drawing cache. Without this, the children would 14063 // steal the canvas by attaching their own bitmap to it and bad, bad 14064 // thing would happen (invisible views, corrupted drawings, etc.) 14065 attachInfo.mCanvas = null; 14066 } else { 14067 // This case should hopefully never or seldom happen 14068 canvas = new Canvas(bitmap); 14069 } 14070 14071 if (clear) { 14072 bitmap.eraseColor(drawingCacheBackgroundColor); 14073 } 14074 14075 computeScroll(); 14076 final int restoreCount = canvas.save(); 14077 14078 if (autoScale && scalingRequired) { 14079 final float scale = attachInfo.mApplicationScale; 14080 canvas.scale(scale, scale); 14081 } 14082 14083 canvas.translate(-mScrollX, -mScrollY); 14084 14085 mPrivateFlags |= PFLAG_DRAWN; 14086 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 14087 mLayerType != LAYER_TYPE_NONE) { 14088 mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID; 14089 } 14090 14091 // Fast path for layouts with no backgrounds 14092 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14093 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14094 dispatchDraw(canvas); 14095 if (mOverlay != null && !mOverlay.isEmpty()) { 14096 mOverlay.getOverlayView().draw(canvas); 14097 } 14098 } else { 14099 draw(canvas); 14100 } 14101 14102 canvas.restoreToCount(restoreCount); 14103 canvas.setBitmap(null); 14104 14105 if (attachInfo != null) { 14106 // Restore the cached Canvas for our siblings 14107 attachInfo.mCanvas = canvas; 14108 } 14109 } 14110 } 14111 14112 /** 14113 * Create a snapshot of the view into a bitmap. We should probably make 14114 * some form of this public, but should think about the API. 14115 */ 14116 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 14117 int width = mRight - mLeft; 14118 int height = mBottom - mTop; 14119 14120 final AttachInfo attachInfo = mAttachInfo; 14121 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 14122 width = (int) ((width * scale) + 0.5f); 14123 height = (int) ((height * scale) + 0.5f); 14124 14125 Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 14126 width > 0 ? width : 1, height > 0 ? height : 1, quality); 14127 if (bitmap == null) { 14128 throw new OutOfMemoryError(); 14129 } 14130 14131 Resources resources = getResources(); 14132 if (resources != null) { 14133 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 14134 } 14135 14136 Canvas canvas; 14137 if (attachInfo != null) { 14138 canvas = attachInfo.mCanvas; 14139 if (canvas == null) { 14140 canvas = new Canvas(); 14141 } 14142 canvas.setBitmap(bitmap); 14143 // Temporarily clobber the cached Canvas in case one of our children 14144 // is also using a drawing cache. Without this, the children would 14145 // steal the canvas by attaching their own bitmap to it and bad, bad 14146 // things would happen (invisible views, corrupted drawings, etc.) 14147 attachInfo.mCanvas = null; 14148 } else { 14149 // This case should hopefully never or seldom happen 14150 canvas = new Canvas(bitmap); 14151 } 14152 14153 if ((backgroundColor & 0xff000000) != 0) { 14154 bitmap.eraseColor(backgroundColor); 14155 } 14156 14157 computeScroll(); 14158 final int restoreCount = canvas.save(); 14159 canvas.scale(scale, scale); 14160 canvas.translate(-mScrollX, -mScrollY); 14161 14162 // Temporarily remove the dirty mask 14163 int flags = mPrivateFlags; 14164 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14165 14166 // Fast path for layouts with no backgrounds 14167 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14168 dispatchDraw(canvas); 14169 if (mOverlay != null && !mOverlay.isEmpty()) { 14170 mOverlay.getOverlayView().draw(canvas); 14171 } 14172 } else { 14173 draw(canvas); 14174 } 14175 14176 mPrivateFlags = flags; 14177 14178 canvas.restoreToCount(restoreCount); 14179 canvas.setBitmap(null); 14180 14181 if (attachInfo != null) { 14182 // Restore the cached Canvas for our siblings 14183 attachInfo.mCanvas = canvas; 14184 } 14185 14186 return bitmap; 14187 } 14188 14189 /** 14190 * Indicates whether this View is currently in edit mode. A View is usually 14191 * in edit mode when displayed within a developer tool. For instance, if 14192 * this View is being drawn by a visual user interface builder, this method 14193 * should return true. 14194 * 14195 * Subclasses should check the return value of this method to provide 14196 * different behaviors if their normal behavior might interfere with the 14197 * host environment. For instance: the class spawns a thread in its 14198 * constructor, the drawing code relies on device-specific features, etc. 14199 * 14200 * This method is usually checked in the drawing code of custom widgets. 14201 * 14202 * @return True if this View is in edit mode, false otherwise. 14203 */ 14204 public boolean isInEditMode() { 14205 return false; 14206 } 14207 14208 /** 14209 * If the View draws content inside its padding and enables fading edges, 14210 * it needs to support padding offsets. Padding offsets are added to the 14211 * fading edges to extend the length of the fade so that it covers pixels 14212 * drawn inside the padding. 14213 * 14214 * Subclasses of this class should override this method if they need 14215 * to draw content inside the padding. 14216 * 14217 * @return True if padding offset must be applied, false otherwise. 14218 * 14219 * @see #getLeftPaddingOffset() 14220 * @see #getRightPaddingOffset() 14221 * @see #getTopPaddingOffset() 14222 * @see #getBottomPaddingOffset() 14223 * 14224 * @since CURRENT 14225 */ 14226 protected boolean isPaddingOffsetRequired() { 14227 return false; 14228 } 14229 14230 /** 14231 * Amount by which to extend the left fading region. Called only when 14232 * {@link #isPaddingOffsetRequired()} returns true. 14233 * 14234 * @return The left padding offset in pixels. 14235 * 14236 * @see #isPaddingOffsetRequired() 14237 * 14238 * @since CURRENT 14239 */ 14240 protected int getLeftPaddingOffset() { 14241 return 0; 14242 } 14243 14244 /** 14245 * Amount by which to extend the right fading region. Called only when 14246 * {@link #isPaddingOffsetRequired()} returns true. 14247 * 14248 * @return The right padding offset in pixels. 14249 * 14250 * @see #isPaddingOffsetRequired() 14251 * 14252 * @since CURRENT 14253 */ 14254 protected int getRightPaddingOffset() { 14255 return 0; 14256 } 14257 14258 /** 14259 * Amount by which to extend the top fading region. Called only when 14260 * {@link #isPaddingOffsetRequired()} returns true. 14261 * 14262 * @return The top padding offset in pixels. 14263 * 14264 * @see #isPaddingOffsetRequired() 14265 * 14266 * @since CURRENT 14267 */ 14268 protected int getTopPaddingOffset() { 14269 return 0; 14270 } 14271 14272 /** 14273 * Amount by which to extend the bottom fading region. Called only when 14274 * {@link #isPaddingOffsetRequired()} returns true. 14275 * 14276 * @return The bottom padding offset in pixels. 14277 * 14278 * @see #isPaddingOffsetRequired() 14279 * 14280 * @since CURRENT 14281 */ 14282 protected int getBottomPaddingOffset() { 14283 return 0; 14284 } 14285 14286 /** 14287 * @hide 14288 * @param offsetRequired 14289 */ 14290 protected int getFadeTop(boolean offsetRequired) { 14291 int top = mPaddingTop; 14292 if (offsetRequired) top += getTopPaddingOffset(); 14293 return top; 14294 } 14295 14296 /** 14297 * @hide 14298 * @param offsetRequired 14299 */ 14300 protected int getFadeHeight(boolean offsetRequired) { 14301 int padding = mPaddingTop; 14302 if (offsetRequired) padding += getTopPaddingOffset(); 14303 return mBottom - mTop - mPaddingBottom - padding; 14304 } 14305 14306 /** 14307 * <p>Indicates whether this view is attached to a hardware accelerated 14308 * window or not.</p> 14309 * 14310 * <p>Even if this method returns true, it does not mean that every call 14311 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 14312 * accelerated {@link android.graphics.Canvas}. For instance, if this view 14313 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 14314 * window is hardware accelerated, 14315 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 14316 * return false, and this method will return true.</p> 14317 * 14318 * @return True if the view is attached to a window and the window is 14319 * hardware accelerated; false in any other case. 14320 */ 14321 public boolean isHardwareAccelerated() { 14322 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 14323 } 14324 14325 /** 14326 * Sets a rectangular area on this view to which the view will be clipped 14327 * when it is drawn. Setting the value to null will remove the clip bounds 14328 * and the view will draw normally, using its full bounds. 14329 * 14330 * @param clipBounds The rectangular area, in the local coordinates of 14331 * this view, to which future drawing operations will be clipped. 14332 */ 14333 public void setClipBounds(Rect clipBounds) { 14334 if (clipBounds != null) { 14335 if (clipBounds.equals(mClipBounds)) { 14336 return; 14337 } 14338 if (mClipBounds == null) { 14339 invalidate(); 14340 mClipBounds = new Rect(clipBounds); 14341 } else { 14342 invalidate(Math.min(mClipBounds.left, clipBounds.left), 14343 Math.min(mClipBounds.top, clipBounds.top), 14344 Math.max(mClipBounds.right, clipBounds.right), 14345 Math.max(mClipBounds.bottom, clipBounds.bottom)); 14346 mClipBounds.set(clipBounds); 14347 } 14348 } else { 14349 if (mClipBounds != null) { 14350 invalidate(); 14351 mClipBounds = null; 14352 } 14353 } 14354 } 14355 14356 /** 14357 * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}. 14358 * 14359 * @return A copy of the current clip bounds if clip bounds are set, 14360 * otherwise null. 14361 */ 14362 public Rect getClipBounds() { 14363 return (mClipBounds != null) ? new Rect(mClipBounds) : null; 14364 } 14365 14366 /** 14367 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 14368 * case of an active Animation being run on the view. 14369 */ 14370 private boolean drawAnimation(ViewGroup parent, long drawingTime, 14371 Animation a, boolean scalingRequired) { 14372 Transformation invalidationTransform; 14373 final int flags = parent.mGroupFlags; 14374 final boolean initialized = a.isInitialized(); 14375 if (!initialized) { 14376 a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight()); 14377 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 14378 if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler); 14379 onAnimationStart(); 14380 } 14381 14382 final Transformation t = parent.getChildTransformation(); 14383 boolean more = a.getTransformation(drawingTime, t, 1f); 14384 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 14385 if (parent.mInvalidationTransformation == null) { 14386 parent.mInvalidationTransformation = new Transformation(); 14387 } 14388 invalidationTransform = parent.mInvalidationTransformation; 14389 a.getTransformation(drawingTime, invalidationTransform, 1f); 14390 } else { 14391 invalidationTransform = t; 14392 } 14393 14394 if (more) { 14395 if (!a.willChangeBounds()) { 14396 if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) == 14397 ViewGroup.FLAG_OPTIMIZE_INVALIDATE) { 14398 parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED; 14399 } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) { 14400 // The child need to draw an animation, potentially offscreen, so 14401 // make sure we do not cancel invalidate requests 14402 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 14403 parent.invalidate(mLeft, mTop, mRight, mBottom); 14404 } 14405 } else { 14406 if (parent.mInvalidateRegion == null) { 14407 parent.mInvalidateRegion = new RectF(); 14408 } 14409 final RectF region = parent.mInvalidateRegion; 14410 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 14411 invalidationTransform); 14412 14413 // The child need to draw an animation, potentially offscreen, so 14414 // make sure we do not cancel invalidate requests 14415 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 14416 14417 final int left = mLeft + (int) region.left; 14418 final int top = mTop + (int) region.top; 14419 parent.invalidate(left, top, left + (int) (region.width() + .5f), 14420 top + (int) (region.height() + .5f)); 14421 } 14422 } 14423 return more; 14424 } 14425 14426 /** 14427 * This method is called by getDisplayList() when a display list is recorded for a View. 14428 * It pushes any properties to the RenderNode that aren't managed by the RenderNode. 14429 */ 14430 void setDisplayListProperties(RenderNode renderNode) { 14431 if (renderNode != null) { 14432 renderNode.setHasOverlappingRendering(hasOverlappingRendering()); 14433 if (mParent instanceof ViewGroup) { 14434 renderNode.setClipToBounds( 14435 (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0); 14436 } 14437 float alpha = 1; 14438 if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags & 14439 ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 14440 ViewGroup parentVG = (ViewGroup) mParent; 14441 final Transformation t = parentVG.getChildTransformation(); 14442 if (parentVG.getChildStaticTransformation(this, t)) { 14443 final int transformType = t.getTransformationType(); 14444 if (transformType != Transformation.TYPE_IDENTITY) { 14445 if ((transformType & Transformation.TYPE_ALPHA) != 0) { 14446 alpha = t.getAlpha(); 14447 } 14448 if ((transformType & Transformation.TYPE_MATRIX) != 0) { 14449 renderNode.setStaticMatrix(t.getMatrix()); 14450 } 14451 } 14452 } 14453 } 14454 if (mTransformationInfo != null) { 14455 alpha *= getFinalAlpha(); 14456 if (alpha < 1) { 14457 final int multipliedAlpha = (int) (255 * alpha); 14458 if (onSetAlpha(multipliedAlpha)) { 14459 alpha = 1; 14460 } 14461 } 14462 renderNode.setAlpha(alpha); 14463 } else if (alpha < 1) { 14464 renderNode.setAlpha(alpha); 14465 } 14466 } 14467 } 14468 14469 /** 14470 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 14471 * This draw() method is an implementation detail and is not intended to be overridden or 14472 * to be called from anywhere else other than ViewGroup.drawChild(). 14473 */ 14474 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 14475 boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 14476 boolean more = false; 14477 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 14478 final int flags = parent.mGroupFlags; 14479 14480 if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) { 14481 parent.getChildTransformation().clear(); 14482 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14483 } 14484 14485 Transformation transformToApply = null; 14486 boolean concatMatrix = false; 14487 14488 boolean scalingRequired = false; 14489 boolean caching; 14490 int layerType = getLayerType(); 14491 14492 final boolean hardwareAccelerated = canvas.isHardwareAccelerated(); 14493 if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 || 14494 (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) { 14495 caching = true; 14496 // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList 14497 if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired; 14498 } else { 14499 caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated; 14500 } 14501 14502 final Animation a = getAnimation(); 14503 if (a != null) { 14504 more = drawAnimation(parent, drawingTime, a, scalingRequired); 14505 concatMatrix = a.willChangeTransformationMatrix(); 14506 if (concatMatrix) { 14507 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 14508 } 14509 transformToApply = parent.getChildTransformation(); 14510 } else { 14511 if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) { 14512 // No longer animating: clear out old animation matrix 14513 mRenderNode.setAnimationMatrix(null); 14514 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 14515 } 14516 if (!useDisplayListProperties && 14517 (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 14518 final Transformation t = parent.getChildTransformation(); 14519 final boolean hasTransform = parent.getChildStaticTransformation(this, t); 14520 if (hasTransform) { 14521 final int transformType = t.getTransformationType(); 14522 transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null; 14523 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 14524 } 14525 } 14526 } 14527 14528 concatMatrix |= !childHasIdentityMatrix; 14529 14530 // Sets the flag as early as possible to allow draw() implementations 14531 // to call invalidate() successfully when doing animations 14532 mPrivateFlags |= PFLAG_DRAWN; 14533 14534 if (!concatMatrix && 14535 (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS | 14536 ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN && 14537 canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 14538 (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) { 14539 mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED; 14540 return more; 14541 } 14542 mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED; 14543 14544 if (hardwareAccelerated) { 14545 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 14546 // retain the flag's value temporarily in the mRecreateDisplayList flag 14547 mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED; 14548 mPrivateFlags &= ~PFLAG_INVALIDATED; 14549 } 14550 14551 RenderNode displayList = null; 14552 Bitmap cache = null; 14553 boolean hasDisplayList = false; 14554 if (caching) { 14555 if (!hardwareAccelerated) { 14556 if (layerType != LAYER_TYPE_NONE) { 14557 layerType = LAYER_TYPE_SOFTWARE; 14558 buildDrawingCache(true); 14559 } 14560 cache = getDrawingCache(true); 14561 } else { 14562 switch (layerType) { 14563 case LAYER_TYPE_SOFTWARE: 14564 if (useDisplayListProperties) { 14565 hasDisplayList = canHaveDisplayList(); 14566 } else { 14567 buildDrawingCache(true); 14568 cache = getDrawingCache(true); 14569 } 14570 break; 14571 case LAYER_TYPE_HARDWARE: 14572 if (useDisplayListProperties) { 14573 hasDisplayList = canHaveDisplayList(); 14574 } 14575 break; 14576 case LAYER_TYPE_NONE: 14577 // Delay getting the display list until animation-driven alpha values are 14578 // set up and possibly passed on to the view 14579 hasDisplayList = canHaveDisplayList(); 14580 break; 14581 } 14582 } 14583 } 14584 useDisplayListProperties &= hasDisplayList; 14585 if (useDisplayListProperties) { 14586 displayList = getDisplayList(); 14587 if (!displayList.isValid()) { 14588 // Uncommon, but possible. If a view is removed from the hierarchy during the call 14589 // to getDisplayList(), the display list will be marked invalid and we should not 14590 // try to use it again. 14591 displayList = null; 14592 hasDisplayList = false; 14593 useDisplayListProperties = false; 14594 } 14595 } 14596 14597 int sx = 0; 14598 int sy = 0; 14599 if (!hasDisplayList) { 14600 computeScroll(); 14601 sx = mScrollX; 14602 sy = mScrollY; 14603 } 14604 14605 final boolean hasNoCache = cache == null || hasDisplayList; 14606 final boolean offsetForScroll = cache == null && !hasDisplayList && 14607 layerType != LAYER_TYPE_HARDWARE; 14608 14609 int restoreTo = -1; 14610 if (!useDisplayListProperties || transformToApply != null) { 14611 restoreTo = canvas.save(); 14612 } 14613 if (offsetForScroll) { 14614 canvas.translate(mLeft - sx, mTop - sy); 14615 } else { 14616 if (!useDisplayListProperties) { 14617 canvas.translate(mLeft, mTop); 14618 } 14619 if (scalingRequired) { 14620 if (useDisplayListProperties) { 14621 // TODO: Might not need this if we put everything inside the DL 14622 restoreTo = canvas.save(); 14623 } 14624 // mAttachInfo cannot be null, otherwise scalingRequired == false 14625 final float scale = 1.0f / mAttachInfo.mApplicationScale; 14626 canvas.scale(scale, scale); 14627 } 14628 } 14629 14630 float alpha = useDisplayListProperties ? 1 : (getAlpha() * getTransitionAlpha()); 14631 if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() || 14632 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 14633 if (transformToApply != null || !childHasIdentityMatrix) { 14634 int transX = 0; 14635 int transY = 0; 14636 14637 if (offsetForScroll) { 14638 transX = -sx; 14639 transY = -sy; 14640 } 14641 14642 if (transformToApply != null) { 14643 if (concatMatrix) { 14644 if (useDisplayListProperties) { 14645 displayList.setAnimationMatrix(transformToApply.getMatrix()); 14646 } else { 14647 // Undo the scroll translation, apply the transformation matrix, 14648 // then redo the scroll translate to get the correct result. 14649 canvas.translate(-transX, -transY); 14650 canvas.concat(transformToApply.getMatrix()); 14651 canvas.translate(transX, transY); 14652 } 14653 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14654 } 14655 14656 float transformAlpha = transformToApply.getAlpha(); 14657 if (transformAlpha < 1) { 14658 alpha *= transformAlpha; 14659 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14660 } 14661 } 14662 14663 if (!childHasIdentityMatrix && !useDisplayListProperties) { 14664 canvas.translate(-transX, -transY); 14665 canvas.concat(getMatrix()); 14666 canvas.translate(transX, transY); 14667 } 14668 } 14669 14670 // Deal with alpha if it is or used to be <1 14671 if (alpha < 1 || 14672 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 14673 if (alpha < 1) { 14674 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA; 14675 } else { 14676 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA; 14677 } 14678 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14679 if (hasNoCache) { 14680 final int multipliedAlpha = (int) (255 * alpha); 14681 if (!onSetAlpha(multipliedAlpha)) { 14682 int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 14683 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 || 14684 layerType != LAYER_TYPE_NONE) { 14685 layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG; 14686 } 14687 if (useDisplayListProperties) { 14688 displayList.setAlpha(alpha * getAlpha() * getTransitionAlpha()); 14689 } else if (layerType == LAYER_TYPE_NONE) { 14690 final int scrollX = hasDisplayList ? 0 : sx; 14691 final int scrollY = hasDisplayList ? 0 : sy; 14692 canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft, 14693 scrollY + mBottom - mTop, multipliedAlpha, layerFlags); 14694 } 14695 } else { 14696 // Alpha is handled by the child directly, clobber the layer's alpha 14697 mPrivateFlags |= PFLAG_ALPHA_SET; 14698 } 14699 } 14700 } 14701 } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 14702 onSetAlpha(255); 14703 mPrivateFlags &= ~PFLAG_ALPHA_SET; 14704 } 14705 14706 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN && 14707 !useDisplayListProperties && cache == null) { 14708 if (offsetForScroll) { 14709 canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop)); 14710 } else { 14711 if (!scalingRequired || cache == null) { 14712 canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop); 14713 } else { 14714 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 14715 } 14716 } 14717 } 14718 14719 if (!useDisplayListProperties && hasDisplayList) { 14720 displayList = getDisplayList(); 14721 if (!displayList.isValid()) { 14722 // Uncommon, but possible. If a view is removed from the hierarchy during the call 14723 // to getDisplayList(), the display list will be marked invalid and we should not 14724 // try to use it again. 14725 displayList = null; 14726 hasDisplayList = false; 14727 } 14728 } 14729 14730 if (hasNoCache) { 14731 boolean layerRendered = false; 14732 if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) { 14733 final HardwareLayer layer = getHardwareLayer(); 14734 if (layer != null && layer.isValid()) { 14735 mLayerPaint.setAlpha((int) (alpha * 255)); 14736 ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint); 14737 layerRendered = true; 14738 } else { 14739 final int scrollX = hasDisplayList ? 0 : sx; 14740 final int scrollY = hasDisplayList ? 0 : sy; 14741 canvas.saveLayer(scrollX, scrollY, 14742 scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint, 14743 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG); 14744 } 14745 } 14746 14747 if (!layerRendered) { 14748 if (!hasDisplayList) { 14749 // Fast path for layouts with no backgrounds 14750 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14751 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14752 dispatchDraw(canvas); 14753 } else { 14754 draw(canvas); 14755 } 14756 } else { 14757 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14758 ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags); 14759 } 14760 } 14761 } else if (cache != null) { 14762 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14763 Paint cachePaint; 14764 14765 if (layerType == LAYER_TYPE_NONE) { 14766 cachePaint = parent.mCachePaint; 14767 if (cachePaint == null) { 14768 cachePaint = new Paint(); 14769 cachePaint.setDither(false); 14770 parent.mCachePaint = cachePaint; 14771 } 14772 if (alpha < 1) { 14773 cachePaint.setAlpha((int) (alpha * 255)); 14774 parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 14775 } else if ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) { 14776 cachePaint.setAlpha(255); 14777 parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 14778 } 14779 } else { 14780 cachePaint = mLayerPaint; 14781 cachePaint.setAlpha((int) (alpha * 255)); 14782 } 14783 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 14784 } 14785 14786 if (restoreTo >= 0) { 14787 canvas.restoreToCount(restoreTo); 14788 } 14789 14790 if (a != null && !more) { 14791 if (!hardwareAccelerated && !a.getFillAfter()) { 14792 onSetAlpha(255); 14793 } 14794 parent.finishAnimatingView(this, a); 14795 } 14796 14797 if (more && hardwareAccelerated) { 14798 if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 14799 // alpha animations should cause the child to recreate its display list 14800 invalidate(true); 14801 } 14802 } 14803 14804 mRecreateDisplayList = false; 14805 14806 return more; 14807 } 14808 14809 /** 14810 * Manually render this view (and all of its children) to the given Canvas. 14811 * The view must have already done a full layout before this function is 14812 * called. When implementing a view, implement 14813 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 14814 * If you do need to override this method, call the superclass version. 14815 * 14816 * @param canvas The Canvas to which the View is rendered. 14817 */ 14818 public void draw(Canvas canvas) { 14819 if (mClipBounds != null) { 14820 canvas.clipRect(mClipBounds); 14821 } 14822 final int privateFlags = mPrivateFlags; 14823 final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE && 14824 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 14825 mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN; 14826 14827 /* 14828 * Draw traversal performs several drawing steps which must be executed 14829 * in the appropriate order: 14830 * 14831 * 1. Draw the background 14832 * 2. If necessary, save the canvas' layers to prepare for fading 14833 * 3. Draw view's content 14834 * 4. Draw children 14835 * 5. If necessary, draw the fading edges and restore layers 14836 * 6. Draw decorations (scrollbars for instance) 14837 */ 14838 14839 // Step 1, draw the background, if needed 14840 int saveCount; 14841 14842 if (!dirtyOpaque) { 14843 drawBackground(canvas); 14844 } 14845 14846 // skip step 2 & 5 if possible (common case) 14847 final int viewFlags = mViewFlags; 14848 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 14849 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 14850 if (!verticalEdges && !horizontalEdges) { 14851 // Step 3, draw the content 14852 if (!dirtyOpaque) onDraw(canvas); 14853 14854 // Step 4, draw the children 14855 dispatchDraw(canvas); 14856 14857 // Step 6, draw decorations (scrollbars) 14858 onDrawScrollBars(canvas); 14859 14860 if (mOverlay != null && !mOverlay.isEmpty()) { 14861 mOverlay.getOverlayView().dispatchDraw(canvas); 14862 } 14863 14864 // we're done... 14865 return; 14866 } 14867 14868 /* 14869 * Here we do the full fledged routine... 14870 * (this is an uncommon case where speed matters less, 14871 * this is why we repeat some of the tests that have been 14872 * done above) 14873 */ 14874 14875 boolean drawTop = false; 14876 boolean drawBottom = false; 14877 boolean drawLeft = false; 14878 boolean drawRight = false; 14879 14880 float topFadeStrength = 0.0f; 14881 float bottomFadeStrength = 0.0f; 14882 float leftFadeStrength = 0.0f; 14883 float rightFadeStrength = 0.0f; 14884 14885 // Step 2, save the canvas' layers 14886 int paddingLeft = mPaddingLeft; 14887 14888 final boolean offsetRequired = isPaddingOffsetRequired(); 14889 if (offsetRequired) { 14890 paddingLeft += getLeftPaddingOffset(); 14891 } 14892 14893 int left = mScrollX + paddingLeft; 14894 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 14895 int top = mScrollY + getFadeTop(offsetRequired); 14896 int bottom = top + getFadeHeight(offsetRequired); 14897 14898 if (offsetRequired) { 14899 right += getRightPaddingOffset(); 14900 bottom += getBottomPaddingOffset(); 14901 } 14902 14903 final ScrollabilityCache scrollabilityCache = mScrollCache; 14904 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 14905 int length = (int) fadeHeight; 14906 14907 // clip the fade length if top and bottom fades overlap 14908 // overlapping fades produce odd-looking artifacts 14909 if (verticalEdges && (top + length > bottom - length)) { 14910 length = (bottom - top) / 2; 14911 } 14912 14913 // also clip horizontal fades if necessary 14914 if (horizontalEdges && (left + length > right - length)) { 14915 length = (right - left) / 2; 14916 } 14917 14918 if (verticalEdges) { 14919 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 14920 drawTop = topFadeStrength * fadeHeight > 1.0f; 14921 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 14922 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 14923 } 14924 14925 if (horizontalEdges) { 14926 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 14927 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 14928 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 14929 drawRight = rightFadeStrength * fadeHeight > 1.0f; 14930 } 14931 14932 saveCount = canvas.getSaveCount(); 14933 14934 int solidColor = getSolidColor(); 14935 if (solidColor == 0) { 14936 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 14937 14938 if (drawTop) { 14939 canvas.saveLayer(left, top, right, top + length, null, flags); 14940 } 14941 14942 if (drawBottom) { 14943 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 14944 } 14945 14946 if (drawLeft) { 14947 canvas.saveLayer(left, top, left + length, bottom, null, flags); 14948 } 14949 14950 if (drawRight) { 14951 canvas.saveLayer(right - length, top, right, bottom, null, flags); 14952 } 14953 } else { 14954 scrollabilityCache.setFadeColor(solidColor); 14955 } 14956 14957 // Step 3, draw the content 14958 if (!dirtyOpaque) onDraw(canvas); 14959 14960 // Step 4, draw the children 14961 dispatchDraw(canvas); 14962 14963 // Step 5, draw the fade effect and restore layers 14964 final Paint p = scrollabilityCache.paint; 14965 final Matrix matrix = scrollabilityCache.matrix; 14966 final Shader fade = scrollabilityCache.shader; 14967 14968 if (drawTop) { 14969 matrix.setScale(1, fadeHeight * topFadeStrength); 14970 matrix.postTranslate(left, top); 14971 fade.setLocalMatrix(matrix); 14972 canvas.drawRect(left, top, right, top + length, p); 14973 } 14974 14975 if (drawBottom) { 14976 matrix.setScale(1, fadeHeight * bottomFadeStrength); 14977 matrix.postRotate(180); 14978 matrix.postTranslate(left, bottom); 14979 fade.setLocalMatrix(matrix); 14980 canvas.drawRect(left, bottom - length, right, bottom, p); 14981 } 14982 14983 if (drawLeft) { 14984 matrix.setScale(1, fadeHeight * leftFadeStrength); 14985 matrix.postRotate(-90); 14986 matrix.postTranslate(left, top); 14987 fade.setLocalMatrix(matrix); 14988 canvas.drawRect(left, top, left + length, bottom, p); 14989 } 14990 14991 if (drawRight) { 14992 matrix.setScale(1, fadeHeight * rightFadeStrength); 14993 matrix.postRotate(90); 14994 matrix.postTranslate(right, top); 14995 fade.setLocalMatrix(matrix); 14996 canvas.drawRect(right - length, top, right, bottom, p); 14997 } 14998 14999 canvas.restoreToCount(saveCount); 15000 15001 // Step 6, draw decorations (scrollbars) 15002 onDrawScrollBars(canvas); 15003 15004 if (mOverlay != null && !mOverlay.isEmpty()) { 15005 mOverlay.getOverlayView().dispatchDraw(canvas); 15006 } 15007 } 15008 15009 /** 15010 * Draws the background onto the specified canvas. 15011 * 15012 * @param canvas Canvas on which to draw the background 15013 */ 15014 private void drawBackground(Canvas canvas) { 15015 final Drawable background = mBackground; 15016 if (background == null) { 15017 return; 15018 } 15019 15020 if (mBackgroundSizeChanged) { 15021 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 15022 mBackgroundSizeChanged = false; 15023 queryOutlineFromBackgroundIfUndefined(); 15024 } 15025 15026 // Attempt to use a display list if requested. 15027 if (canvas.isHardwareAccelerated() && mAttachInfo != null 15028 && mAttachInfo.mHardwareRenderer != null) { 15029 mBackgroundDisplayList = getDrawableDisplayList(background, mBackgroundDisplayList); 15030 15031 final RenderNode displayList = mBackgroundDisplayList; 15032 if (displayList != null && displayList.isValid()) { 15033 setBackgroundDisplayListProperties(displayList); 15034 ((HardwareCanvas) canvas).drawDisplayList(displayList); 15035 return; 15036 } 15037 } 15038 15039 final int scrollX = mScrollX; 15040 final int scrollY = mScrollY; 15041 if ((scrollX | scrollY) == 0) { 15042 background.draw(canvas); 15043 } else { 15044 canvas.translate(scrollX, scrollY); 15045 background.draw(canvas); 15046 canvas.translate(-scrollX, -scrollY); 15047 } 15048 } 15049 15050 /** 15051 * Set up background drawable display list properties. 15052 * 15053 * @param displayList Valid display list for the background drawable 15054 */ 15055 private void setBackgroundDisplayListProperties(RenderNode displayList) { 15056 displayList.setTranslationX(mScrollX); 15057 displayList.setTranslationY(mScrollY); 15058 } 15059 15060 /** 15061 * Creates a new display list or updates the existing display list for the 15062 * specified Drawable. 15063 * 15064 * @param drawable Drawable for which to create a display list 15065 * @param displayList Existing display list, or {@code null} 15066 * @return A valid display list for the specified drawable 15067 */ 15068 private RenderNode getDrawableDisplayList(Drawable drawable, RenderNode displayList) { 15069 if (displayList == null) { 15070 displayList = RenderNode.create(drawable.getClass().getName()); 15071 } 15072 15073 final Rect bounds = drawable.getBounds(); 15074 final int width = bounds.width(); 15075 final int height = bounds.height(); 15076 final HardwareCanvas canvas = displayList.start(width, height); 15077 try { 15078 drawable.draw(canvas); 15079 } finally { 15080 displayList.end(canvas); 15081 } 15082 15083 // Set up drawable properties that are view-independent. 15084 displayList.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom); 15085 displayList.setProjectBackwards(drawable.isProjected()); 15086 displayList.setProjectionReceiver(true); 15087 displayList.setClipToBounds(false); 15088 return displayList; 15089 } 15090 15091 /** 15092 * Returns the overlay for this view, creating it if it does not yet exist. 15093 * Adding drawables to the overlay will cause them to be displayed whenever 15094 * the view itself is redrawn. Objects in the overlay should be actively 15095 * managed: remove them when they should not be displayed anymore. The 15096 * overlay will always have the same size as its host view. 15097 * 15098 * <p>Note: Overlays do not currently work correctly with {@link 15099 * SurfaceView} or {@link TextureView}; contents in overlays for these 15100 * types of views may not display correctly.</p> 15101 * 15102 * @return The ViewOverlay object for this view. 15103 * @see ViewOverlay 15104 */ 15105 public ViewOverlay getOverlay() { 15106 if (mOverlay == null) { 15107 mOverlay = new ViewOverlay(mContext, this); 15108 } 15109 return mOverlay; 15110 } 15111 15112 /** 15113 * Override this if your view is known to always be drawn on top of a solid color background, 15114 * and needs to draw fading edges. Returning a non-zero color enables the view system to 15115 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 15116 * should be set to 0xFF. 15117 * 15118 * @see #setVerticalFadingEdgeEnabled(boolean) 15119 * @see #setHorizontalFadingEdgeEnabled(boolean) 15120 * 15121 * @return The known solid color background for this view, or 0 if the color may vary 15122 */ 15123 @ViewDebug.ExportedProperty(category = "drawing") 15124 public int getSolidColor() { 15125 return 0; 15126 } 15127 15128 /** 15129 * Build a human readable string representation of the specified view flags. 15130 * 15131 * @param flags the view flags to convert to a string 15132 * @return a String representing the supplied flags 15133 */ 15134 private static String printFlags(int flags) { 15135 String output = ""; 15136 int numFlags = 0; 15137 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 15138 output += "TAKES_FOCUS"; 15139 numFlags++; 15140 } 15141 15142 switch (flags & VISIBILITY_MASK) { 15143 case INVISIBLE: 15144 if (numFlags > 0) { 15145 output += " "; 15146 } 15147 output += "INVISIBLE"; 15148 // USELESS HERE numFlags++; 15149 break; 15150 case GONE: 15151 if (numFlags > 0) { 15152 output += " "; 15153 } 15154 output += "GONE"; 15155 // USELESS HERE numFlags++; 15156 break; 15157 default: 15158 break; 15159 } 15160 return output; 15161 } 15162 15163 /** 15164 * Build a human readable string representation of the specified private 15165 * view flags. 15166 * 15167 * @param privateFlags the private view flags to convert to a string 15168 * @return a String representing the supplied flags 15169 */ 15170 private static String printPrivateFlags(int privateFlags) { 15171 String output = ""; 15172 int numFlags = 0; 15173 15174 if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) { 15175 output += "WANTS_FOCUS"; 15176 numFlags++; 15177 } 15178 15179 if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) { 15180 if (numFlags > 0) { 15181 output += " "; 15182 } 15183 output += "FOCUSED"; 15184 numFlags++; 15185 } 15186 15187 if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) { 15188 if (numFlags > 0) { 15189 output += " "; 15190 } 15191 output += "SELECTED"; 15192 numFlags++; 15193 } 15194 15195 if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) { 15196 if (numFlags > 0) { 15197 output += " "; 15198 } 15199 output += "IS_ROOT_NAMESPACE"; 15200 numFlags++; 15201 } 15202 15203 if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) { 15204 if (numFlags > 0) { 15205 output += " "; 15206 } 15207 output += "HAS_BOUNDS"; 15208 numFlags++; 15209 } 15210 15211 if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) { 15212 if (numFlags > 0) { 15213 output += " "; 15214 } 15215 output += "DRAWN"; 15216 // USELESS HERE numFlags++; 15217 } 15218 return output; 15219 } 15220 15221 /** 15222 * <p>Indicates whether or not this view's layout will be requested during 15223 * the next hierarchy layout pass.</p> 15224 * 15225 * @return true if the layout will be forced during next layout pass 15226 */ 15227 public boolean isLayoutRequested() { 15228 return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 15229 } 15230 15231 /** 15232 * Return true if o is a ViewGroup that is laying out using optical bounds. 15233 * @hide 15234 */ 15235 public static boolean isLayoutModeOptical(Object o) { 15236 return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical(); 15237 } 15238 15239 private boolean setOpticalFrame(int left, int top, int right, int bottom) { 15240 Insets parentInsets = mParent instanceof View ? 15241 ((View) mParent).getOpticalInsets() : Insets.NONE; 15242 Insets childInsets = getOpticalInsets(); 15243 return setFrame( 15244 left + parentInsets.left - childInsets.left, 15245 top + parentInsets.top - childInsets.top, 15246 right + parentInsets.left + childInsets.right, 15247 bottom + parentInsets.top + childInsets.bottom); 15248 } 15249 15250 /** 15251 * Assign a size and position to a view and all of its 15252 * descendants 15253 * 15254 * <p>This is the second phase of the layout mechanism. 15255 * (The first is measuring). In this phase, each parent calls 15256 * layout on all of its children to position them. 15257 * This is typically done using the child measurements 15258 * that were stored in the measure pass().</p> 15259 * 15260 * <p>Derived classes should not override this method. 15261 * Derived classes with children should override 15262 * onLayout. In that method, they should 15263 * call layout on each of their children.</p> 15264 * 15265 * @param l Left position, relative to parent 15266 * @param t Top position, relative to parent 15267 * @param r Right position, relative to parent 15268 * @param b Bottom position, relative to parent 15269 */ 15270 @SuppressWarnings({"unchecked"}) 15271 public void layout(int l, int t, int r, int b) { 15272 if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) { 15273 onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec); 15274 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 15275 } 15276 15277 int oldL = mLeft; 15278 int oldT = mTop; 15279 int oldB = mBottom; 15280 int oldR = mRight; 15281 15282 boolean changed = isLayoutModeOptical(mParent) ? 15283 setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b); 15284 15285 if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) { 15286 onLayout(changed, l, t, r, b); 15287 mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED; 15288 15289 ListenerInfo li = mListenerInfo; 15290 if (li != null && li.mOnLayoutChangeListeners != null) { 15291 ArrayList<OnLayoutChangeListener> listenersCopy = 15292 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 15293 int numListeners = listenersCopy.size(); 15294 for (int i = 0; i < numListeners; ++i) { 15295 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 15296 } 15297 } 15298 } 15299 15300 mPrivateFlags &= ~PFLAG_FORCE_LAYOUT; 15301 mPrivateFlags3 |= PFLAG3_IS_LAID_OUT; 15302 } 15303 15304 /** 15305 * Called from layout when this view should 15306 * assign a size and position to each of its children. 15307 * 15308 * Derived classes with children should override 15309 * this method and call layout on each of 15310 * their children. 15311 * @param changed This is a new size or position for this view 15312 * @param left Left position, relative to parent 15313 * @param top Top position, relative to parent 15314 * @param right Right position, relative to parent 15315 * @param bottom Bottom position, relative to parent 15316 */ 15317 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 15318 } 15319 15320 /** 15321 * Assign a size and position to this view. 15322 * 15323 * This is called from layout. 15324 * 15325 * @param left Left position, relative to parent 15326 * @param top Top position, relative to parent 15327 * @param right Right position, relative to parent 15328 * @param bottom Bottom position, relative to parent 15329 * @return true if the new size and position are different than the 15330 * previous ones 15331 * {@hide} 15332 */ 15333 protected boolean setFrame(int left, int top, int right, int bottom) { 15334 boolean changed = false; 15335 15336 if (DBG) { 15337 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 15338 + right + "," + bottom + ")"); 15339 } 15340 15341 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 15342 changed = true; 15343 15344 // Remember our drawn bit 15345 int drawn = mPrivateFlags & PFLAG_DRAWN; 15346 15347 int oldWidth = mRight - mLeft; 15348 int oldHeight = mBottom - mTop; 15349 int newWidth = right - left; 15350 int newHeight = bottom - top; 15351 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 15352 15353 // Invalidate our old position 15354 invalidate(sizeChanged); 15355 15356 mLeft = left; 15357 mTop = top; 15358 mRight = right; 15359 mBottom = bottom; 15360 mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 15361 15362 mPrivateFlags |= PFLAG_HAS_BOUNDS; 15363 15364 15365 if (sizeChanged) { 15366 sizeChange(newWidth, newHeight, oldWidth, oldHeight); 15367 } 15368 15369 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) { 15370 // If we are visible, force the DRAWN bit to on so that 15371 // this invalidate will go through (at least to our parent). 15372 // This is because someone may have invalidated this view 15373 // before this call to setFrame came in, thereby clearing 15374 // the DRAWN bit. 15375 mPrivateFlags |= PFLAG_DRAWN; 15376 invalidate(sizeChanged); 15377 // parent display list may need to be recreated based on a change in the bounds 15378 // of any child 15379 invalidateParentCaches(); 15380 } 15381 15382 // Reset drawn bit to original value (invalidate turns it off) 15383 mPrivateFlags |= drawn; 15384 15385 mBackgroundSizeChanged = true; 15386 15387 notifySubtreeAccessibilityStateChangedIfNeeded(); 15388 } 15389 return changed; 15390 } 15391 15392 private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) { 15393 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 15394 if (mOverlay != null) { 15395 mOverlay.getOverlayView().setRight(newWidth); 15396 mOverlay.getOverlayView().setBottom(newHeight); 15397 } 15398 } 15399 15400 /** 15401 * Finalize inflating a view from XML. This is called as the last phase 15402 * of inflation, after all child views have been added. 15403 * 15404 * <p>Even if the subclass overrides onFinishInflate, they should always be 15405 * sure to call the super method, so that we get called. 15406 */ 15407 protected void onFinishInflate() { 15408 } 15409 15410 /** 15411 * Returns the resources associated with this view. 15412 * 15413 * @return Resources object. 15414 */ 15415 public Resources getResources() { 15416 return mResources; 15417 } 15418 15419 /** 15420 * Invalidates the specified Drawable. 15421 * 15422 * @param drawable the drawable to invalidate 15423 */ 15424 @Override 15425 public void invalidateDrawable(@NonNull Drawable drawable) { 15426 if (verifyDrawable(drawable)) { 15427 final Rect dirty = drawable.getDirtyBounds(); 15428 final int scrollX = mScrollX; 15429 final int scrollY = mScrollY; 15430 15431 invalidate(dirty.left + scrollX, dirty.top + scrollY, 15432 dirty.right + scrollX, dirty.bottom + scrollY); 15433 15434 if (drawable == mBackground) { 15435 queryOutlineFromBackgroundIfUndefined(); 15436 } 15437 } 15438 } 15439 15440 /** 15441 * Schedules an action on a drawable to occur at a specified time. 15442 * 15443 * @param who the recipient of the action 15444 * @param what the action to run on the drawable 15445 * @param when the time at which the action must occur. Uses the 15446 * {@link SystemClock#uptimeMillis} timebase. 15447 */ 15448 @Override 15449 public void scheduleDrawable(Drawable who, Runnable what, long when) { 15450 if (verifyDrawable(who) && what != null) { 15451 final long delay = when - SystemClock.uptimeMillis(); 15452 if (mAttachInfo != null) { 15453 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 15454 Choreographer.CALLBACK_ANIMATION, what, who, 15455 Choreographer.subtractFrameDelay(delay)); 15456 } else { 15457 ViewRootImpl.getRunQueue().postDelayed(what, delay); 15458 } 15459 } 15460 } 15461 15462 /** 15463 * Cancels a scheduled action on a drawable. 15464 * 15465 * @param who the recipient of the action 15466 * @param what the action to cancel 15467 */ 15468 @Override 15469 public void unscheduleDrawable(Drawable who, Runnable what) { 15470 if (verifyDrawable(who) && what != null) { 15471 if (mAttachInfo != null) { 15472 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 15473 Choreographer.CALLBACK_ANIMATION, what, who); 15474 } 15475 ViewRootImpl.getRunQueue().removeCallbacks(what); 15476 } 15477 } 15478 15479 /** 15480 * Unschedule any events associated with the given Drawable. This can be 15481 * used when selecting a new Drawable into a view, so that the previous 15482 * one is completely unscheduled. 15483 * 15484 * @param who The Drawable to unschedule. 15485 * 15486 * @see #drawableStateChanged 15487 */ 15488 public void unscheduleDrawable(Drawable who) { 15489 if (mAttachInfo != null && who != null) { 15490 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 15491 Choreographer.CALLBACK_ANIMATION, null, who); 15492 } 15493 } 15494 15495 /** 15496 * Resolve the Drawables depending on the layout direction. This is implicitly supposing 15497 * that the View directionality can and will be resolved before its Drawables. 15498 * 15499 * Will call {@link View#onResolveDrawables} when resolution is done. 15500 * 15501 * @hide 15502 */ 15503 protected void resolveDrawables() { 15504 // Drawables resolution may need to happen before resolving the layout direction (which is 15505 // done only during the measure() call). 15506 // If the layout direction is not resolved yet, we cannot resolve the Drawables except in 15507 // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT. 15508 // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or 15509 // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout 15510 // direction to be resolved as its resolved value will be the same as its raw value. 15511 if (!isLayoutDirectionResolved() && 15512 getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) { 15513 return; 15514 } 15515 15516 final int layoutDirection = isLayoutDirectionResolved() ? 15517 getLayoutDirection() : getRawLayoutDirection(); 15518 15519 if (mBackground != null) { 15520 mBackground.setLayoutDirection(layoutDirection); 15521 } 15522 mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED; 15523 onResolveDrawables(layoutDirection); 15524 } 15525 15526 /** 15527 * Called when layout direction has been resolved. 15528 * 15529 * The default implementation does nothing. 15530 * 15531 * @param layoutDirection The resolved layout direction. 15532 * 15533 * @see #LAYOUT_DIRECTION_LTR 15534 * @see #LAYOUT_DIRECTION_RTL 15535 * 15536 * @hide 15537 */ 15538 public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) { 15539 } 15540 15541 /** 15542 * @hide 15543 */ 15544 protected void resetResolvedDrawables() { 15545 mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED; 15546 } 15547 15548 private boolean isDrawablesResolved() { 15549 return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED; 15550 } 15551 15552 /** 15553 * If your view subclass is displaying its own Drawable objects, it should 15554 * override this function and return true for any Drawable it is 15555 * displaying. This allows animations for those drawables to be 15556 * scheduled. 15557 * 15558 * <p>Be sure to call through to the super class when overriding this 15559 * function. 15560 * 15561 * @param who The Drawable to verify. Return true if it is one you are 15562 * displaying, else return the result of calling through to the 15563 * super class. 15564 * 15565 * @return boolean If true than the Drawable is being displayed in the 15566 * view; else false and it is not allowed to animate. 15567 * 15568 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 15569 * @see #drawableStateChanged() 15570 */ 15571 protected boolean verifyDrawable(Drawable who) { 15572 return who == mBackground; 15573 } 15574 15575 /** 15576 * This function is called whenever the state of the view changes in such 15577 * a way that it impacts the state of drawables being shown. 15578 * <p> 15579 * If the View has a StateListAnimator, it will also be called to run necessary state 15580 * change animations. 15581 * <p> 15582 * Be sure to call through to the superclass when overriding this function. 15583 * 15584 * @see Drawable#setState(int[]) 15585 */ 15586 protected void drawableStateChanged() { 15587 final Drawable d = mBackground; 15588 if (d != null && d.isStateful()) { 15589 d.setState(getDrawableState()); 15590 } 15591 15592 if (mStateListAnimator != null) { 15593 mStateListAnimator.setState(getDrawableState()); 15594 } 15595 } 15596 15597 /** 15598 * Call this to force a view to update its drawable state. This will cause 15599 * drawableStateChanged to be called on this view. Views that are interested 15600 * in the new state should call getDrawableState. 15601 * 15602 * @see #drawableStateChanged 15603 * @see #getDrawableState 15604 */ 15605 public void refreshDrawableState() { 15606 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 15607 drawableStateChanged(); 15608 15609 ViewParent parent = mParent; 15610 if (parent != null) { 15611 parent.childDrawableStateChanged(this); 15612 } 15613 } 15614 15615 /** 15616 * Return an array of resource IDs of the drawable states representing the 15617 * current state of the view. 15618 * 15619 * @return The current drawable state 15620 * 15621 * @see Drawable#setState(int[]) 15622 * @see #drawableStateChanged() 15623 * @see #onCreateDrawableState(int) 15624 */ 15625 public final int[] getDrawableState() { 15626 if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) { 15627 return mDrawableState; 15628 } else { 15629 mDrawableState = onCreateDrawableState(0); 15630 mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY; 15631 return mDrawableState; 15632 } 15633 } 15634 15635 /** 15636 * Generate the new {@link android.graphics.drawable.Drawable} state for 15637 * this view. This is called by the view 15638 * system when the cached Drawable state is determined to be invalid. To 15639 * retrieve the current state, you should use {@link #getDrawableState}. 15640 * 15641 * @param extraSpace if non-zero, this is the number of extra entries you 15642 * would like in the returned array in which you can place your own 15643 * states. 15644 * 15645 * @return Returns an array holding the current {@link Drawable} state of 15646 * the view. 15647 * 15648 * @see #mergeDrawableStates(int[], int[]) 15649 */ 15650 protected int[] onCreateDrawableState(int extraSpace) { 15651 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 15652 mParent instanceof View) { 15653 return ((View) mParent).onCreateDrawableState(extraSpace); 15654 } 15655 15656 int[] drawableState; 15657 15658 int privateFlags = mPrivateFlags; 15659 15660 int viewStateIndex = 0; 15661 if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED; 15662 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED; 15663 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED; 15664 if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED; 15665 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED; 15666 if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED; 15667 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 15668 HardwareRenderer.isAvailable()) { 15669 // This is set if HW acceleration is requested, even if the current 15670 // process doesn't allow it. This is just to allow app preview 15671 // windows to better match their app. 15672 viewStateIndex |= VIEW_STATE_ACCELERATED; 15673 } 15674 if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED; 15675 15676 final int privateFlags2 = mPrivateFlags2; 15677 if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT; 15678 if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED; 15679 15680 drawableState = VIEW_STATE_SETS[viewStateIndex]; 15681 15682 //noinspection ConstantIfStatement 15683 if (false) { 15684 Log.i("View", "drawableStateIndex=" + viewStateIndex); 15685 Log.i("View", toString() 15686 + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0) 15687 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 15688 + " fo=" + hasFocus() 15689 + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0) 15690 + " wf=" + hasWindowFocus() 15691 + ": " + Arrays.toString(drawableState)); 15692 } 15693 15694 if (extraSpace == 0) { 15695 return drawableState; 15696 } 15697 15698 final int[] fullState; 15699 if (drawableState != null) { 15700 fullState = new int[drawableState.length + extraSpace]; 15701 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 15702 } else { 15703 fullState = new int[extraSpace]; 15704 } 15705 15706 return fullState; 15707 } 15708 15709 /** 15710 * Merge your own state values in <var>additionalState</var> into the base 15711 * state values <var>baseState</var> that were returned by 15712 * {@link #onCreateDrawableState(int)}. 15713 * 15714 * @param baseState The base state values returned by 15715 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 15716 * own additional state values. 15717 * 15718 * @param additionalState The additional state values you would like 15719 * added to <var>baseState</var>; this array is not modified. 15720 * 15721 * @return As a convenience, the <var>baseState</var> array you originally 15722 * passed into the function is returned. 15723 * 15724 * @see #onCreateDrawableState(int) 15725 */ 15726 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 15727 final int N = baseState.length; 15728 int i = N - 1; 15729 while (i >= 0 && baseState[i] == 0) { 15730 i--; 15731 } 15732 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 15733 return baseState; 15734 } 15735 15736 /** 15737 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 15738 * on all Drawable objects associated with this view. 15739 * <p> 15740 * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator 15741 * attached to this view. 15742 */ 15743 public void jumpDrawablesToCurrentState() { 15744 if (mBackground != null) { 15745 mBackground.jumpToCurrentState(); 15746 } 15747 if (mStateListAnimator != null) { 15748 mStateListAnimator.jumpToCurrentState(); 15749 } 15750 } 15751 15752 /** 15753 * Sets the background color for this view. 15754 * @param color the color of the background 15755 */ 15756 @RemotableViewMethod 15757 public void setBackgroundColor(int color) { 15758 if (mBackground instanceof ColorDrawable) { 15759 ((ColorDrawable) mBackground.mutate()).setColor(color); 15760 computeOpaqueFlags(); 15761 mBackgroundResource = 0; 15762 } else { 15763 setBackground(new ColorDrawable(color)); 15764 } 15765 } 15766 15767 /** 15768 * Set the background to a given resource. The resource should refer to 15769 * a Drawable object or 0 to remove the background. 15770 * @param resid The identifier of the resource. 15771 * 15772 * @attr ref android.R.styleable#View_background 15773 */ 15774 @RemotableViewMethod 15775 public void setBackgroundResource(int resid) { 15776 if (resid != 0 && resid == mBackgroundResource) { 15777 return; 15778 } 15779 15780 Drawable d= null; 15781 if (resid != 0) { 15782 d = mContext.getDrawable(resid); 15783 } 15784 setBackground(d); 15785 15786 mBackgroundResource = resid; 15787 } 15788 15789 /** 15790 * Set the background to a given Drawable, or remove the background. If the 15791 * background has padding, this View's padding is set to the background's 15792 * padding. However, when a background is removed, this View's padding isn't 15793 * touched. If setting the padding is desired, please use 15794 * {@link #setPadding(int, int, int, int)}. 15795 * 15796 * @param background The Drawable to use as the background, or null to remove the 15797 * background 15798 */ 15799 public void setBackground(Drawable background) { 15800 //noinspection deprecation 15801 setBackgroundDrawable(background); 15802 } 15803 15804 /** 15805 * @deprecated use {@link #setBackground(Drawable)} instead 15806 */ 15807 @Deprecated 15808 public void setBackgroundDrawable(Drawable background) { 15809 computeOpaqueFlags(); 15810 15811 if (background == mBackground) { 15812 return; 15813 } 15814 15815 boolean requestLayout = false; 15816 15817 mBackgroundResource = 0; 15818 15819 /* 15820 * Regardless of whether we're setting a new background or not, we want 15821 * to clear the previous drawable. 15822 */ 15823 if (mBackground != null) { 15824 mBackground.setCallback(null); 15825 unscheduleDrawable(mBackground); 15826 } 15827 15828 if (background != null) { 15829 Rect padding = sThreadLocal.get(); 15830 if (padding == null) { 15831 padding = new Rect(); 15832 sThreadLocal.set(padding); 15833 } 15834 resetResolvedDrawables(); 15835 background.setLayoutDirection(getLayoutDirection()); 15836 if (background.getPadding(padding)) { 15837 resetResolvedPadding(); 15838 switch (background.getLayoutDirection()) { 15839 case LAYOUT_DIRECTION_RTL: 15840 mUserPaddingLeftInitial = padding.right; 15841 mUserPaddingRightInitial = padding.left; 15842 internalSetPadding(padding.right, padding.top, padding.left, padding.bottom); 15843 break; 15844 case LAYOUT_DIRECTION_LTR: 15845 default: 15846 mUserPaddingLeftInitial = padding.left; 15847 mUserPaddingRightInitial = padding.right; 15848 internalSetPadding(padding.left, padding.top, padding.right, padding.bottom); 15849 } 15850 mLeftPaddingDefined = false; 15851 mRightPaddingDefined = false; 15852 } 15853 15854 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 15855 // if it has a different minimum size, we should layout again 15856 if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() || 15857 mBackground.getMinimumWidth() != background.getMinimumWidth()) { 15858 requestLayout = true; 15859 } 15860 15861 background.setCallback(this); 15862 if (background.isStateful()) { 15863 background.setState(getDrawableState()); 15864 } 15865 background.setVisible(getVisibility() == VISIBLE, false); 15866 mBackground = background; 15867 15868 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 15869 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 15870 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 15871 requestLayout = true; 15872 } 15873 } else { 15874 /* Remove the background */ 15875 mBackground = null; 15876 15877 if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) { 15878 /* 15879 * This view ONLY drew the background before and we're removing 15880 * the background, so now it won't draw anything 15881 * (hence we SKIP_DRAW) 15882 */ 15883 mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND; 15884 mPrivateFlags |= PFLAG_SKIP_DRAW; 15885 } 15886 15887 /* 15888 * When the background is set, we try to apply its padding to this 15889 * View. When the background is removed, we don't touch this View's 15890 * padding. This is noted in the Javadocs. Hence, we don't need to 15891 * requestLayout(), the invalidate() below is sufficient. 15892 */ 15893 15894 // The old background's minimum size could have affected this 15895 // View's layout, so let's requestLayout 15896 requestLayout = true; 15897 } 15898 15899 computeOpaqueFlags(); 15900 15901 if (requestLayout) { 15902 requestLayout(); 15903 } 15904 15905 mBackgroundSizeChanged = true; 15906 invalidate(true); 15907 } 15908 15909 /** 15910 * Gets the background drawable 15911 * 15912 * @return The drawable used as the background for this view, if any. 15913 * 15914 * @see #setBackground(Drawable) 15915 * 15916 * @attr ref android.R.styleable#View_background 15917 */ 15918 public Drawable getBackground() { 15919 return mBackground; 15920 } 15921 15922 /** 15923 * Sets the padding. The view may add on the space required to display 15924 * the scrollbars, depending on the style and visibility of the scrollbars. 15925 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 15926 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 15927 * from the values set in this call. 15928 * 15929 * @attr ref android.R.styleable#View_padding 15930 * @attr ref android.R.styleable#View_paddingBottom 15931 * @attr ref android.R.styleable#View_paddingLeft 15932 * @attr ref android.R.styleable#View_paddingRight 15933 * @attr ref android.R.styleable#View_paddingTop 15934 * @param left the left padding in pixels 15935 * @param top the top padding in pixels 15936 * @param right the right padding in pixels 15937 * @param bottom the bottom padding in pixels 15938 */ 15939 public void setPadding(int left, int top, int right, int bottom) { 15940 resetResolvedPadding(); 15941 15942 mUserPaddingStart = UNDEFINED_PADDING; 15943 mUserPaddingEnd = UNDEFINED_PADDING; 15944 15945 mUserPaddingLeftInitial = left; 15946 mUserPaddingRightInitial = right; 15947 15948 mLeftPaddingDefined = true; 15949 mRightPaddingDefined = true; 15950 15951 internalSetPadding(left, top, right, bottom); 15952 } 15953 15954 /** 15955 * @hide 15956 */ 15957 protected void internalSetPadding(int left, int top, int right, int bottom) { 15958 mUserPaddingLeft = left; 15959 mUserPaddingRight = right; 15960 mUserPaddingBottom = bottom; 15961 15962 final int viewFlags = mViewFlags; 15963 boolean changed = false; 15964 15965 // Common case is there are no scroll bars. 15966 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 15967 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 15968 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 15969 ? 0 : getVerticalScrollbarWidth(); 15970 switch (mVerticalScrollbarPosition) { 15971 case SCROLLBAR_POSITION_DEFAULT: 15972 if (isLayoutRtl()) { 15973 left += offset; 15974 } else { 15975 right += offset; 15976 } 15977 break; 15978 case SCROLLBAR_POSITION_RIGHT: 15979 right += offset; 15980 break; 15981 case SCROLLBAR_POSITION_LEFT: 15982 left += offset; 15983 break; 15984 } 15985 } 15986 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 15987 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 15988 ? 0 : getHorizontalScrollbarHeight(); 15989 } 15990 } 15991 15992 if (mPaddingLeft != left) { 15993 changed = true; 15994 mPaddingLeft = left; 15995 } 15996 if (mPaddingTop != top) { 15997 changed = true; 15998 mPaddingTop = top; 15999 } 16000 if (mPaddingRight != right) { 16001 changed = true; 16002 mPaddingRight = right; 16003 } 16004 if (mPaddingBottom != bottom) { 16005 changed = true; 16006 mPaddingBottom = bottom; 16007 } 16008 16009 if (changed) { 16010 requestLayout(); 16011 } 16012 } 16013 16014 /** 16015 * Sets the relative padding. The view may add on the space required to display 16016 * the scrollbars, depending on the style and visibility of the scrollbars. 16017 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 16018 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 16019 * from the values set in this call. 16020 * 16021 * @attr ref android.R.styleable#View_padding 16022 * @attr ref android.R.styleable#View_paddingBottom 16023 * @attr ref android.R.styleable#View_paddingStart 16024 * @attr ref android.R.styleable#View_paddingEnd 16025 * @attr ref android.R.styleable#View_paddingTop 16026 * @param start the start padding in pixels 16027 * @param top the top padding in pixels 16028 * @param end the end padding in pixels 16029 * @param bottom the bottom padding in pixels 16030 */ 16031 public void setPaddingRelative(int start, int top, int end, int bottom) { 16032 resetResolvedPadding(); 16033 16034 mUserPaddingStart = start; 16035 mUserPaddingEnd = end; 16036 mLeftPaddingDefined = true; 16037 mRightPaddingDefined = true; 16038 16039 switch(getLayoutDirection()) { 16040 case LAYOUT_DIRECTION_RTL: 16041 mUserPaddingLeftInitial = end; 16042 mUserPaddingRightInitial = start; 16043 internalSetPadding(end, top, start, bottom); 16044 break; 16045 case LAYOUT_DIRECTION_LTR: 16046 default: 16047 mUserPaddingLeftInitial = start; 16048 mUserPaddingRightInitial = end; 16049 internalSetPadding(start, top, end, bottom); 16050 } 16051 } 16052 16053 /** 16054 * Returns the top padding of this view. 16055 * 16056 * @return the top padding in pixels 16057 */ 16058 public int getPaddingTop() { 16059 return mPaddingTop; 16060 } 16061 16062 /** 16063 * Returns the bottom padding of this view. If there are inset and enabled 16064 * scrollbars, this value may include the space required to display the 16065 * scrollbars as well. 16066 * 16067 * @return the bottom padding in pixels 16068 */ 16069 public int getPaddingBottom() { 16070 return mPaddingBottom; 16071 } 16072 16073 /** 16074 * Returns the left padding of this view. If there are inset and enabled 16075 * scrollbars, this value may include the space required to display the 16076 * scrollbars as well. 16077 * 16078 * @return the left padding in pixels 16079 */ 16080 public int getPaddingLeft() { 16081 if (!isPaddingResolved()) { 16082 resolvePadding(); 16083 } 16084 return mPaddingLeft; 16085 } 16086 16087 /** 16088 * Returns the start padding of this view depending on its resolved layout direction. 16089 * If there are inset and enabled scrollbars, this value may include the space 16090 * required to display the scrollbars as well. 16091 * 16092 * @return the start padding in pixels 16093 */ 16094 public int getPaddingStart() { 16095 if (!isPaddingResolved()) { 16096 resolvePadding(); 16097 } 16098 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 16099 mPaddingRight : mPaddingLeft; 16100 } 16101 16102 /** 16103 * Returns the right padding of this view. If there are inset and enabled 16104 * scrollbars, this value may include the space required to display the 16105 * scrollbars as well. 16106 * 16107 * @return the right padding in pixels 16108 */ 16109 public int getPaddingRight() { 16110 if (!isPaddingResolved()) { 16111 resolvePadding(); 16112 } 16113 return mPaddingRight; 16114 } 16115 16116 /** 16117 * Returns the end padding of this view depending on its resolved layout direction. 16118 * If there are inset and enabled scrollbars, this value may include the space 16119 * required to display the scrollbars as well. 16120 * 16121 * @return the end padding in pixels 16122 */ 16123 public int getPaddingEnd() { 16124 if (!isPaddingResolved()) { 16125 resolvePadding(); 16126 } 16127 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 16128 mPaddingLeft : mPaddingRight; 16129 } 16130 16131 /** 16132 * Return if the padding as been set thru relative values 16133 * {@link #setPaddingRelative(int, int, int, int)} or thru 16134 * @attr ref android.R.styleable#View_paddingStart or 16135 * @attr ref android.R.styleable#View_paddingEnd 16136 * 16137 * @return true if the padding is relative or false if it is not. 16138 */ 16139 public boolean isPaddingRelative() { 16140 return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING); 16141 } 16142 16143 Insets computeOpticalInsets() { 16144 return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets(); 16145 } 16146 16147 /** 16148 * @hide 16149 */ 16150 public void resetPaddingToInitialValues() { 16151 if (isRtlCompatibilityMode()) { 16152 mPaddingLeft = mUserPaddingLeftInitial; 16153 mPaddingRight = mUserPaddingRightInitial; 16154 return; 16155 } 16156 if (isLayoutRtl()) { 16157 mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial; 16158 mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial; 16159 } else { 16160 mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial; 16161 mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial; 16162 } 16163 } 16164 16165 /** 16166 * @hide 16167 */ 16168 public Insets getOpticalInsets() { 16169 if (mLayoutInsets == null) { 16170 mLayoutInsets = computeOpticalInsets(); 16171 } 16172 return mLayoutInsets; 16173 } 16174 16175 /** 16176 * Changes the selection state of this view. A view can be selected or not. 16177 * Note that selection is not the same as focus. Views are typically 16178 * selected in the context of an AdapterView like ListView or GridView; 16179 * the selected view is the view that is highlighted. 16180 * 16181 * @param selected true if the view must be selected, false otherwise 16182 */ 16183 public void setSelected(boolean selected) { 16184 //noinspection DoubleNegation 16185 if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) { 16186 mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0); 16187 if (!selected) resetPressedState(); 16188 invalidate(true); 16189 refreshDrawableState(); 16190 dispatchSetSelected(selected); 16191 notifyViewAccessibilityStateChangedIfNeeded( 16192 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 16193 } 16194 } 16195 16196 /** 16197 * Dispatch setSelected to all of this View's children. 16198 * 16199 * @see #setSelected(boolean) 16200 * 16201 * @param selected The new selected state 16202 */ 16203 protected void dispatchSetSelected(boolean selected) { 16204 } 16205 16206 /** 16207 * Indicates the selection state of this view. 16208 * 16209 * @return true if the view is selected, false otherwise 16210 */ 16211 @ViewDebug.ExportedProperty 16212 public boolean isSelected() { 16213 return (mPrivateFlags & PFLAG_SELECTED) != 0; 16214 } 16215 16216 /** 16217 * Changes the activated state of this view. A view can be activated or not. 16218 * Note that activation is not the same as selection. Selection is 16219 * a transient property, representing the view (hierarchy) the user is 16220 * currently interacting with. Activation is a longer-term state that the 16221 * user can move views in and out of. For example, in a list view with 16222 * single or multiple selection enabled, the views in the current selection 16223 * set are activated. (Um, yeah, we are deeply sorry about the terminology 16224 * here.) The activated state is propagated down to children of the view it 16225 * is set on. 16226 * 16227 * @param activated true if the view must be activated, false otherwise 16228 */ 16229 public void setActivated(boolean activated) { 16230 //noinspection DoubleNegation 16231 if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) { 16232 mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0); 16233 invalidate(true); 16234 refreshDrawableState(); 16235 dispatchSetActivated(activated); 16236 } 16237 } 16238 16239 /** 16240 * Dispatch setActivated to all of this View's children. 16241 * 16242 * @see #setActivated(boolean) 16243 * 16244 * @param activated The new activated state 16245 */ 16246 protected void dispatchSetActivated(boolean activated) { 16247 } 16248 16249 /** 16250 * Indicates the activation state of this view. 16251 * 16252 * @return true if the view is activated, false otherwise 16253 */ 16254 @ViewDebug.ExportedProperty 16255 public boolean isActivated() { 16256 return (mPrivateFlags & PFLAG_ACTIVATED) != 0; 16257 } 16258 16259 /** 16260 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 16261 * observer can be used to get notifications when global events, like 16262 * layout, happen. 16263 * 16264 * The returned ViewTreeObserver observer is not guaranteed to remain 16265 * valid for the lifetime of this View. If the caller of this method keeps 16266 * a long-lived reference to ViewTreeObserver, it should always check for 16267 * the return value of {@link ViewTreeObserver#isAlive()}. 16268 * 16269 * @return The ViewTreeObserver for this view's hierarchy. 16270 */ 16271 public ViewTreeObserver getViewTreeObserver() { 16272 if (mAttachInfo != null) { 16273 return mAttachInfo.mTreeObserver; 16274 } 16275 if (mFloatingTreeObserver == null) { 16276 mFloatingTreeObserver = new ViewTreeObserver(); 16277 } 16278 return mFloatingTreeObserver; 16279 } 16280 16281 /** 16282 * <p>Finds the topmost view in the current view hierarchy.</p> 16283 * 16284 * @return the topmost view containing this view 16285 */ 16286 public View getRootView() { 16287 if (mAttachInfo != null) { 16288 final View v = mAttachInfo.mRootView; 16289 if (v != null) { 16290 return v; 16291 } 16292 } 16293 16294 View parent = this; 16295 16296 while (parent.mParent != null && parent.mParent instanceof View) { 16297 parent = (View) parent.mParent; 16298 } 16299 16300 return parent; 16301 } 16302 16303 /** 16304 * Transforms a motion event from view-local coordinates to on-screen 16305 * coordinates. 16306 * 16307 * @param ev the view-local motion event 16308 * @return false if the transformation could not be applied 16309 * @hide 16310 */ 16311 public boolean toGlobalMotionEvent(MotionEvent ev) { 16312 final AttachInfo info = mAttachInfo; 16313 if (info == null) { 16314 return false; 16315 } 16316 16317 final Matrix m = info.mTmpMatrix; 16318 m.set(Matrix.IDENTITY_MATRIX); 16319 transformMatrixToGlobal(m); 16320 ev.transform(m); 16321 return true; 16322 } 16323 16324 /** 16325 * Transforms a motion event from on-screen coordinates to view-local 16326 * coordinates. 16327 * 16328 * @param ev the on-screen motion event 16329 * @return false if the transformation could not be applied 16330 * @hide 16331 */ 16332 public boolean toLocalMotionEvent(MotionEvent ev) { 16333 final AttachInfo info = mAttachInfo; 16334 if (info == null) { 16335 return false; 16336 } 16337 16338 final Matrix m = info.mTmpMatrix; 16339 m.set(Matrix.IDENTITY_MATRIX); 16340 transformMatrixToLocal(m); 16341 ev.transform(m); 16342 return true; 16343 } 16344 16345 /** 16346 * Modifies the input matrix such that it maps view-local coordinates to 16347 * on-screen coordinates. 16348 * 16349 * @param m input matrix to modify 16350 */ 16351 void transformMatrixToGlobal(Matrix m) { 16352 final ViewParent parent = mParent; 16353 if (parent instanceof View) { 16354 final View vp = (View) parent; 16355 vp.transformMatrixToGlobal(m); 16356 m.postTranslate(-vp.mScrollX, -vp.mScrollY); 16357 } else if (parent instanceof ViewRootImpl) { 16358 final ViewRootImpl vr = (ViewRootImpl) parent; 16359 vr.transformMatrixToGlobal(m); 16360 m.postTranslate(0, -vr.mCurScrollY); 16361 } 16362 16363 m.postTranslate(mLeft, mTop); 16364 16365 if (!hasIdentityMatrix()) { 16366 m.postConcat(getMatrix()); 16367 } 16368 } 16369 16370 /** 16371 * Modifies the input matrix such that it maps on-screen coordinates to 16372 * view-local coordinates. 16373 * 16374 * @param m input matrix to modify 16375 */ 16376 void transformMatrixToLocal(Matrix m) { 16377 final ViewParent parent = mParent; 16378 if (parent instanceof View) { 16379 final View vp = (View) parent; 16380 vp.transformMatrixToLocal(m); 16381 m.preTranslate(vp.mScrollX, vp.mScrollY); 16382 } else if (parent instanceof ViewRootImpl) { 16383 final ViewRootImpl vr = (ViewRootImpl) parent; 16384 vr.transformMatrixToLocal(m); 16385 m.preTranslate(0, vr.mCurScrollY); 16386 } 16387 16388 m.preTranslate(-mLeft, -mTop); 16389 16390 if (!hasIdentityMatrix()) { 16391 m.preConcat(getInverseMatrix()); 16392 } 16393 } 16394 16395 /** 16396 * <p>Computes the coordinates of this view on the screen. The argument 16397 * must be an array of two integers. After the method returns, the array 16398 * contains the x and y location in that order.</p> 16399 * 16400 * @param location an array of two integers in which to hold the coordinates 16401 */ 16402 public void getLocationOnScreen(int[] location) { 16403 getLocationInWindow(location); 16404 16405 final AttachInfo info = mAttachInfo; 16406 if (info != null) { 16407 location[0] += info.mWindowLeft; 16408 location[1] += info.mWindowTop; 16409 } 16410 } 16411 16412 /** 16413 * <p>Computes the coordinates of this view in its window. The argument 16414 * must be an array of two integers. After the method returns, the array 16415 * contains the x and y location in that order.</p> 16416 * 16417 * @param location an array of two integers in which to hold the coordinates 16418 */ 16419 public void getLocationInWindow(int[] location) { 16420 if (location == null || location.length < 2) { 16421 throw new IllegalArgumentException("location must be an array of two integers"); 16422 } 16423 16424 if (mAttachInfo == null) { 16425 // When the view is not attached to a window, this method does not make sense 16426 location[0] = location[1] = 0; 16427 return; 16428 } 16429 16430 float[] position = mAttachInfo.mTmpTransformLocation; 16431 position[0] = position[1] = 0.0f; 16432 16433 if (!hasIdentityMatrix()) { 16434 getMatrix().mapPoints(position); 16435 } 16436 16437 position[0] += mLeft; 16438 position[1] += mTop; 16439 16440 ViewParent viewParent = mParent; 16441 while (viewParent instanceof View) { 16442 final View view = (View) viewParent; 16443 16444 position[0] -= view.mScrollX; 16445 position[1] -= view.mScrollY; 16446 16447 if (!view.hasIdentityMatrix()) { 16448 view.getMatrix().mapPoints(position); 16449 } 16450 16451 position[0] += view.mLeft; 16452 position[1] += view.mTop; 16453 16454 viewParent = view.mParent; 16455 } 16456 16457 if (viewParent instanceof ViewRootImpl) { 16458 // *cough* 16459 final ViewRootImpl vr = (ViewRootImpl) viewParent; 16460 position[1] -= vr.mCurScrollY; 16461 } 16462 16463 location[0] = (int) (position[0] + 0.5f); 16464 location[1] = (int) (position[1] + 0.5f); 16465 } 16466 16467 /** 16468 * {@hide} 16469 * @param id the id of the view to be found 16470 * @return the view of the specified id, null if cannot be found 16471 */ 16472 protected View findViewTraversal(int id) { 16473 if (id == mID) { 16474 return this; 16475 } 16476 return null; 16477 } 16478 16479 /** 16480 * {@hide} 16481 * @param tag the tag of the view to be found 16482 * @return the view of specified tag, null if cannot be found 16483 */ 16484 protected View findViewWithTagTraversal(Object tag) { 16485 if (tag != null && tag.equals(mTag)) { 16486 return this; 16487 } 16488 return null; 16489 } 16490 16491 /** 16492 * {@hide} 16493 * @param predicate The predicate to evaluate. 16494 * @param childToSkip If not null, ignores this child during the recursive traversal. 16495 * @return The first view that matches the predicate or null. 16496 */ 16497 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 16498 if (predicate.apply(this)) { 16499 return this; 16500 } 16501 return null; 16502 } 16503 16504 /** 16505 * Look for a child view with the given id. If this view has the given 16506 * id, return this view. 16507 * 16508 * @param id The id to search for. 16509 * @return The view that has the given id in the hierarchy or null 16510 */ 16511 public final View findViewById(int id) { 16512 if (id < 0) { 16513 return null; 16514 } 16515 return findViewTraversal(id); 16516 } 16517 16518 /** 16519 * Finds a view by its unuque and stable accessibility id. 16520 * 16521 * @param accessibilityId The searched accessibility id. 16522 * @return The found view. 16523 */ 16524 final View findViewByAccessibilityId(int accessibilityId) { 16525 if (accessibilityId < 0) { 16526 return null; 16527 } 16528 return findViewByAccessibilityIdTraversal(accessibilityId); 16529 } 16530 16531 /** 16532 * Performs the traversal to find a view by its unuque and stable accessibility id. 16533 * 16534 * <strong>Note:</strong>This method does not stop at the root namespace 16535 * boundary since the user can touch the screen at an arbitrary location 16536 * potentially crossing the root namespace bounday which will send an 16537 * accessibility event to accessibility services and they should be able 16538 * to obtain the event source. Also accessibility ids are guaranteed to be 16539 * unique in the window. 16540 * 16541 * @param accessibilityId The accessibility id. 16542 * @return The found view. 16543 * 16544 * @hide 16545 */ 16546 public View findViewByAccessibilityIdTraversal(int accessibilityId) { 16547 if (getAccessibilityViewId() == accessibilityId) { 16548 return this; 16549 } 16550 return null; 16551 } 16552 16553 /** 16554 * Look for a child view with the given tag. If this view has the given 16555 * tag, return this view. 16556 * 16557 * @param tag The tag to search for, using "tag.equals(getTag())". 16558 * @return The View that has the given tag in the hierarchy or null 16559 */ 16560 public final View findViewWithTag(Object tag) { 16561 if (tag == null) { 16562 return null; 16563 } 16564 return findViewWithTagTraversal(tag); 16565 } 16566 16567 /** 16568 * {@hide} 16569 * Look for a child view that matches the specified predicate. 16570 * If this view matches the predicate, return this view. 16571 * 16572 * @param predicate The predicate to evaluate. 16573 * @return The first view that matches the predicate or null. 16574 */ 16575 public final View findViewByPredicate(Predicate<View> predicate) { 16576 return findViewByPredicateTraversal(predicate, null); 16577 } 16578 16579 /** 16580 * {@hide} 16581 * Look for a child view that matches the specified predicate, 16582 * starting with the specified view and its descendents and then 16583 * recusively searching the ancestors and siblings of that view 16584 * until this view is reached. 16585 * 16586 * This method is useful in cases where the predicate does not match 16587 * a single unique view (perhaps multiple views use the same id) 16588 * and we are trying to find the view that is "closest" in scope to the 16589 * starting view. 16590 * 16591 * @param start The view to start from. 16592 * @param predicate The predicate to evaluate. 16593 * @return The first view that matches the predicate or null. 16594 */ 16595 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 16596 View childToSkip = null; 16597 for (;;) { 16598 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 16599 if (view != null || start == this) { 16600 return view; 16601 } 16602 16603 ViewParent parent = start.getParent(); 16604 if (parent == null || !(parent instanceof View)) { 16605 return null; 16606 } 16607 16608 childToSkip = start; 16609 start = (View) parent; 16610 } 16611 } 16612 16613 /** 16614 * Sets the identifier for this view. The identifier does not have to be 16615 * unique in this view's hierarchy. The identifier should be a positive 16616 * number. 16617 * 16618 * @see #NO_ID 16619 * @see #getId() 16620 * @see #findViewById(int) 16621 * 16622 * @param id a number used to identify the view 16623 * 16624 * @attr ref android.R.styleable#View_id 16625 */ 16626 public void setId(int id) { 16627 mID = id; 16628 if (mID == View.NO_ID && mLabelForId != View.NO_ID) { 16629 mID = generateViewId(); 16630 } 16631 } 16632 16633 /** 16634 * {@hide} 16635 * 16636 * @param isRoot true if the view belongs to the root namespace, false 16637 * otherwise 16638 */ 16639 public void setIsRootNamespace(boolean isRoot) { 16640 if (isRoot) { 16641 mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE; 16642 } else { 16643 mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE; 16644 } 16645 } 16646 16647 /** 16648 * {@hide} 16649 * 16650 * @return true if the view belongs to the root namespace, false otherwise 16651 */ 16652 public boolean isRootNamespace() { 16653 return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0; 16654 } 16655 16656 /** 16657 * Returns this view's identifier. 16658 * 16659 * @return a positive integer used to identify the view or {@link #NO_ID} 16660 * if the view has no ID 16661 * 16662 * @see #setId(int) 16663 * @see #findViewById(int) 16664 * @attr ref android.R.styleable#View_id 16665 */ 16666 @ViewDebug.CapturedViewProperty 16667 public int getId() { 16668 return mID; 16669 } 16670 16671 /** 16672 * Returns this view's tag. 16673 * 16674 * @return the Object stored in this view as a tag, or {@code null} if not 16675 * set 16676 * 16677 * @see #setTag(Object) 16678 * @see #getTag(int) 16679 */ 16680 @ViewDebug.ExportedProperty 16681 public Object getTag() { 16682 return mTag; 16683 } 16684 16685 /** 16686 * Sets the tag associated with this view. A tag can be used to mark 16687 * a view in its hierarchy and does not have to be unique within the 16688 * hierarchy. Tags can also be used to store data within a view without 16689 * resorting to another data structure. 16690 * 16691 * @param tag an Object to tag the view with 16692 * 16693 * @see #getTag() 16694 * @see #setTag(int, Object) 16695 */ 16696 public void setTag(final Object tag) { 16697 mTag = tag; 16698 } 16699 16700 /** 16701 * Returns the tag associated with this view and the specified key. 16702 * 16703 * @param key The key identifying the tag 16704 * 16705 * @return the Object stored in this view as a tag, or {@code null} if not 16706 * set 16707 * 16708 * @see #setTag(int, Object) 16709 * @see #getTag() 16710 */ 16711 public Object getTag(int key) { 16712 if (mKeyedTags != null) return mKeyedTags.get(key); 16713 return null; 16714 } 16715 16716 /** 16717 * Sets a tag associated with this view and a key. A tag can be used 16718 * to mark a view in its hierarchy and does not have to be unique within 16719 * the hierarchy. Tags can also be used to store data within a view 16720 * without resorting to another data structure. 16721 * 16722 * The specified key should be an id declared in the resources of the 16723 * application to ensure it is unique (see the <a 16724 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 16725 * Keys identified as belonging to 16726 * the Android framework or not associated with any package will cause 16727 * an {@link IllegalArgumentException} to be thrown. 16728 * 16729 * @param key The key identifying the tag 16730 * @param tag An Object to tag the view with 16731 * 16732 * @throws IllegalArgumentException If they specified key is not valid 16733 * 16734 * @see #setTag(Object) 16735 * @see #getTag(int) 16736 */ 16737 public void setTag(int key, final Object tag) { 16738 // If the package id is 0x00 or 0x01, it's either an undefined package 16739 // or a framework id 16740 if ((key >>> 24) < 2) { 16741 throw new IllegalArgumentException("The key must be an application-specific " 16742 + "resource id."); 16743 } 16744 16745 setKeyedTag(key, tag); 16746 } 16747 16748 /** 16749 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 16750 * framework id. 16751 * 16752 * @hide 16753 */ 16754 public void setTagInternal(int key, Object tag) { 16755 if ((key >>> 24) != 0x1) { 16756 throw new IllegalArgumentException("The key must be a framework-specific " 16757 + "resource id."); 16758 } 16759 16760 setKeyedTag(key, tag); 16761 } 16762 16763 private void setKeyedTag(int key, Object tag) { 16764 if (mKeyedTags == null) { 16765 mKeyedTags = new SparseArray<Object>(2); 16766 } 16767 16768 mKeyedTags.put(key, tag); 16769 } 16770 16771 /** 16772 * Prints information about this view in the log output, with the tag 16773 * {@link #VIEW_LOG_TAG}. 16774 * 16775 * @hide 16776 */ 16777 public void debug() { 16778 debug(0); 16779 } 16780 16781 /** 16782 * Prints information about this view in the log output, with the tag 16783 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 16784 * indentation defined by the <code>depth</code>. 16785 * 16786 * @param depth the indentation level 16787 * 16788 * @hide 16789 */ 16790 protected void debug(int depth) { 16791 String output = debugIndent(depth - 1); 16792 16793 output += "+ " + this; 16794 int id = getId(); 16795 if (id != -1) { 16796 output += " (id=" + id + ")"; 16797 } 16798 Object tag = getTag(); 16799 if (tag != null) { 16800 output += " (tag=" + tag + ")"; 16801 } 16802 Log.d(VIEW_LOG_TAG, output); 16803 16804 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 16805 output = debugIndent(depth) + " FOCUSED"; 16806 Log.d(VIEW_LOG_TAG, output); 16807 } 16808 16809 output = debugIndent(depth); 16810 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 16811 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 16812 + "} "; 16813 Log.d(VIEW_LOG_TAG, output); 16814 16815 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 16816 || mPaddingBottom != 0) { 16817 output = debugIndent(depth); 16818 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 16819 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 16820 Log.d(VIEW_LOG_TAG, output); 16821 } 16822 16823 output = debugIndent(depth); 16824 output += "mMeasureWidth=" + mMeasuredWidth + 16825 " mMeasureHeight=" + mMeasuredHeight; 16826 Log.d(VIEW_LOG_TAG, output); 16827 16828 output = debugIndent(depth); 16829 if (mLayoutParams == null) { 16830 output += "BAD! no layout params"; 16831 } else { 16832 output = mLayoutParams.debug(output); 16833 } 16834 Log.d(VIEW_LOG_TAG, output); 16835 16836 output = debugIndent(depth); 16837 output += "flags={"; 16838 output += View.printFlags(mViewFlags); 16839 output += "}"; 16840 Log.d(VIEW_LOG_TAG, output); 16841 16842 output = debugIndent(depth); 16843 output += "privateFlags={"; 16844 output += View.printPrivateFlags(mPrivateFlags); 16845 output += "}"; 16846 Log.d(VIEW_LOG_TAG, output); 16847 } 16848 16849 /** 16850 * Creates a string of whitespaces used for indentation. 16851 * 16852 * @param depth the indentation level 16853 * @return a String containing (depth * 2 + 3) * 2 white spaces 16854 * 16855 * @hide 16856 */ 16857 protected static String debugIndent(int depth) { 16858 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 16859 for (int i = 0; i < (depth * 2) + 3; i++) { 16860 spaces.append(' ').append(' '); 16861 } 16862 return spaces.toString(); 16863 } 16864 16865 /** 16866 * <p>Return the offset of the widget's text baseline from the widget's top 16867 * boundary. If this widget does not support baseline alignment, this 16868 * method returns -1. </p> 16869 * 16870 * @return the offset of the baseline within the widget's bounds or -1 16871 * if baseline alignment is not supported 16872 */ 16873 @ViewDebug.ExportedProperty(category = "layout") 16874 public int getBaseline() { 16875 return -1; 16876 } 16877 16878 /** 16879 * Returns whether the view hierarchy is currently undergoing a layout pass. This 16880 * information is useful to avoid situations such as calling {@link #requestLayout()} during 16881 * a layout pass. 16882 * 16883 * @return whether the view hierarchy is currently undergoing a layout pass 16884 */ 16885 public boolean isInLayout() { 16886 ViewRootImpl viewRoot = getViewRootImpl(); 16887 return (viewRoot != null && viewRoot.isInLayout()); 16888 } 16889 16890 /** 16891 * Call this when something has changed which has invalidated the 16892 * layout of this view. This will schedule a layout pass of the view 16893 * tree. This should not be called while the view hierarchy is currently in a layout 16894 * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the 16895 * end of the current layout pass (and then layout will run again) or after the current 16896 * frame is drawn and the next layout occurs. 16897 * 16898 * <p>Subclasses which override this method should call the superclass method to 16899 * handle possible request-during-layout errors correctly.</p> 16900 */ 16901 public void requestLayout() { 16902 if (mMeasureCache != null) mMeasureCache.clear(); 16903 16904 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) { 16905 // Only trigger request-during-layout logic if this is the view requesting it, 16906 // not the views in its parent hierarchy 16907 ViewRootImpl viewRoot = getViewRootImpl(); 16908 if (viewRoot != null && viewRoot.isInLayout()) { 16909 if (!viewRoot.requestLayoutDuringLayout(this)) { 16910 return; 16911 } 16912 } 16913 mAttachInfo.mViewRequestingLayout = this; 16914 } 16915 16916 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 16917 mPrivateFlags |= PFLAG_INVALIDATED; 16918 16919 if (mParent != null && !mParent.isLayoutRequested()) { 16920 mParent.requestLayout(); 16921 } 16922 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) { 16923 mAttachInfo.mViewRequestingLayout = null; 16924 } 16925 } 16926 16927 /** 16928 * Forces this view to be laid out during the next layout pass. 16929 * This method does not call requestLayout() or forceLayout() 16930 * on the parent. 16931 */ 16932 public void forceLayout() { 16933 if (mMeasureCache != null) mMeasureCache.clear(); 16934 16935 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 16936 mPrivateFlags |= PFLAG_INVALIDATED; 16937 } 16938 16939 /** 16940 * <p> 16941 * This is called to find out how big a view should be. The parent 16942 * supplies constraint information in the width and height parameters. 16943 * </p> 16944 * 16945 * <p> 16946 * The actual measurement work of a view is performed in 16947 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 16948 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 16949 * </p> 16950 * 16951 * 16952 * @param widthMeasureSpec Horizontal space requirements as imposed by the 16953 * parent 16954 * @param heightMeasureSpec Vertical space requirements as imposed by the 16955 * parent 16956 * 16957 * @see #onMeasure(int, int) 16958 */ 16959 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 16960 boolean optical = isLayoutModeOptical(this); 16961 if (optical != isLayoutModeOptical(mParent)) { 16962 Insets insets = getOpticalInsets(); 16963 int oWidth = insets.left + insets.right; 16964 int oHeight = insets.top + insets.bottom; 16965 widthMeasureSpec = MeasureSpec.adjust(widthMeasureSpec, optical ? -oWidth : oWidth); 16966 heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight); 16967 } 16968 16969 // Suppress sign extension for the low bytes 16970 long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL; 16971 if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2); 16972 16973 if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT || 16974 widthMeasureSpec != mOldWidthMeasureSpec || 16975 heightMeasureSpec != mOldHeightMeasureSpec) { 16976 16977 // first clears the measured dimension flag 16978 mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET; 16979 16980 resolveRtlPropertiesIfNeeded(); 16981 16982 int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 : 16983 mMeasureCache.indexOfKey(key); 16984 if (cacheIndex < 0 || sIgnoreMeasureCache) { 16985 // measure ourselves, this should set the measured dimension flag back 16986 onMeasure(widthMeasureSpec, heightMeasureSpec); 16987 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 16988 } else { 16989 long value = mMeasureCache.valueAt(cacheIndex); 16990 // Casting a long to int drops the high 32 bits, no mask needed 16991 setMeasuredDimensionRaw((int) (value >> 32), (int) value); 16992 mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 16993 } 16994 16995 // flag not set, setMeasuredDimension() was not invoked, we raise 16996 // an exception to warn the developer 16997 if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) { 16998 throw new IllegalStateException("onMeasure() did not set the" 16999 + " measured dimension by calling" 17000 + " setMeasuredDimension()"); 17001 } 17002 17003 mPrivateFlags |= PFLAG_LAYOUT_REQUIRED; 17004 } 17005 17006 mOldWidthMeasureSpec = widthMeasureSpec; 17007 mOldHeightMeasureSpec = heightMeasureSpec; 17008 17009 mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 | 17010 (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension 17011 } 17012 17013 /** 17014 * <p> 17015 * Measure the view and its content to determine the measured width and the 17016 * measured height. This method is invoked by {@link #measure(int, int)} and 17017 * should be overriden by subclasses to provide accurate and efficient 17018 * measurement of their contents. 17019 * </p> 17020 * 17021 * <p> 17022 * <strong>CONTRACT:</strong> When overriding this method, you 17023 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 17024 * measured width and height of this view. Failure to do so will trigger an 17025 * <code>IllegalStateException</code>, thrown by 17026 * {@link #measure(int, int)}. Calling the superclass' 17027 * {@link #onMeasure(int, int)} is a valid use. 17028 * </p> 17029 * 17030 * <p> 17031 * The base class implementation of measure defaults to the background size, 17032 * unless a larger size is allowed by the MeasureSpec. Subclasses should 17033 * override {@link #onMeasure(int, int)} to provide better measurements of 17034 * their content. 17035 * </p> 17036 * 17037 * <p> 17038 * If this method is overridden, it is the subclass's responsibility to make 17039 * sure the measured height and width are at least the view's minimum height 17040 * and width ({@link #getSuggestedMinimumHeight()} and 17041 * {@link #getSuggestedMinimumWidth()}). 17042 * </p> 17043 * 17044 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 17045 * The requirements are encoded with 17046 * {@link android.view.View.MeasureSpec}. 17047 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 17048 * The requirements are encoded with 17049 * {@link android.view.View.MeasureSpec}. 17050 * 17051 * @see #getMeasuredWidth() 17052 * @see #getMeasuredHeight() 17053 * @see #setMeasuredDimension(int, int) 17054 * @see #getSuggestedMinimumHeight() 17055 * @see #getSuggestedMinimumWidth() 17056 * @see android.view.View.MeasureSpec#getMode(int) 17057 * @see android.view.View.MeasureSpec#getSize(int) 17058 */ 17059 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 17060 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 17061 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 17062 } 17063 17064 /** 17065 * <p>This method must be called by {@link #onMeasure(int, int)} to store the 17066 * measured width and measured height. Failing to do so will trigger an 17067 * exception at measurement time.</p> 17068 * 17069 * @param measuredWidth The measured width of this view. May be a complex 17070 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17071 * {@link #MEASURED_STATE_TOO_SMALL}. 17072 * @param measuredHeight The measured height of this view. May be a complex 17073 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17074 * {@link #MEASURED_STATE_TOO_SMALL}. 17075 */ 17076 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 17077 boolean optical = isLayoutModeOptical(this); 17078 if (optical != isLayoutModeOptical(mParent)) { 17079 Insets insets = getOpticalInsets(); 17080 int opticalWidth = insets.left + insets.right; 17081 int opticalHeight = insets.top + insets.bottom; 17082 17083 measuredWidth += optical ? opticalWidth : -opticalWidth; 17084 measuredHeight += optical ? opticalHeight : -opticalHeight; 17085 } 17086 setMeasuredDimensionRaw(measuredWidth, measuredHeight); 17087 } 17088 17089 /** 17090 * Sets the measured dimension without extra processing for things like optical bounds. 17091 * Useful for reapplying consistent values that have already been cooked with adjustments 17092 * for optical bounds, etc. such as those from the measurement cache. 17093 * 17094 * @param measuredWidth The measured width of this view. May be a complex 17095 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17096 * {@link #MEASURED_STATE_TOO_SMALL}. 17097 * @param measuredHeight The measured height of this view. May be a complex 17098 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17099 * {@link #MEASURED_STATE_TOO_SMALL}. 17100 */ 17101 private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) { 17102 mMeasuredWidth = measuredWidth; 17103 mMeasuredHeight = measuredHeight; 17104 17105 mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET; 17106 } 17107 17108 /** 17109 * Merge two states as returned by {@link #getMeasuredState()}. 17110 * @param curState The current state as returned from a view or the result 17111 * of combining multiple views. 17112 * @param newState The new view state to combine. 17113 * @return Returns a new integer reflecting the combination of the two 17114 * states. 17115 */ 17116 public static int combineMeasuredStates(int curState, int newState) { 17117 return curState | newState; 17118 } 17119 17120 /** 17121 * Version of {@link #resolveSizeAndState(int, int, int)} 17122 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 17123 */ 17124 public static int resolveSize(int size, int measureSpec) { 17125 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 17126 } 17127 17128 /** 17129 * Utility to reconcile a desired size and state, with constraints imposed 17130 * by a MeasureSpec. Will take the desired size, unless a different size 17131 * is imposed by the constraints. The returned value is a compound integer, 17132 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 17133 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting 17134 * size is smaller than the size the view wants to be. 17135 * 17136 * @param size How big the view wants to be 17137 * @param measureSpec Constraints imposed by the parent 17138 * @return Size information bit mask as defined by 17139 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 17140 */ 17141 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 17142 int result = size; 17143 int specMode = MeasureSpec.getMode(measureSpec); 17144 int specSize = MeasureSpec.getSize(measureSpec); 17145 switch (specMode) { 17146 case MeasureSpec.UNSPECIFIED: 17147 result = size; 17148 break; 17149 case MeasureSpec.AT_MOST: 17150 if (specSize < size) { 17151 result = specSize | MEASURED_STATE_TOO_SMALL; 17152 } else { 17153 result = size; 17154 } 17155 break; 17156 case MeasureSpec.EXACTLY: 17157 result = specSize; 17158 break; 17159 } 17160 return result | (childMeasuredState&MEASURED_STATE_MASK); 17161 } 17162 17163 /** 17164 * Utility to return a default size. Uses the supplied size if the 17165 * MeasureSpec imposed no constraints. Will get larger if allowed 17166 * by the MeasureSpec. 17167 * 17168 * @param size Default size for this view 17169 * @param measureSpec Constraints imposed by the parent 17170 * @return The size this view should be. 17171 */ 17172 public static int getDefaultSize(int size, int measureSpec) { 17173 int result = size; 17174 int specMode = MeasureSpec.getMode(measureSpec); 17175 int specSize = MeasureSpec.getSize(measureSpec); 17176 17177 switch (specMode) { 17178 case MeasureSpec.UNSPECIFIED: 17179 result = size; 17180 break; 17181 case MeasureSpec.AT_MOST: 17182 case MeasureSpec.EXACTLY: 17183 result = specSize; 17184 break; 17185 } 17186 return result; 17187 } 17188 17189 /** 17190 * Returns the suggested minimum height that the view should use. This 17191 * returns the maximum of the view's minimum height 17192 * and the background's minimum height 17193 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 17194 * <p> 17195 * When being used in {@link #onMeasure(int, int)}, the caller should still 17196 * ensure the returned height is within the requirements of the parent. 17197 * 17198 * @return The suggested minimum height of the view. 17199 */ 17200 protected int getSuggestedMinimumHeight() { 17201 return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight()); 17202 17203 } 17204 17205 /** 17206 * Returns the suggested minimum width that the view should use. This 17207 * returns the maximum of the view's minimum width) 17208 * and the background's minimum width 17209 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 17210 * <p> 17211 * When being used in {@link #onMeasure(int, int)}, the caller should still 17212 * ensure the returned width is within the requirements of the parent. 17213 * 17214 * @return The suggested minimum width of the view. 17215 */ 17216 protected int getSuggestedMinimumWidth() { 17217 return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); 17218 } 17219 17220 /** 17221 * Returns the minimum height of the view. 17222 * 17223 * @return the minimum height the view will try to be. 17224 * 17225 * @see #setMinimumHeight(int) 17226 * 17227 * @attr ref android.R.styleable#View_minHeight 17228 */ 17229 public int getMinimumHeight() { 17230 return mMinHeight; 17231 } 17232 17233 /** 17234 * Sets the minimum height of the view. It is not guaranteed the view will 17235 * be able to achieve this minimum height (for example, if its parent layout 17236 * constrains it with less available height). 17237 * 17238 * @param minHeight The minimum height the view will try to be. 17239 * 17240 * @see #getMinimumHeight() 17241 * 17242 * @attr ref android.R.styleable#View_minHeight 17243 */ 17244 public void setMinimumHeight(int minHeight) { 17245 mMinHeight = minHeight; 17246 requestLayout(); 17247 } 17248 17249 /** 17250 * Returns the minimum width of the view. 17251 * 17252 * @return the minimum width the view will try to be. 17253 * 17254 * @see #setMinimumWidth(int) 17255 * 17256 * @attr ref android.R.styleable#View_minWidth 17257 */ 17258 public int getMinimumWidth() { 17259 return mMinWidth; 17260 } 17261 17262 /** 17263 * Sets the minimum width of the view. It is not guaranteed the view will 17264 * be able to achieve this minimum width (for example, if its parent layout 17265 * constrains it with less available width). 17266 * 17267 * @param minWidth The minimum width the view will try to be. 17268 * 17269 * @see #getMinimumWidth() 17270 * 17271 * @attr ref android.R.styleable#View_minWidth 17272 */ 17273 public void setMinimumWidth(int minWidth) { 17274 mMinWidth = minWidth; 17275 requestLayout(); 17276 17277 } 17278 17279 /** 17280 * Get the animation currently associated with this view. 17281 * 17282 * @return The animation that is currently playing or 17283 * scheduled to play for this view. 17284 */ 17285 public Animation getAnimation() { 17286 return mCurrentAnimation; 17287 } 17288 17289 /** 17290 * Start the specified animation now. 17291 * 17292 * @param animation the animation to start now 17293 */ 17294 public void startAnimation(Animation animation) { 17295 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 17296 setAnimation(animation); 17297 invalidateParentCaches(); 17298 invalidate(true); 17299 } 17300 17301 /** 17302 * Cancels any animations for this view. 17303 */ 17304 public void clearAnimation() { 17305 if (mCurrentAnimation != null) { 17306 mCurrentAnimation.detach(); 17307 } 17308 mCurrentAnimation = null; 17309 invalidateParentIfNeeded(); 17310 } 17311 17312 /** 17313 * Sets the next animation to play for this view. 17314 * If you want the animation to play immediately, use 17315 * {@link #startAnimation(android.view.animation.Animation)} instead. 17316 * This method provides allows fine-grained 17317 * control over the start time and invalidation, but you 17318 * must make sure that 1) the animation has a start time set, and 17319 * 2) the view's parent (which controls animations on its children) 17320 * will be invalidated when the animation is supposed to 17321 * start. 17322 * 17323 * @param animation The next animation, or null. 17324 */ 17325 public void setAnimation(Animation animation) { 17326 mCurrentAnimation = animation; 17327 17328 if (animation != null) { 17329 // If the screen is off assume the animation start time is now instead of 17330 // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time 17331 // would cause the animation to start when the screen turns back on 17332 if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF 17333 && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) { 17334 animation.setStartTime(AnimationUtils.currentAnimationTimeMillis()); 17335 } 17336 animation.reset(); 17337 } 17338 } 17339 17340 /** 17341 * Invoked by a parent ViewGroup to notify the start of the animation 17342 * currently associated with this view. If you override this method, 17343 * always call super.onAnimationStart(); 17344 * 17345 * @see #setAnimation(android.view.animation.Animation) 17346 * @see #getAnimation() 17347 */ 17348 protected void onAnimationStart() { 17349 mPrivateFlags |= PFLAG_ANIMATION_STARTED; 17350 } 17351 17352 /** 17353 * Invoked by a parent ViewGroup to notify the end of the animation 17354 * currently associated with this view. If you override this method, 17355 * always call super.onAnimationEnd(); 17356 * 17357 * @see #setAnimation(android.view.animation.Animation) 17358 * @see #getAnimation() 17359 */ 17360 protected void onAnimationEnd() { 17361 mPrivateFlags &= ~PFLAG_ANIMATION_STARTED; 17362 } 17363 17364 /** 17365 * Invoked if there is a Transform that involves alpha. Subclass that can 17366 * draw themselves with the specified alpha should return true, and then 17367 * respect that alpha when their onDraw() is called. If this returns false 17368 * then the view may be redirected to draw into an offscreen buffer to 17369 * fulfill the request, which will look fine, but may be slower than if the 17370 * subclass handles it internally. The default implementation returns false. 17371 * 17372 * @param alpha The alpha (0..255) to apply to the view's drawing 17373 * @return true if the view can draw with the specified alpha. 17374 */ 17375 protected boolean onSetAlpha(int alpha) { 17376 return false; 17377 } 17378 17379 /** 17380 * This is used by the RootView to perform an optimization when 17381 * the view hierarchy contains one or several SurfaceView. 17382 * SurfaceView is always considered transparent, but its children are not, 17383 * therefore all View objects remove themselves from the global transparent 17384 * region (passed as a parameter to this function). 17385 * 17386 * @param region The transparent region for this ViewAncestor (window). 17387 * 17388 * @return Returns true if the effective visibility of the view at this 17389 * point is opaque, regardless of the transparent region; returns false 17390 * if it is possible for underlying windows to be seen behind the view. 17391 * 17392 * {@hide} 17393 */ 17394 public boolean gatherTransparentRegion(Region region) { 17395 final AttachInfo attachInfo = mAttachInfo; 17396 if (region != null && attachInfo != null) { 17397 final int pflags = mPrivateFlags; 17398 if ((pflags & PFLAG_SKIP_DRAW) == 0) { 17399 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 17400 // remove it from the transparent region. 17401 final int[] location = attachInfo.mTransparentLocation; 17402 getLocationInWindow(location); 17403 region.op(location[0], location[1], location[0] + mRight - mLeft, 17404 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 17405 } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) { 17406 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 17407 // exists, so we remove the background drawable's non-transparent 17408 // parts from this transparent region. 17409 applyDrawableToTransparentRegion(mBackground, region); 17410 } 17411 } 17412 return true; 17413 } 17414 17415 /** 17416 * Play a sound effect for this view. 17417 * 17418 * <p>The framework will play sound effects for some built in actions, such as 17419 * clicking, but you may wish to play these effects in your widget, 17420 * for instance, for internal navigation. 17421 * 17422 * <p>The sound effect will only be played if sound effects are enabled by the user, and 17423 * {@link #isSoundEffectsEnabled()} is true. 17424 * 17425 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 17426 */ 17427 public void playSoundEffect(int soundConstant) { 17428 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 17429 return; 17430 } 17431 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 17432 } 17433 17434 /** 17435 * BZZZTT!!1! 17436 * 17437 * <p>Provide haptic feedback to the user for this view. 17438 * 17439 * <p>The framework will provide haptic feedback for some built in actions, 17440 * such as long presses, but you may wish to provide feedback for your 17441 * own widget. 17442 * 17443 * <p>The feedback will only be performed if 17444 * {@link #isHapticFeedbackEnabled()} is true. 17445 * 17446 * @param feedbackConstant One of the constants defined in 17447 * {@link HapticFeedbackConstants} 17448 */ 17449 public boolean performHapticFeedback(int feedbackConstant) { 17450 return performHapticFeedback(feedbackConstant, 0); 17451 } 17452 17453 /** 17454 * BZZZTT!!1! 17455 * 17456 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 17457 * 17458 * @param feedbackConstant One of the constants defined in 17459 * {@link HapticFeedbackConstants} 17460 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 17461 */ 17462 public boolean performHapticFeedback(int feedbackConstant, int flags) { 17463 if (mAttachInfo == null) { 17464 return false; 17465 } 17466 //noinspection SimplifiableIfStatement 17467 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 17468 && !isHapticFeedbackEnabled()) { 17469 return false; 17470 } 17471 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 17472 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 17473 } 17474 17475 /** 17476 * Request that the visibility of the status bar or other screen/window 17477 * decorations be changed. 17478 * 17479 * <p>This method is used to put the over device UI into temporary modes 17480 * where the user's attention is focused more on the application content, 17481 * by dimming or hiding surrounding system affordances. This is typically 17482 * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY 17483 * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content 17484 * to be placed behind the action bar (and with these flags other system 17485 * affordances) so that smooth transitions between hiding and showing them 17486 * can be done. 17487 * 17488 * <p>Two representative examples of the use of system UI visibility is 17489 * implementing a content browsing application (like a magazine reader) 17490 * and a video playing application. 17491 * 17492 * <p>The first code shows a typical implementation of a View in a content 17493 * browsing application. In this implementation, the application goes 17494 * into a content-oriented mode by hiding the status bar and action bar, 17495 * and putting the navigation elements into lights out mode. The user can 17496 * then interact with content while in this mode. Such an application should 17497 * provide an easy way for the user to toggle out of the mode (such as to 17498 * check information in the status bar or access notifications). In the 17499 * implementation here, this is done simply by tapping on the content. 17500 * 17501 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java 17502 * content} 17503 * 17504 * <p>This second code sample shows a typical implementation of a View 17505 * in a video playing application. In this situation, while the video is 17506 * playing the application would like to go into a complete full-screen mode, 17507 * to use as much of the display as possible for the video. When in this state 17508 * the user can not interact with the application; the system intercepts 17509 * touching on the screen to pop the UI out of full screen mode. See 17510 * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code. 17511 * 17512 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java 17513 * content} 17514 * 17515 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 17516 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 17517 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 17518 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 17519 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 17520 */ 17521 public void setSystemUiVisibility(int visibility) { 17522 if (visibility != mSystemUiVisibility) { 17523 mSystemUiVisibility = visibility; 17524 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 17525 mParent.recomputeViewAttributes(this); 17526 } 17527 } 17528 } 17529 17530 /** 17531 * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested. 17532 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 17533 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 17534 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 17535 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 17536 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 17537 */ 17538 public int getSystemUiVisibility() { 17539 return mSystemUiVisibility; 17540 } 17541 17542 /** 17543 * Returns the current system UI visibility that is currently set for 17544 * the entire window. This is the combination of the 17545 * {@link #setSystemUiVisibility(int)} values supplied by all of the 17546 * views in the window. 17547 */ 17548 public int getWindowSystemUiVisibility() { 17549 return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0; 17550 } 17551 17552 /** 17553 * Override to find out when the window's requested system UI visibility 17554 * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}. 17555 * This is different from the callbacks received through 17556 * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)} 17557 * in that this is only telling you about the local request of the window, 17558 * not the actual values applied by the system. 17559 */ 17560 public void onWindowSystemUiVisibilityChanged(int visible) { 17561 } 17562 17563 /** 17564 * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down 17565 * the view hierarchy. 17566 */ 17567 public void dispatchWindowSystemUiVisiblityChanged(int visible) { 17568 onWindowSystemUiVisibilityChanged(visible); 17569 } 17570 17571 /** 17572 * Set a listener to receive callbacks when the visibility of the system bar changes. 17573 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 17574 */ 17575 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 17576 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 17577 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 17578 mParent.recomputeViewAttributes(this); 17579 } 17580 } 17581 17582 /** 17583 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 17584 * the view hierarchy. 17585 */ 17586 public void dispatchSystemUiVisibilityChanged(int visibility) { 17587 ListenerInfo li = mListenerInfo; 17588 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 17589 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 17590 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 17591 } 17592 } 17593 17594 boolean updateLocalSystemUiVisibility(int localValue, int localChanges) { 17595 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 17596 if (val != mSystemUiVisibility) { 17597 setSystemUiVisibility(val); 17598 return true; 17599 } 17600 return false; 17601 } 17602 17603 /** @hide */ 17604 public void setDisabledSystemUiVisibility(int flags) { 17605 if (mAttachInfo != null) { 17606 if (mAttachInfo.mDisabledSystemUiVisibility != flags) { 17607 mAttachInfo.mDisabledSystemUiVisibility = flags; 17608 if (mParent != null) { 17609 mParent.recomputeViewAttributes(this); 17610 } 17611 } 17612 } 17613 } 17614 17615 /** 17616 * Creates an image that the system displays during the drag and drop 17617 * operation. This is called a "drag shadow". The default implementation 17618 * for a DragShadowBuilder based on a View returns an image that has exactly the same 17619 * appearance as the given View. The default also positions the center of the drag shadow 17620 * directly under the touch point. If no View is provided (the constructor with no parameters 17621 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 17622 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the 17623 * default is an invisible drag shadow. 17624 * <p> 17625 * You are not required to use the View you provide to the constructor as the basis of the 17626 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 17627 * anything you want as the drag shadow. 17628 * </p> 17629 * <p> 17630 * You pass a DragShadowBuilder object to the system when you start the drag. The system 17631 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 17632 * size and position of the drag shadow. It uses this data to construct a 17633 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 17634 * so that your application can draw the shadow image in the Canvas. 17635 * </p> 17636 * 17637 * <div class="special reference"> 17638 * <h3>Developer Guides</h3> 17639 * <p>For a guide to implementing drag and drop features, read the 17640 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 17641 * </div> 17642 */ 17643 public static class DragShadowBuilder { 17644 private final WeakReference<View> mView; 17645 17646 /** 17647 * Constructs a shadow image builder based on a View. By default, the resulting drag 17648 * shadow will have the same appearance and dimensions as the View, with the touch point 17649 * over the center of the View. 17650 * @param view A View. Any View in scope can be used. 17651 */ 17652 public DragShadowBuilder(View view) { 17653 mView = new WeakReference<View>(view); 17654 } 17655 17656 /** 17657 * Construct a shadow builder object with no associated View. This 17658 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 17659 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 17660 * to supply the drag shadow's dimensions and appearance without 17661 * reference to any View object. If they are not overridden, then the result is an 17662 * invisible drag shadow. 17663 */ 17664 public DragShadowBuilder() { 17665 mView = new WeakReference<View>(null); 17666 } 17667 17668 /** 17669 * Returns the View object that had been passed to the 17670 * {@link #View.DragShadowBuilder(View)} 17671 * constructor. If that View parameter was {@code null} or if the 17672 * {@link #View.DragShadowBuilder()} 17673 * constructor was used to instantiate the builder object, this method will return 17674 * null. 17675 * 17676 * @return The View object associate with this builder object. 17677 */ 17678 @SuppressWarnings({"JavadocReference"}) 17679 final public View getView() { 17680 return mView.get(); 17681 } 17682 17683 /** 17684 * Provides the metrics for the shadow image. These include the dimensions of 17685 * the shadow image, and the point within that shadow that should 17686 * be centered under the touch location while dragging. 17687 * <p> 17688 * The default implementation sets the dimensions of the shadow to be the 17689 * same as the dimensions of the View itself and centers the shadow under 17690 * the touch point. 17691 * </p> 17692 * 17693 * @param shadowSize A {@link android.graphics.Point} containing the width and height 17694 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 17695 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 17696 * image. 17697 * 17698 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 17699 * shadow image that should be underneath the touch point during the drag and drop 17700 * operation. Your application must set {@link android.graphics.Point#x} to the 17701 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 17702 */ 17703 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 17704 final View view = mView.get(); 17705 if (view != null) { 17706 shadowSize.set(view.getWidth(), view.getHeight()); 17707 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 17708 } else { 17709 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 17710 } 17711 } 17712 17713 /** 17714 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 17715 * based on the dimensions it received from the 17716 * {@link #onProvideShadowMetrics(Point, Point)} callback. 17717 * 17718 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 17719 */ 17720 public void onDrawShadow(Canvas canvas) { 17721 final View view = mView.get(); 17722 if (view != null) { 17723 view.draw(canvas); 17724 } else { 17725 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 17726 } 17727 } 17728 } 17729 17730 /** 17731 * Starts a drag and drop operation. When your application calls this method, it passes a 17732 * {@link android.view.View.DragShadowBuilder} object to the system. The 17733 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 17734 * to get metrics for the drag shadow, and then calls the object's 17735 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 17736 * <p> 17737 * Once the system has the drag shadow, it begins the drag and drop operation by sending 17738 * drag events to all the View objects in your application that are currently visible. It does 17739 * this either by calling the View object's drag listener (an implementation of 17740 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 17741 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 17742 * Both are passed a {@link android.view.DragEvent} object that has a 17743 * {@link android.view.DragEvent#getAction()} value of 17744 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 17745 * </p> 17746 * <p> 17747 * Your application can invoke startDrag() on any attached View object. The View object does not 17748 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to 17749 * be related to the View the user selected for dragging. 17750 * </p> 17751 * @param data A {@link android.content.ClipData} object pointing to the data to be 17752 * transferred by the drag and drop operation. 17753 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 17754 * drag shadow. 17755 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 17756 * drop operation. This Object is put into every DragEvent object sent by the system during the 17757 * current drag. 17758 * <p> 17759 * myLocalState is a lightweight mechanism for the sending information from the dragged View 17760 * to the target Views. For example, it can contain flags that differentiate between a 17761 * a copy operation and a move operation. 17762 * </p> 17763 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 17764 * so the parameter should be set to 0. 17765 * @return {@code true} if the method completes successfully, or 17766 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 17767 * do a drag, and so no drag operation is in progress. 17768 */ 17769 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 17770 Object myLocalState, int flags) { 17771 if (ViewDebug.DEBUG_DRAG) { 17772 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 17773 } 17774 boolean okay = false; 17775 17776 Point shadowSize = new Point(); 17777 Point shadowTouchPoint = new Point(); 17778 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 17779 17780 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 17781 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 17782 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 17783 } 17784 17785 if (ViewDebug.DEBUG_DRAG) { 17786 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 17787 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 17788 } 17789 Surface surface = new Surface(); 17790 try { 17791 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 17792 flags, shadowSize.x, shadowSize.y, surface); 17793 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 17794 + " surface=" + surface); 17795 if (token != null) { 17796 Canvas canvas = surface.lockCanvas(null); 17797 try { 17798 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 17799 shadowBuilder.onDrawShadow(canvas); 17800 } finally { 17801 surface.unlockCanvasAndPost(canvas); 17802 } 17803 17804 final ViewRootImpl root = getViewRootImpl(); 17805 17806 // Cache the local state object for delivery with DragEvents 17807 root.setLocalDragState(myLocalState); 17808 17809 // repurpose 'shadowSize' for the last touch point 17810 root.getLastTouchPoint(shadowSize); 17811 17812 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 17813 shadowSize.x, shadowSize.y, 17814 shadowTouchPoint.x, shadowTouchPoint.y, data); 17815 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 17816 17817 // Off and running! Release our local surface instance; the drag 17818 // shadow surface is now managed by the system process. 17819 surface.release(); 17820 } 17821 } catch (Exception e) { 17822 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 17823 surface.destroy(); 17824 } 17825 17826 return okay; 17827 } 17828 17829 /** 17830 * Handles drag events sent by the system following a call to 17831 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}. 17832 *<p> 17833 * When the system calls this method, it passes a 17834 * {@link android.view.DragEvent} object. A call to 17835 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 17836 * in DragEvent. The method uses these to determine what is happening in the drag and drop 17837 * operation. 17838 * @param event The {@link android.view.DragEvent} sent by the system. 17839 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 17840 * in DragEvent, indicating the type of drag event represented by this object. 17841 * @return {@code true} if the method was successful, otherwise {@code false}. 17842 * <p> 17843 * The method should return {@code true} in response to an action type of 17844 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 17845 * operation. 17846 * </p> 17847 * <p> 17848 * The method should also return {@code true} in response to an action type of 17849 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 17850 * {@code false} if it didn't. 17851 * </p> 17852 */ 17853 public boolean onDragEvent(DragEvent event) { 17854 return false; 17855 } 17856 17857 /** 17858 * Detects if this View is enabled and has a drag event listener. 17859 * If both are true, then it calls the drag event listener with the 17860 * {@link android.view.DragEvent} it received. If the drag event listener returns 17861 * {@code true}, then dispatchDragEvent() returns {@code true}. 17862 * <p> 17863 * For all other cases, the method calls the 17864 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 17865 * method and returns its result. 17866 * </p> 17867 * <p> 17868 * This ensures that a drag event is always consumed, even if the View does not have a drag 17869 * event listener. However, if the View has a listener and the listener returns true, then 17870 * onDragEvent() is not called. 17871 * </p> 17872 */ 17873 public boolean dispatchDragEvent(DragEvent event) { 17874 ListenerInfo li = mListenerInfo; 17875 //noinspection SimplifiableIfStatement 17876 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 17877 && li.mOnDragListener.onDrag(this, event)) { 17878 return true; 17879 } 17880 return onDragEvent(event); 17881 } 17882 17883 boolean canAcceptDrag() { 17884 return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0; 17885 } 17886 17887 /** 17888 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 17889 * it is ever exposed at all. 17890 * @hide 17891 */ 17892 public void onCloseSystemDialogs(String reason) { 17893 } 17894 17895 /** 17896 * Given a Drawable whose bounds have been set to draw into this view, 17897 * update a Region being computed for 17898 * {@link #gatherTransparentRegion(android.graphics.Region)} so 17899 * that any non-transparent parts of the Drawable are removed from the 17900 * given transparent region. 17901 * 17902 * @param dr The Drawable whose transparency is to be applied to the region. 17903 * @param region A Region holding the current transparency information, 17904 * where any parts of the region that are set are considered to be 17905 * transparent. On return, this region will be modified to have the 17906 * transparency information reduced by the corresponding parts of the 17907 * Drawable that are not transparent. 17908 * {@hide} 17909 */ 17910 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 17911 if (DBG) { 17912 Log.i("View", "Getting transparent region for: " + this); 17913 } 17914 final Region r = dr.getTransparentRegion(); 17915 final Rect db = dr.getBounds(); 17916 final AttachInfo attachInfo = mAttachInfo; 17917 if (r != null && attachInfo != null) { 17918 final int w = getRight()-getLeft(); 17919 final int h = getBottom()-getTop(); 17920 if (db.left > 0) { 17921 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 17922 r.op(0, 0, db.left, h, Region.Op.UNION); 17923 } 17924 if (db.right < w) { 17925 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 17926 r.op(db.right, 0, w, h, Region.Op.UNION); 17927 } 17928 if (db.top > 0) { 17929 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 17930 r.op(0, 0, w, db.top, Region.Op.UNION); 17931 } 17932 if (db.bottom < h) { 17933 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 17934 r.op(0, db.bottom, w, h, Region.Op.UNION); 17935 } 17936 final int[] location = attachInfo.mTransparentLocation; 17937 getLocationInWindow(location); 17938 r.translate(location[0], location[1]); 17939 region.op(r, Region.Op.INTERSECT); 17940 } else { 17941 region.op(db, Region.Op.DIFFERENCE); 17942 } 17943 } 17944 17945 private void checkForLongClick(int delayOffset) { 17946 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 17947 mHasPerformedLongPress = false; 17948 17949 if (mPendingCheckForLongPress == null) { 17950 mPendingCheckForLongPress = new CheckForLongPress(); 17951 } 17952 mPendingCheckForLongPress.rememberWindowAttachCount(); 17953 postDelayed(mPendingCheckForLongPress, 17954 ViewConfiguration.getLongPressTimeout() - delayOffset); 17955 } 17956 } 17957 17958 /** 17959 * Inflate a view from an XML resource. This convenience method wraps the {@link 17960 * LayoutInflater} class, which provides a full range of options for view inflation. 17961 * 17962 * @param context The Context object for your activity or application. 17963 * @param resource The resource ID to inflate 17964 * @param root A view group that will be the parent. Used to properly inflate the 17965 * layout_* parameters. 17966 * @see LayoutInflater 17967 */ 17968 public static View inflate(Context context, int resource, ViewGroup root) { 17969 LayoutInflater factory = LayoutInflater.from(context); 17970 return factory.inflate(resource, root); 17971 } 17972 17973 /** 17974 * Scroll the view with standard behavior for scrolling beyond the normal 17975 * content boundaries. Views that call this method should override 17976 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 17977 * results of an over-scroll operation. 17978 * 17979 * Views can use this method to handle any touch or fling-based scrolling. 17980 * 17981 * @param deltaX Change in X in pixels 17982 * @param deltaY Change in Y in pixels 17983 * @param scrollX Current X scroll value in pixels before applying deltaX 17984 * @param scrollY Current Y scroll value in pixels before applying deltaY 17985 * @param scrollRangeX Maximum content scroll range along the X axis 17986 * @param scrollRangeY Maximum content scroll range along the Y axis 17987 * @param maxOverScrollX Number of pixels to overscroll by in either direction 17988 * along the X axis. 17989 * @param maxOverScrollY Number of pixels to overscroll by in either direction 17990 * along the Y axis. 17991 * @param isTouchEvent true if this scroll operation is the result of a touch event. 17992 * @return true if scrolling was clamped to an over-scroll boundary along either 17993 * axis, false otherwise. 17994 */ 17995 @SuppressWarnings({"UnusedParameters"}) 17996 protected boolean overScrollBy(int deltaX, int deltaY, 17997 int scrollX, int scrollY, 17998 int scrollRangeX, int scrollRangeY, 17999 int maxOverScrollX, int maxOverScrollY, 18000 boolean isTouchEvent) { 18001 final int overScrollMode = mOverScrollMode; 18002 final boolean canScrollHorizontal = 18003 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 18004 final boolean canScrollVertical = 18005 computeVerticalScrollRange() > computeVerticalScrollExtent(); 18006 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 18007 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 18008 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 18009 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 18010 18011 int newScrollX = scrollX + deltaX; 18012 if (!overScrollHorizontal) { 18013 maxOverScrollX = 0; 18014 } 18015 18016 int newScrollY = scrollY + deltaY; 18017 if (!overScrollVertical) { 18018 maxOverScrollY = 0; 18019 } 18020 18021 // Clamp values if at the limits and record 18022 final int left = -maxOverScrollX; 18023 final int right = maxOverScrollX + scrollRangeX; 18024 final int top = -maxOverScrollY; 18025 final int bottom = maxOverScrollY + scrollRangeY; 18026 18027 boolean clampedX = false; 18028 if (newScrollX > right) { 18029 newScrollX = right; 18030 clampedX = true; 18031 } else if (newScrollX < left) { 18032 newScrollX = left; 18033 clampedX = true; 18034 } 18035 18036 boolean clampedY = false; 18037 if (newScrollY > bottom) { 18038 newScrollY = bottom; 18039 clampedY = true; 18040 } else if (newScrollY < top) { 18041 newScrollY = top; 18042 clampedY = true; 18043 } 18044 18045 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 18046 18047 return clampedX || clampedY; 18048 } 18049 18050 /** 18051 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 18052 * respond to the results of an over-scroll operation. 18053 * 18054 * @param scrollX New X scroll value in pixels 18055 * @param scrollY New Y scroll value in pixels 18056 * @param clampedX True if scrollX was clamped to an over-scroll boundary 18057 * @param clampedY True if scrollY was clamped to an over-scroll boundary 18058 */ 18059 protected void onOverScrolled(int scrollX, int scrollY, 18060 boolean clampedX, boolean clampedY) { 18061 // Intentionally empty. 18062 } 18063 18064 /** 18065 * Returns the over-scroll mode for this view. The result will be 18066 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 18067 * (allow over-scrolling only if the view content is larger than the container), 18068 * or {@link #OVER_SCROLL_NEVER}. 18069 * 18070 * @return This view's over-scroll mode. 18071 */ 18072 public int getOverScrollMode() { 18073 return mOverScrollMode; 18074 } 18075 18076 /** 18077 * Set the over-scroll mode for this view. Valid over-scroll modes are 18078 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 18079 * (allow over-scrolling only if the view content is larger than the container), 18080 * or {@link #OVER_SCROLL_NEVER}. 18081 * 18082 * Setting the over-scroll mode of a view will have an effect only if the 18083 * view is capable of scrolling. 18084 * 18085 * @param overScrollMode The new over-scroll mode for this view. 18086 */ 18087 public void setOverScrollMode(int overScrollMode) { 18088 if (overScrollMode != OVER_SCROLL_ALWAYS && 18089 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 18090 overScrollMode != OVER_SCROLL_NEVER) { 18091 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 18092 } 18093 mOverScrollMode = overScrollMode; 18094 } 18095 18096 /** 18097 * Enable or disable nested scrolling for this view. 18098 * 18099 * <p>If this property is set to true the view will be permitted to initiate nested 18100 * scrolling operations with a compatible parent view in the current hierarchy. If this 18101 * view does not implement nested scrolling this will have no effect. Disabling nested scrolling 18102 * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping} 18103 * the nested scroll.</p> 18104 * 18105 * @param enabled true to enable nested scrolling, false to disable 18106 * 18107 * @see #isNestedScrollingEnabled() 18108 */ 18109 public void setNestedScrollingEnabled(boolean enabled) { 18110 if (enabled) { 18111 mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED; 18112 } else { 18113 stopNestedScroll(); 18114 mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED; 18115 } 18116 } 18117 18118 /** 18119 * Returns true if nested scrolling is enabled for this view. 18120 * 18121 * <p>If nested scrolling is enabled and this View class implementation supports it, 18122 * this view will act as a nested scrolling child view when applicable, forwarding data 18123 * about the scroll operation in progress to a compatible and cooperating nested scrolling 18124 * parent.</p> 18125 * 18126 * @return true if nested scrolling is enabled 18127 * 18128 * @see #setNestedScrollingEnabled(boolean) 18129 */ 18130 public boolean isNestedScrollingEnabled() { 18131 return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) == 18132 PFLAG3_NESTED_SCROLLING_ENABLED; 18133 } 18134 18135 /** 18136 * Begin a nestable scroll operation along the given axes. 18137 * 18138 * <p>A view starting a nested scroll promises to abide by the following contract:</p> 18139 * 18140 * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case 18141 * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}. 18142 * In the case of touch scrolling the nested scroll will be terminated automatically in 18143 * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}. 18144 * In the event of programmatic scrolling the caller must explicitly call 18145 * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p> 18146 * 18147 * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found. 18148 * If it returns false the caller may ignore the rest of this contract until the next scroll. 18149 * Calling startNestedScroll while a nested scroll is already in progress will return true.</p> 18150 * 18151 * <p>At each incremental step of the scroll the caller should invoke 18152 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} 18153 * once it has calculated the requested scrolling delta. If it returns true the nested scrolling 18154 * parent at least partially consumed the scroll and the caller should adjust the amount it 18155 * scrolls by.</p> 18156 * 18157 * <p>After applying the remainder of the scroll delta the caller should invoke 18158 * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing 18159 * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat 18160 * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}. 18161 * </p> 18162 * 18163 * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or 18164 * {@link #SCROLL_AXIS_VERTICAL}. 18165 * @return true if a cooperative parent was found and nested scrolling has been enabled for 18166 * the current gesture. 18167 * 18168 * @see #stopNestedScroll() 18169 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 18170 * @see #dispatchNestedScroll(int, int, int, int, int[]) 18171 */ 18172 public boolean startNestedScroll(int axes) { 18173 if (hasNestedScrollingParent()) { 18174 // Already in progress 18175 return true; 18176 } 18177 if (isNestedScrollingEnabled()) { 18178 ViewParent p = getParent(); 18179 View child = this; 18180 while (p != null) { 18181 try { 18182 if (p.onStartNestedScroll(child, this, axes)) { 18183 mNestedScrollingParent = p; 18184 p.onNestedScrollAccepted(child, this, axes); 18185 return true; 18186 } 18187 } catch (AbstractMethodError e) { 18188 Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " + 18189 "method onStartNestedScroll", e); 18190 // Allow the search upward to continue 18191 } 18192 if (p instanceof View) { 18193 child = (View) p; 18194 } 18195 p = p.getParent(); 18196 } 18197 } 18198 return false; 18199 } 18200 18201 /** 18202 * Stop a nested scroll in progress. 18203 * 18204 * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p> 18205 * 18206 * @see #startNestedScroll(int) 18207 */ 18208 public void stopNestedScroll() { 18209 if (mNestedScrollingParent != null) { 18210 mNestedScrollingParent.onStopNestedScroll(this); 18211 mNestedScrollingParent = null; 18212 } 18213 } 18214 18215 /** 18216 * Returns true if this view has a nested scrolling parent. 18217 * 18218 * <p>The presence of a nested scrolling parent indicates that this view has initiated 18219 * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p> 18220 * 18221 * @return whether this view has a nested scrolling parent 18222 */ 18223 public boolean hasNestedScrollingParent() { 18224 return mNestedScrollingParent != null; 18225 } 18226 18227 /** 18228 * Dispatch one step of a nested scroll in progress. 18229 * 18230 * <p>Implementations of views that support nested scrolling should call this to report 18231 * info about a scroll in progress to the current nested scrolling parent. If a nested scroll 18232 * is not currently in progress or nested scrolling is not 18233 * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p> 18234 * 18235 * <p>Compatible View implementations should also call 18236 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before 18237 * consuming a component of the scroll event themselves.</p> 18238 * 18239 * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step 18240 * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step 18241 * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view 18242 * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view 18243 * @param offsetInWindow Optional. If not null, on return this will contain the offset 18244 * in local view coordinates of this view from before this operation 18245 * to after it completes. View implementations may use this to adjust 18246 * expected input coordinate tracking. 18247 * @return true if the event was dispatched, false if it could not be dispatched. 18248 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 18249 */ 18250 public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, 18251 int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow) { 18252 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18253 if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) { 18254 int startX = 0; 18255 int startY = 0; 18256 if (offsetInWindow != null) { 18257 getLocationInWindow(offsetInWindow); 18258 startX = offsetInWindow[0]; 18259 startY = offsetInWindow[1]; 18260 } 18261 18262 mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed, 18263 dxUnconsumed, dyUnconsumed); 18264 18265 if (offsetInWindow != null) { 18266 getLocationInWindow(offsetInWindow); 18267 offsetInWindow[0] -= startX; 18268 offsetInWindow[1] -= startY; 18269 } 18270 return true; 18271 } else if (offsetInWindow != null) { 18272 // No motion, no dispatch. Keep offsetInWindow up to date. 18273 offsetInWindow[0] = 0; 18274 offsetInWindow[1] = 0; 18275 } 18276 } 18277 return false; 18278 } 18279 18280 /** 18281 * Dispatch one step of a nested scroll in progress before this view consumes any portion of it. 18282 * 18283 * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch. 18284 * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested 18285 * scrolling operation to consume some or all of the scroll operation before the child view 18286 * consumes it.</p> 18287 * 18288 * @param dx Horizontal scroll distance in pixels 18289 * @param dy Vertical scroll distance in pixels 18290 * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx 18291 * and consumed[1] the consumed dy. 18292 * @param offsetInWindow Optional. If not null, on return this will contain the offset 18293 * in local view coordinates of this view from before this operation 18294 * to after it completes. View implementations may use this to adjust 18295 * expected input coordinate tracking. 18296 * @return true if the parent consumed some or all of the scroll delta 18297 * @see #dispatchNestedScroll(int, int, int, int, int[]) 18298 */ 18299 public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) { 18300 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18301 if (dx != 0 || dy != 0) { 18302 int startX = 0; 18303 int startY = 0; 18304 if (offsetInWindow != null) { 18305 getLocationInWindow(offsetInWindow); 18306 startX = offsetInWindow[0]; 18307 startY = offsetInWindow[1]; 18308 } 18309 18310 if (consumed == null) { 18311 if (mTempNestedScrollConsumed == null) { 18312 mTempNestedScrollConsumed = new int[2]; 18313 } 18314 consumed = mTempNestedScrollConsumed; 18315 } 18316 consumed[0] = 0; 18317 consumed[1] = 0; 18318 mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed); 18319 18320 if (offsetInWindow != null) { 18321 getLocationInWindow(offsetInWindow); 18322 offsetInWindow[0] -= startX; 18323 offsetInWindow[1] -= startY; 18324 } 18325 return consumed[0] != 0 || consumed[1] != 0; 18326 } else if (offsetInWindow != null) { 18327 offsetInWindow[0] = 0; 18328 offsetInWindow[1] = 0; 18329 } 18330 } 18331 return false; 18332 } 18333 18334 /** 18335 * Dispatch a fling to a nested scrolling parent. 18336 * 18337 * <p>This method should be used to indicate that a nested scrolling child has detected 18338 * suitable conditions for a fling. Generally this means that a touch scroll has ended with a 18339 * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds 18340 * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity} 18341 * along a scrollable axis.</p> 18342 * 18343 * <p>If a nested scrolling child view would normally fling but it is at the edge of 18344 * its own content, it can use this method to delegate the fling to its nested scrolling 18345 * parent instead. The parent may optionally consume the fling or observe a child fling.</p> 18346 * 18347 * @param velocityX Horizontal fling velocity in pixels per second 18348 * @param velocityY Vertical fling velocity in pixels per second 18349 * @param consumed true if the child consumed the fling, false otherwise 18350 * @return true if the nested scrolling parent consumed or otherwise reacted to the fling 18351 */ 18352 public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) { 18353 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18354 return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed); 18355 } 18356 return false; 18357 } 18358 18359 /** 18360 * Gets a scale factor that determines the distance the view should scroll 18361 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 18362 * @return The vertical scroll scale factor. 18363 * @hide 18364 */ 18365 protected float getVerticalScrollFactor() { 18366 if (mVerticalScrollFactor == 0) { 18367 TypedValue outValue = new TypedValue(); 18368 if (!mContext.getTheme().resolveAttribute( 18369 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 18370 throw new IllegalStateException( 18371 "Expected theme to define listPreferredItemHeight."); 18372 } 18373 mVerticalScrollFactor = outValue.getDimension( 18374 mContext.getResources().getDisplayMetrics()); 18375 } 18376 return mVerticalScrollFactor; 18377 } 18378 18379 /** 18380 * Gets a scale factor that determines the distance the view should scroll 18381 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 18382 * @return The horizontal scroll scale factor. 18383 * @hide 18384 */ 18385 protected float getHorizontalScrollFactor() { 18386 // TODO: Should use something else. 18387 return getVerticalScrollFactor(); 18388 } 18389 18390 /** 18391 * Return the value specifying the text direction or policy that was set with 18392 * {@link #setTextDirection(int)}. 18393 * 18394 * @return the defined text direction. It can be one of: 18395 * 18396 * {@link #TEXT_DIRECTION_INHERIT}, 18397 * {@link #TEXT_DIRECTION_FIRST_STRONG} 18398 * {@link #TEXT_DIRECTION_ANY_RTL}, 18399 * {@link #TEXT_DIRECTION_LTR}, 18400 * {@link #TEXT_DIRECTION_RTL}, 18401 * {@link #TEXT_DIRECTION_LOCALE} 18402 * 18403 * @attr ref android.R.styleable#View_textDirection 18404 * 18405 * @hide 18406 */ 18407 @ViewDebug.ExportedProperty(category = "text", mapping = { 18408 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 18409 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 18410 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 18411 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 18412 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 18413 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 18414 }) 18415 public int getRawTextDirection() { 18416 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 18417 } 18418 18419 /** 18420 * Set the text direction. 18421 * 18422 * @param textDirection the direction to set. Should be one of: 18423 * 18424 * {@link #TEXT_DIRECTION_INHERIT}, 18425 * {@link #TEXT_DIRECTION_FIRST_STRONG} 18426 * {@link #TEXT_DIRECTION_ANY_RTL}, 18427 * {@link #TEXT_DIRECTION_LTR}, 18428 * {@link #TEXT_DIRECTION_RTL}, 18429 * {@link #TEXT_DIRECTION_LOCALE} 18430 * 18431 * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution 18432 * proceeds up the parent chain of the view to get the value. If there is no parent, then it will 18433 * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}. 18434 * 18435 * @attr ref android.R.styleable#View_textDirection 18436 */ 18437 public void setTextDirection(int textDirection) { 18438 if (getRawTextDirection() != textDirection) { 18439 // Reset the current text direction and the resolved one 18440 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 18441 resetResolvedTextDirection(); 18442 // Set the new text direction 18443 mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK); 18444 // Do resolution 18445 resolveTextDirection(); 18446 // Notify change 18447 onRtlPropertiesChanged(getLayoutDirection()); 18448 // Refresh 18449 requestLayout(); 18450 invalidate(true); 18451 } 18452 } 18453 18454 /** 18455 * Return the resolved text direction. 18456 * 18457 * @return the resolved text direction. Returns one of: 18458 * 18459 * {@link #TEXT_DIRECTION_FIRST_STRONG} 18460 * {@link #TEXT_DIRECTION_ANY_RTL}, 18461 * {@link #TEXT_DIRECTION_LTR}, 18462 * {@link #TEXT_DIRECTION_RTL}, 18463 * {@link #TEXT_DIRECTION_LOCALE} 18464 * 18465 * @attr ref android.R.styleable#View_textDirection 18466 */ 18467 @ViewDebug.ExportedProperty(category = "text", mapping = { 18468 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 18469 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 18470 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 18471 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 18472 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 18473 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 18474 }) 18475 public int getTextDirection() { 18476 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 18477 } 18478 18479 /** 18480 * Resolve the text direction. 18481 * 18482 * @return true if resolution has been done, false otherwise. 18483 * 18484 * @hide 18485 */ 18486 public boolean resolveTextDirection() { 18487 // Reset any previous text direction resolution 18488 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 18489 18490 if (hasRtlSupport()) { 18491 // Set resolved text direction flag depending on text direction flag 18492 final int textDirection = getRawTextDirection(); 18493 switch(textDirection) { 18494 case TEXT_DIRECTION_INHERIT: 18495 if (!canResolveTextDirection()) { 18496 // We cannot do the resolution if there is no parent, so use the default one 18497 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18498 // Resolution will need to happen again later 18499 return false; 18500 } 18501 18502 // Parent has not yet resolved, so we still return the default 18503 try { 18504 if (!mParent.isTextDirectionResolved()) { 18505 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18506 // Resolution will need to happen again later 18507 return false; 18508 } 18509 } catch (AbstractMethodError e) { 18510 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18511 " does not fully implement ViewParent", e); 18512 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED | 18513 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18514 return true; 18515 } 18516 18517 // Set current resolved direction to the same value as the parent's one 18518 int parentResolvedDirection; 18519 try { 18520 parentResolvedDirection = mParent.getTextDirection(); 18521 } catch (AbstractMethodError e) { 18522 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18523 " does not fully implement ViewParent", e); 18524 parentResolvedDirection = TEXT_DIRECTION_LTR; 18525 } 18526 switch (parentResolvedDirection) { 18527 case TEXT_DIRECTION_FIRST_STRONG: 18528 case TEXT_DIRECTION_ANY_RTL: 18529 case TEXT_DIRECTION_LTR: 18530 case TEXT_DIRECTION_RTL: 18531 case TEXT_DIRECTION_LOCALE: 18532 mPrivateFlags2 |= 18533 (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 18534 break; 18535 default: 18536 // Default resolved direction is "first strong" heuristic 18537 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18538 } 18539 break; 18540 case TEXT_DIRECTION_FIRST_STRONG: 18541 case TEXT_DIRECTION_ANY_RTL: 18542 case TEXT_DIRECTION_LTR: 18543 case TEXT_DIRECTION_RTL: 18544 case TEXT_DIRECTION_LOCALE: 18545 // Resolved direction is the same as text direction 18546 mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 18547 break; 18548 default: 18549 // Default resolved direction is "first strong" heuristic 18550 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18551 } 18552 } else { 18553 // Default resolved direction is "first strong" heuristic 18554 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18555 } 18556 18557 // Set to resolved 18558 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED; 18559 return true; 18560 } 18561 18562 /** 18563 * Check if text direction resolution can be done. 18564 * 18565 * @return true if text direction resolution can be done otherwise return false. 18566 */ 18567 public boolean canResolveTextDirection() { 18568 switch (getRawTextDirection()) { 18569 case TEXT_DIRECTION_INHERIT: 18570 if (mParent != null) { 18571 try { 18572 return mParent.canResolveTextDirection(); 18573 } catch (AbstractMethodError e) { 18574 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18575 " does not fully implement ViewParent", e); 18576 } 18577 } 18578 return false; 18579 18580 default: 18581 return true; 18582 } 18583 } 18584 18585 /** 18586 * Reset resolved text direction. Text direction will be resolved during a call to 18587 * {@link #onMeasure(int, int)}. 18588 * 18589 * @hide 18590 */ 18591 public void resetResolvedTextDirection() { 18592 // Reset any previous text direction resolution 18593 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 18594 // Set to default value 18595 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18596 } 18597 18598 /** 18599 * @return true if text direction is inherited. 18600 * 18601 * @hide 18602 */ 18603 public boolean isTextDirectionInherited() { 18604 return (getRawTextDirection() == TEXT_DIRECTION_INHERIT); 18605 } 18606 18607 /** 18608 * @return true if text direction is resolved. 18609 */ 18610 public boolean isTextDirectionResolved() { 18611 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED; 18612 } 18613 18614 /** 18615 * Return the value specifying the text alignment or policy that was set with 18616 * {@link #setTextAlignment(int)}. 18617 * 18618 * @return the defined text alignment. It can be one of: 18619 * 18620 * {@link #TEXT_ALIGNMENT_INHERIT}, 18621 * {@link #TEXT_ALIGNMENT_GRAVITY}, 18622 * {@link #TEXT_ALIGNMENT_CENTER}, 18623 * {@link #TEXT_ALIGNMENT_TEXT_START}, 18624 * {@link #TEXT_ALIGNMENT_TEXT_END}, 18625 * {@link #TEXT_ALIGNMENT_VIEW_START}, 18626 * {@link #TEXT_ALIGNMENT_VIEW_END} 18627 * 18628 * @attr ref android.R.styleable#View_textAlignment 18629 * 18630 * @hide 18631 */ 18632 @ViewDebug.ExportedProperty(category = "text", mapping = { 18633 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 18634 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 18635 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 18636 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 18637 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 18638 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 18639 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 18640 }) 18641 @TextAlignment 18642 public int getRawTextAlignment() { 18643 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 18644 } 18645 18646 /** 18647 * Set the text alignment. 18648 * 18649 * @param textAlignment The text alignment to set. Should be one of 18650 * 18651 * {@link #TEXT_ALIGNMENT_INHERIT}, 18652 * {@link #TEXT_ALIGNMENT_GRAVITY}, 18653 * {@link #TEXT_ALIGNMENT_CENTER}, 18654 * {@link #TEXT_ALIGNMENT_TEXT_START}, 18655 * {@link #TEXT_ALIGNMENT_TEXT_END}, 18656 * {@link #TEXT_ALIGNMENT_VIEW_START}, 18657 * {@link #TEXT_ALIGNMENT_VIEW_END} 18658 * 18659 * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution 18660 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 18661 * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}. 18662 * 18663 * @attr ref android.R.styleable#View_textAlignment 18664 */ 18665 public void setTextAlignment(@TextAlignment int textAlignment) { 18666 if (textAlignment != getRawTextAlignment()) { 18667 // Reset the current and resolved text alignment 18668 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 18669 resetResolvedTextAlignment(); 18670 // Set the new text alignment 18671 mPrivateFlags2 |= 18672 ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK); 18673 // Do resolution 18674 resolveTextAlignment(); 18675 // Notify change 18676 onRtlPropertiesChanged(getLayoutDirection()); 18677 // Refresh 18678 requestLayout(); 18679 invalidate(true); 18680 } 18681 } 18682 18683 /** 18684 * Return the resolved text alignment. 18685 * 18686 * @return the resolved text alignment. Returns one of: 18687 * 18688 * {@link #TEXT_ALIGNMENT_GRAVITY}, 18689 * {@link #TEXT_ALIGNMENT_CENTER}, 18690 * {@link #TEXT_ALIGNMENT_TEXT_START}, 18691 * {@link #TEXT_ALIGNMENT_TEXT_END}, 18692 * {@link #TEXT_ALIGNMENT_VIEW_START}, 18693 * {@link #TEXT_ALIGNMENT_VIEW_END} 18694 * 18695 * @attr ref android.R.styleable#View_textAlignment 18696 */ 18697 @ViewDebug.ExportedProperty(category = "text", mapping = { 18698 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 18699 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 18700 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 18701 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 18702 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 18703 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 18704 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 18705 }) 18706 @TextAlignment 18707 public int getTextAlignment() { 18708 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >> 18709 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 18710 } 18711 18712 /** 18713 * Resolve the text alignment. 18714 * 18715 * @return true if resolution has been done, false otherwise. 18716 * 18717 * @hide 18718 */ 18719 public boolean resolveTextAlignment() { 18720 // Reset any previous text alignment resolution 18721 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 18722 18723 if (hasRtlSupport()) { 18724 // Set resolved text alignment flag depending on text alignment flag 18725 final int textAlignment = getRawTextAlignment(); 18726 switch (textAlignment) { 18727 case TEXT_ALIGNMENT_INHERIT: 18728 // Check if we can resolve the text alignment 18729 if (!canResolveTextAlignment()) { 18730 // We cannot do the resolution if there is no parent so use the default 18731 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18732 // Resolution will need to happen again later 18733 return false; 18734 } 18735 18736 // Parent has not yet resolved, so we still return the default 18737 try { 18738 if (!mParent.isTextAlignmentResolved()) { 18739 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18740 // Resolution will need to happen again later 18741 return false; 18742 } 18743 } catch (AbstractMethodError e) { 18744 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18745 " does not fully implement ViewParent", e); 18746 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED | 18747 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18748 return true; 18749 } 18750 18751 int parentResolvedTextAlignment; 18752 try { 18753 parentResolvedTextAlignment = mParent.getTextAlignment(); 18754 } catch (AbstractMethodError e) { 18755 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18756 " does not fully implement ViewParent", e); 18757 parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY; 18758 } 18759 switch (parentResolvedTextAlignment) { 18760 case TEXT_ALIGNMENT_GRAVITY: 18761 case TEXT_ALIGNMENT_TEXT_START: 18762 case TEXT_ALIGNMENT_TEXT_END: 18763 case TEXT_ALIGNMENT_CENTER: 18764 case TEXT_ALIGNMENT_VIEW_START: 18765 case TEXT_ALIGNMENT_VIEW_END: 18766 // Resolved text alignment is the same as the parent resolved 18767 // text alignment 18768 mPrivateFlags2 |= 18769 (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 18770 break; 18771 default: 18772 // Use default resolved text alignment 18773 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18774 } 18775 break; 18776 case TEXT_ALIGNMENT_GRAVITY: 18777 case TEXT_ALIGNMENT_TEXT_START: 18778 case TEXT_ALIGNMENT_TEXT_END: 18779 case TEXT_ALIGNMENT_CENTER: 18780 case TEXT_ALIGNMENT_VIEW_START: 18781 case TEXT_ALIGNMENT_VIEW_END: 18782 // Resolved text alignment is the same as text alignment 18783 mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 18784 break; 18785 default: 18786 // Use default resolved text alignment 18787 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18788 } 18789 } else { 18790 // Use default resolved text alignment 18791 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18792 } 18793 18794 // Set the resolved 18795 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED; 18796 return true; 18797 } 18798 18799 /** 18800 * Check if text alignment resolution can be done. 18801 * 18802 * @return true if text alignment resolution can be done otherwise return false. 18803 */ 18804 public boolean canResolveTextAlignment() { 18805 switch (getRawTextAlignment()) { 18806 case TEXT_DIRECTION_INHERIT: 18807 if (mParent != null) { 18808 try { 18809 return mParent.canResolveTextAlignment(); 18810 } catch (AbstractMethodError e) { 18811 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18812 " does not fully implement ViewParent", e); 18813 } 18814 } 18815 return false; 18816 18817 default: 18818 return true; 18819 } 18820 } 18821 18822 /** 18823 * Reset resolved text alignment. Text alignment will be resolved during a call to 18824 * {@link #onMeasure(int, int)}. 18825 * 18826 * @hide 18827 */ 18828 public void resetResolvedTextAlignment() { 18829 // Reset any previous text alignment resolution 18830 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 18831 // Set to default 18832 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18833 } 18834 18835 /** 18836 * @return true if text alignment is inherited. 18837 * 18838 * @hide 18839 */ 18840 public boolean isTextAlignmentInherited() { 18841 return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT); 18842 } 18843 18844 /** 18845 * @return true if text alignment is resolved. 18846 */ 18847 public boolean isTextAlignmentResolved() { 18848 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED; 18849 } 18850 18851 /** 18852 * Generate a value suitable for use in {@link #setId(int)}. 18853 * This value will not collide with ID values generated at build time by aapt for R.id. 18854 * 18855 * @return a generated ID value 18856 */ 18857 public static int generateViewId() { 18858 for (;;) { 18859 final int result = sNextGeneratedId.get(); 18860 // aapt-generated IDs have the high byte nonzero; clamp to the range under that. 18861 int newValue = result + 1; 18862 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. 18863 if (sNextGeneratedId.compareAndSet(result, newValue)) { 18864 return result; 18865 } 18866 } 18867 } 18868 18869 /** 18870 * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions. 18871 * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and 18872 * a normal View or a ViewGroup with 18873 * {@link android.view.ViewGroup#isTransitionGroup()} true. 18874 * @hide 18875 */ 18876 public void captureTransitioningViews(List<View> transitioningViews) { 18877 if (getVisibility() == View.VISIBLE) { 18878 transitioningViews.add(this); 18879 } 18880 } 18881 18882 /** 18883 * Adds all Views that have {@link #getViewName()} non-null to namedElements. 18884 * @param namedElements Will contain all Views in the hierarchy having a view name. 18885 * @hide 18886 */ 18887 public void findNamedViews(Map<String, View> namedElements) { 18888 if (getVisibility() == VISIBLE) { 18889 String viewName = getViewName(); 18890 if (viewName != null) { 18891 namedElements.put(viewName, this); 18892 } 18893 } 18894 } 18895 18896 // 18897 // Properties 18898 // 18899 /** 18900 * A Property wrapper around the <code>alpha</code> functionality handled by the 18901 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 18902 */ 18903 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 18904 @Override 18905 public void setValue(View object, float value) { 18906 object.setAlpha(value); 18907 } 18908 18909 @Override 18910 public Float get(View object) { 18911 return object.getAlpha(); 18912 } 18913 }; 18914 18915 /** 18916 * A Property wrapper around the <code>translationX</code> functionality handled by the 18917 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 18918 */ 18919 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 18920 @Override 18921 public void setValue(View object, float value) { 18922 object.setTranslationX(value); 18923 } 18924 18925 @Override 18926 public Float get(View object) { 18927 return object.getTranslationX(); 18928 } 18929 }; 18930 18931 /** 18932 * A Property wrapper around the <code>translationY</code> functionality handled by the 18933 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 18934 */ 18935 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 18936 @Override 18937 public void setValue(View object, float value) { 18938 object.setTranslationY(value); 18939 } 18940 18941 @Override 18942 public Float get(View object) { 18943 return object.getTranslationY(); 18944 } 18945 }; 18946 18947 /** 18948 * A Property wrapper around the <code>translationZ</code> functionality handled by the 18949 * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods. 18950 */ 18951 public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") { 18952 @Override 18953 public void setValue(View object, float value) { 18954 object.setTranslationZ(value); 18955 } 18956 18957 @Override 18958 public Float get(View object) { 18959 return object.getTranslationZ(); 18960 } 18961 }; 18962 18963 /** 18964 * A Property wrapper around the <code>x</code> functionality handled by the 18965 * {@link View#setX(float)} and {@link View#getX()} methods. 18966 */ 18967 public static final Property<View, Float> X = new FloatProperty<View>("x") { 18968 @Override 18969 public void setValue(View object, float value) { 18970 object.setX(value); 18971 } 18972 18973 @Override 18974 public Float get(View object) { 18975 return object.getX(); 18976 } 18977 }; 18978 18979 /** 18980 * A Property wrapper around the <code>y</code> functionality handled by the 18981 * {@link View#setY(float)} and {@link View#getY()} methods. 18982 */ 18983 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 18984 @Override 18985 public void setValue(View object, float value) { 18986 object.setY(value); 18987 } 18988 18989 @Override 18990 public Float get(View object) { 18991 return object.getY(); 18992 } 18993 }; 18994 18995 /** 18996 * A Property wrapper around the <code>z</code> functionality handled by the 18997 * {@link View#setZ(float)} and {@link View#getZ()} methods. 18998 */ 18999 public static final Property<View, Float> Z = new FloatProperty<View>("z") { 19000 @Override 19001 public void setValue(View object, float value) { 19002 object.setZ(value); 19003 } 19004 19005 @Override 19006 public Float get(View object) { 19007 return object.getZ(); 19008 } 19009 }; 19010 19011 /** 19012 * A Property wrapper around the <code>rotation</code> functionality handled by the 19013 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 19014 */ 19015 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 19016 @Override 19017 public void setValue(View object, float value) { 19018 object.setRotation(value); 19019 } 19020 19021 @Override 19022 public Float get(View object) { 19023 return object.getRotation(); 19024 } 19025 }; 19026 19027 /** 19028 * A Property wrapper around the <code>rotationX</code> functionality handled by the 19029 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 19030 */ 19031 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 19032 @Override 19033 public void setValue(View object, float value) { 19034 object.setRotationX(value); 19035 } 19036 19037 @Override 19038 public Float get(View object) { 19039 return object.getRotationX(); 19040 } 19041 }; 19042 19043 /** 19044 * A Property wrapper around the <code>rotationY</code> functionality handled by the 19045 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 19046 */ 19047 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 19048 @Override 19049 public void setValue(View object, float value) { 19050 object.setRotationY(value); 19051 } 19052 19053 @Override 19054 public Float get(View object) { 19055 return object.getRotationY(); 19056 } 19057 }; 19058 19059 /** 19060 * A Property wrapper around the <code>scaleX</code> functionality handled by the 19061 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 19062 */ 19063 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 19064 @Override 19065 public void setValue(View object, float value) { 19066 object.setScaleX(value); 19067 } 19068 19069 @Override 19070 public Float get(View object) { 19071 return object.getScaleX(); 19072 } 19073 }; 19074 19075 /** 19076 * A Property wrapper around the <code>scaleY</code> functionality handled by the 19077 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 19078 */ 19079 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 19080 @Override 19081 public void setValue(View object, float value) { 19082 object.setScaleY(value); 19083 } 19084 19085 @Override 19086 public Float get(View object) { 19087 return object.getScaleY(); 19088 } 19089 }; 19090 19091 /** 19092 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 19093 * Each MeasureSpec represents a requirement for either the width or the height. 19094 * A MeasureSpec is comprised of a size and a mode. There are three possible 19095 * modes: 19096 * <dl> 19097 * <dt>UNSPECIFIED</dt> 19098 * <dd> 19099 * The parent has not imposed any constraint on the child. It can be whatever size 19100 * it wants. 19101 * </dd> 19102 * 19103 * <dt>EXACTLY</dt> 19104 * <dd> 19105 * The parent has determined an exact size for the child. The child is going to be 19106 * given those bounds regardless of how big it wants to be. 19107 * </dd> 19108 * 19109 * <dt>AT_MOST</dt> 19110 * <dd> 19111 * The child can be as large as it wants up to the specified size. 19112 * </dd> 19113 * </dl> 19114 * 19115 * MeasureSpecs are implemented as ints to reduce object allocation. This class 19116 * is provided to pack and unpack the <size, mode> tuple into the int. 19117 */ 19118 public static class MeasureSpec { 19119 private static final int MODE_SHIFT = 30; 19120 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 19121 19122 /** 19123 * Measure specification mode: The parent has not imposed any constraint 19124 * on the child. It can be whatever size it wants. 19125 */ 19126 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 19127 19128 /** 19129 * Measure specification mode: The parent has determined an exact size 19130 * for the child. The child is going to be given those bounds regardless 19131 * of how big it wants to be. 19132 */ 19133 public static final int EXACTLY = 1 << MODE_SHIFT; 19134 19135 /** 19136 * Measure specification mode: The child can be as large as it wants up 19137 * to the specified size. 19138 */ 19139 public static final int AT_MOST = 2 << MODE_SHIFT; 19140 19141 /** 19142 * Creates a measure specification based on the supplied size and mode. 19143 * 19144 * The mode must always be one of the following: 19145 * <ul> 19146 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 19147 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 19148 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 19149 * </ul> 19150 * 19151 * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's 19152 * implementation was such that the order of arguments did not matter 19153 * and overflow in either value could impact the resulting MeasureSpec. 19154 * {@link android.widget.RelativeLayout} was affected by this bug. 19155 * Apps targeting API levels greater than 17 will get the fixed, more strict 19156 * behavior.</p> 19157 * 19158 * @param size the size of the measure specification 19159 * @param mode the mode of the measure specification 19160 * @return the measure specification based on size and mode 19161 */ 19162 public static int makeMeasureSpec(int size, int mode) { 19163 if (sUseBrokenMakeMeasureSpec) { 19164 return size + mode; 19165 } else { 19166 return (size & ~MODE_MASK) | (mode & MODE_MASK); 19167 } 19168 } 19169 19170 /** 19171 * Extracts the mode from the supplied measure specification. 19172 * 19173 * @param measureSpec the measure specification to extract the mode from 19174 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 19175 * {@link android.view.View.MeasureSpec#AT_MOST} or 19176 * {@link android.view.View.MeasureSpec#EXACTLY} 19177 */ 19178 public static int getMode(int measureSpec) { 19179 return (measureSpec & MODE_MASK); 19180 } 19181 19182 /** 19183 * Extracts the size from the supplied measure specification. 19184 * 19185 * @param measureSpec the measure specification to extract the size from 19186 * @return the size in pixels defined in the supplied measure specification 19187 */ 19188 public static int getSize(int measureSpec) { 19189 return (measureSpec & ~MODE_MASK); 19190 } 19191 19192 static int adjust(int measureSpec, int delta) { 19193 final int mode = getMode(measureSpec); 19194 if (mode == UNSPECIFIED) { 19195 // No need to adjust size for UNSPECIFIED mode. 19196 return makeMeasureSpec(0, UNSPECIFIED); 19197 } 19198 int size = getSize(measureSpec) + delta; 19199 if (size < 0) { 19200 Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size + 19201 ") spec: " + toString(measureSpec) + " delta: " + delta); 19202 size = 0; 19203 } 19204 return makeMeasureSpec(size, mode); 19205 } 19206 19207 /** 19208 * Returns a String representation of the specified measure 19209 * specification. 19210 * 19211 * @param measureSpec the measure specification to convert to a String 19212 * @return a String with the following format: "MeasureSpec: MODE SIZE" 19213 */ 19214 public static String toString(int measureSpec) { 19215 int mode = getMode(measureSpec); 19216 int size = getSize(measureSpec); 19217 19218 StringBuilder sb = new StringBuilder("MeasureSpec: "); 19219 19220 if (mode == UNSPECIFIED) 19221 sb.append("UNSPECIFIED "); 19222 else if (mode == EXACTLY) 19223 sb.append("EXACTLY "); 19224 else if (mode == AT_MOST) 19225 sb.append("AT_MOST "); 19226 else 19227 sb.append(mode).append(" "); 19228 19229 sb.append(size); 19230 return sb.toString(); 19231 } 19232 } 19233 19234 private final class CheckForLongPress implements Runnable { 19235 private int mOriginalWindowAttachCount; 19236 19237 @Override 19238 public void run() { 19239 if (isPressed() && (mParent != null) 19240 && mOriginalWindowAttachCount == mWindowAttachCount) { 19241 if (performLongClick()) { 19242 mHasPerformedLongPress = true; 19243 } 19244 } 19245 } 19246 19247 public void rememberWindowAttachCount() { 19248 mOriginalWindowAttachCount = mWindowAttachCount; 19249 } 19250 } 19251 19252 private final class CheckForTap implements Runnable { 19253 public float x; 19254 public float y; 19255 19256 @Override 19257 public void run() { 19258 mPrivateFlags &= ~PFLAG_PREPRESSED; 19259 setPressed(true, x, y); 19260 checkForLongClick(ViewConfiguration.getTapTimeout()); 19261 } 19262 } 19263 19264 private final class PerformClick implements Runnable { 19265 @Override 19266 public void run() { 19267 performClick(); 19268 } 19269 } 19270 19271 /** @hide */ 19272 public void hackTurnOffWindowResizeAnim(boolean off) { 19273 mAttachInfo.mTurnOffWindowResizeAnim = off; 19274 } 19275 19276 /** 19277 * This method returns a ViewPropertyAnimator object, which can be used to animate 19278 * specific properties on this View. 19279 * 19280 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 19281 */ 19282 public ViewPropertyAnimator animate() { 19283 if (mAnimator == null) { 19284 mAnimator = new ViewPropertyAnimator(this); 19285 } 19286 return mAnimator; 19287 } 19288 19289 /** 19290 * Sets the name of the View to be used to identify Views in Transitions. 19291 * Names should be unique in the View hierarchy. 19292 * 19293 * @param viewName The name of the View to uniquely identify it for Transitions. 19294 */ 19295 public final void setViewName(String viewName) { 19296 mViewName = viewName; 19297 } 19298 19299 /** 19300 * Returns the name of the View to be used to identify Views in Transitions. 19301 * Names should be unique in the View hierarchy. 19302 * 19303 * <p>This returns null if the View has not been given a name.</p> 19304 * 19305 * @return The name used of the View to be used to identify Views in Transitions or null 19306 * if no name has been given. 19307 */ 19308 public String getViewName() { 19309 return mViewName; 19310 } 19311 19312 /** 19313 * Interface definition for a callback to be invoked when a hardware key event is 19314 * dispatched to this view. The callback will be invoked before the key event is 19315 * given to the view. This is only useful for hardware keyboards; a software input 19316 * method has no obligation to trigger this listener. 19317 */ 19318 public interface OnKeyListener { 19319 /** 19320 * Called when a hardware key is dispatched to a view. This allows listeners to 19321 * get a chance to respond before the target view. 19322 * <p>Key presses in software keyboards will generally NOT trigger this method, 19323 * although some may elect to do so in some situations. Do not assume a 19324 * software input method has to be key-based; even if it is, it may use key presses 19325 * in a different way than you expect, so there is no way to reliably catch soft 19326 * input key presses. 19327 * 19328 * @param v The view the key has been dispatched to. 19329 * @param keyCode The code for the physical key that was pressed 19330 * @param event The KeyEvent object containing full information about 19331 * the event. 19332 * @return True if the listener has consumed the event, false otherwise. 19333 */ 19334 boolean onKey(View v, int keyCode, KeyEvent event); 19335 } 19336 19337 /** 19338 * Interface definition for a callback to be invoked when a touch event is 19339 * dispatched to this view. The callback will be invoked before the touch 19340 * event is given to the view. 19341 */ 19342 public interface OnTouchListener { 19343 /** 19344 * Called when a touch event is dispatched to a view. This allows listeners to 19345 * get a chance to respond before the target view. 19346 * 19347 * @param v The view the touch event has been dispatched to. 19348 * @param event The MotionEvent object containing full information about 19349 * the event. 19350 * @return True if the listener has consumed the event, false otherwise. 19351 */ 19352 boolean onTouch(View v, MotionEvent event); 19353 } 19354 19355 /** 19356 * Interface definition for a callback to be invoked when a hover event is 19357 * dispatched to this view. The callback will be invoked before the hover 19358 * event is given to the view. 19359 */ 19360 public interface OnHoverListener { 19361 /** 19362 * Called when a hover event is dispatched to a view. This allows listeners to 19363 * get a chance to respond before the target view. 19364 * 19365 * @param v The view the hover event has been dispatched to. 19366 * @param event The MotionEvent object containing full information about 19367 * the event. 19368 * @return True if the listener has consumed the event, false otherwise. 19369 */ 19370 boolean onHover(View v, MotionEvent event); 19371 } 19372 19373 /** 19374 * Interface definition for a callback to be invoked when a generic motion event is 19375 * dispatched to this view. The callback will be invoked before the generic motion 19376 * event is given to the view. 19377 */ 19378 public interface OnGenericMotionListener { 19379 /** 19380 * Called when a generic motion event is dispatched to a view. This allows listeners to 19381 * get a chance to respond before the target view. 19382 * 19383 * @param v The view the generic motion event has been dispatched to. 19384 * @param event The MotionEvent object containing full information about 19385 * the event. 19386 * @return True if the listener has consumed the event, false otherwise. 19387 */ 19388 boolean onGenericMotion(View v, MotionEvent event); 19389 } 19390 19391 /** 19392 * Interface definition for a callback to be invoked when a view has been clicked and held. 19393 */ 19394 public interface OnLongClickListener { 19395 /** 19396 * Called when a view has been clicked and held. 19397 * 19398 * @param v The view that was clicked and held. 19399 * 19400 * @return true if the callback consumed the long click, false otherwise. 19401 */ 19402 boolean onLongClick(View v); 19403 } 19404 19405 /** 19406 * Interface definition for a callback to be invoked when a drag is being dispatched 19407 * to this view. The callback will be invoked before the hosting view's own 19408 * onDrag(event) method. If the listener wants to fall back to the hosting view's 19409 * onDrag(event) behavior, it should return 'false' from this callback. 19410 * 19411 * <div class="special reference"> 19412 * <h3>Developer Guides</h3> 19413 * <p>For a guide to implementing drag and drop features, read the 19414 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 19415 * </div> 19416 */ 19417 public interface OnDragListener { 19418 /** 19419 * Called when a drag event is dispatched to a view. This allows listeners 19420 * to get a chance to override base View behavior. 19421 * 19422 * @param v The View that received the drag event. 19423 * @param event The {@link android.view.DragEvent} object for the drag event. 19424 * @return {@code true} if the drag event was handled successfully, or {@code false} 19425 * if the drag event was not handled. Note that {@code false} will trigger the View 19426 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 19427 */ 19428 boolean onDrag(View v, DragEvent event); 19429 } 19430 19431 /** 19432 * Interface definition for a callback to be invoked when the focus state of 19433 * a view changed. 19434 */ 19435 public interface OnFocusChangeListener { 19436 /** 19437 * Called when the focus state of a view has changed. 19438 * 19439 * @param v The view whose state has changed. 19440 * @param hasFocus The new focus state of v. 19441 */ 19442 void onFocusChange(View v, boolean hasFocus); 19443 } 19444 19445 /** 19446 * Interface definition for a callback to be invoked when a view is clicked. 19447 */ 19448 public interface OnClickListener { 19449 /** 19450 * Called when a view has been clicked. 19451 * 19452 * @param v The view that was clicked. 19453 */ 19454 void onClick(View v); 19455 } 19456 19457 /** 19458 * Interface definition for a callback to be invoked when the context menu 19459 * for this view is being built. 19460 */ 19461 public interface OnCreateContextMenuListener { 19462 /** 19463 * Called when the context menu for this view is being built. It is not 19464 * safe to hold onto the menu after this method returns. 19465 * 19466 * @param menu The context menu that is being built 19467 * @param v The view for which the context menu is being built 19468 * @param menuInfo Extra information about the item for which the 19469 * context menu should be shown. This information will vary 19470 * depending on the class of v. 19471 */ 19472 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 19473 } 19474 19475 /** 19476 * Interface definition for a callback to be invoked when the status bar changes 19477 * visibility. This reports <strong>global</strong> changes to the system UI 19478 * state, not what the application is requesting. 19479 * 19480 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 19481 */ 19482 public interface OnSystemUiVisibilityChangeListener { 19483 /** 19484 * Called when the status bar changes visibility because of a call to 19485 * {@link View#setSystemUiVisibility(int)}. 19486 * 19487 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 19488 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}. 19489 * This tells you the <strong>global</strong> state of these UI visibility 19490 * flags, not what your app is currently applying. 19491 */ 19492 public void onSystemUiVisibilityChange(int visibility); 19493 } 19494 19495 /** 19496 * Interface definition for a callback to be invoked when this view is attached 19497 * or detached from its window. 19498 */ 19499 public interface OnAttachStateChangeListener { 19500 /** 19501 * Called when the view is attached to a window. 19502 * @param v The view that was attached 19503 */ 19504 public void onViewAttachedToWindow(View v); 19505 /** 19506 * Called when the view is detached from a window. 19507 * @param v The view that was detached 19508 */ 19509 public void onViewDetachedFromWindow(View v); 19510 } 19511 19512 /** 19513 * Listener for applying window insets on a view in a custom way. 19514 * 19515 * <p>Apps may choose to implement this interface if they want to apply custom policy 19516 * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener 19517 * is set, its 19518 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 19519 * method will be called instead of the View's own 19520 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener 19521 * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply 19522 * the View's normal behavior as part of its own.</p> 19523 */ 19524 public interface OnApplyWindowInsetsListener { 19525 /** 19526 * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set} 19527 * on a View, this listener method will be called instead of the view's own 19528 * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 19529 * 19530 * @param v The view applying window insets 19531 * @param insets The insets to apply 19532 * @return The insets supplied, minus any insets that were consumed 19533 */ 19534 public WindowInsets onApplyWindowInsets(View v, WindowInsets insets); 19535 } 19536 19537 private final class UnsetPressedState implements Runnable { 19538 @Override 19539 public void run() { 19540 setPressed(false); 19541 } 19542 } 19543 19544 /** 19545 * Base class for derived classes that want to save and restore their own 19546 * state in {@link android.view.View#onSaveInstanceState()}. 19547 */ 19548 public static class BaseSavedState extends AbsSavedState { 19549 /** 19550 * Constructor used when reading from a parcel. Reads the state of the superclass. 19551 * 19552 * @param source 19553 */ 19554 public BaseSavedState(Parcel source) { 19555 super(source); 19556 } 19557 19558 /** 19559 * Constructor called by derived classes when creating their SavedState objects 19560 * 19561 * @param superState The state of the superclass of this view 19562 */ 19563 public BaseSavedState(Parcelable superState) { 19564 super(superState); 19565 } 19566 19567 public static final Parcelable.Creator<BaseSavedState> CREATOR = 19568 new Parcelable.Creator<BaseSavedState>() { 19569 public BaseSavedState createFromParcel(Parcel in) { 19570 return new BaseSavedState(in); 19571 } 19572 19573 public BaseSavedState[] newArray(int size) { 19574 return new BaseSavedState[size]; 19575 } 19576 }; 19577 } 19578 19579 /** 19580 * A set of information given to a view when it is attached to its parent 19581 * window. 19582 */ 19583 final static class AttachInfo { 19584 interface Callbacks { 19585 void playSoundEffect(int effectId); 19586 boolean performHapticFeedback(int effectId, boolean always); 19587 } 19588 19589 /** 19590 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 19591 * to a Handler. This class contains the target (View) to invalidate and 19592 * the coordinates of the dirty rectangle. 19593 * 19594 * For performance purposes, this class also implements a pool of up to 19595 * POOL_LIMIT objects that get reused. This reduces memory allocations 19596 * whenever possible. 19597 */ 19598 static class InvalidateInfo { 19599 private static final int POOL_LIMIT = 10; 19600 19601 private static final SynchronizedPool<InvalidateInfo> sPool = 19602 new SynchronizedPool<InvalidateInfo>(POOL_LIMIT); 19603 19604 View target; 19605 19606 int left; 19607 int top; 19608 int right; 19609 int bottom; 19610 19611 public static InvalidateInfo obtain() { 19612 InvalidateInfo instance = sPool.acquire(); 19613 return (instance != null) ? instance : new InvalidateInfo(); 19614 } 19615 19616 public void recycle() { 19617 target = null; 19618 sPool.release(this); 19619 } 19620 } 19621 19622 final IWindowSession mSession; 19623 19624 final IWindow mWindow; 19625 19626 final IBinder mWindowToken; 19627 19628 final Display mDisplay; 19629 19630 final Callbacks mRootCallbacks; 19631 19632 IWindowId mIWindowId; 19633 WindowId mWindowId; 19634 19635 /** 19636 * The top view of the hierarchy. 19637 */ 19638 View mRootView; 19639 19640 IBinder mPanelParentWindowToken; 19641 19642 boolean mHardwareAccelerated; 19643 boolean mHardwareAccelerationRequested; 19644 HardwareRenderer mHardwareRenderer; 19645 19646 /** 19647 * The state of the display to which the window is attached, as reported 19648 * by {@link Display#getState()}. Note that the display state constants 19649 * declared by {@link Display} do not exactly line up with the screen state 19650 * constants declared by {@link View} (there are more display states than 19651 * screen states). 19652 */ 19653 int mDisplayState = Display.STATE_UNKNOWN; 19654 19655 /** 19656 * Scale factor used by the compatibility mode 19657 */ 19658 float mApplicationScale; 19659 19660 /** 19661 * Indicates whether the application is in compatibility mode 19662 */ 19663 boolean mScalingRequired; 19664 19665 /** 19666 * If set, ViewRootImpl doesn't use its lame animation for when the window resizes. 19667 */ 19668 boolean mTurnOffWindowResizeAnim; 19669 19670 /** 19671 * Left position of this view's window 19672 */ 19673 int mWindowLeft; 19674 19675 /** 19676 * Top position of this view's window 19677 */ 19678 int mWindowTop; 19679 19680 /** 19681 * Indicates whether views need to use 32-bit drawing caches 19682 */ 19683 boolean mUse32BitDrawingCache; 19684 19685 /** 19686 * For windows that are full-screen but using insets to layout inside 19687 * of the screen areas, these are the current insets to appear inside 19688 * the overscan area of the display. 19689 */ 19690 final Rect mOverscanInsets = new Rect(); 19691 19692 /** 19693 * For windows that are full-screen but using insets to layout inside 19694 * of the screen decorations, these are the current insets for the 19695 * content of the window. 19696 */ 19697 final Rect mContentInsets = new Rect(); 19698 19699 /** 19700 * For windows that are full-screen but using insets to layout inside 19701 * of the screen decorations, these are the current insets for the 19702 * actual visible parts of the window. 19703 */ 19704 final Rect mVisibleInsets = new Rect(); 19705 19706 /** 19707 * The internal insets given by this window. This value is 19708 * supplied by the client (through 19709 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 19710 * be given to the window manager when changed to be used in laying 19711 * out windows behind it. 19712 */ 19713 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 19714 = new ViewTreeObserver.InternalInsetsInfo(); 19715 19716 /** 19717 * Set to true when mGivenInternalInsets is non-empty. 19718 */ 19719 boolean mHasNonEmptyGivenInternalInsets; 19720 19721 /** 19722 * All views in the window's hierarchy that serve as scroll containers, 19723 * used to determine if the window can be resized or must be panned 19724 * to adjust for a soft input area. 19725 */ 19726 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 19727 19728 final KeyEvent.DispatcherState mKeyDispatchState 19729 = new KeyEvent.DispatcherState(); 19730 19731 /** 19732 * Indicates whether the view's window currently has the focus. 19733 */ 19734 boolean mHasWindowFocus; 19735 19736 /** 19737 * The current visibility of the window. 19738 */ 19739 int mWindowVisibility; 19740 19741 /** 19742 * Indicates the time at which drawing started to occur. 19743 */ 19744 long mDrawingTime; 19745 19746 /** 19747 * Indicates whether or not ignoring the DIRTY_MASK flags. 19748 */ 19749 boolean mIgnoreDirtyState; 19750 19751 /** 19752 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 19753 * to avoid clearing that flag prematurely. 19754 */ 19755 boolean mSetIgnoreDirtyState = false; 19756 19757 /** 19758 * Indicates whether the view's window is currently in touch mode. 19759 */ 19760 boolean mInTouchMode; 19761 19762 /** 19763 * Indicates that ViewAncestor should trigger a global layout change 19764 * the next time it performs a traversal 19765 */ 19766 boolean mRecomputeGlobalAttributes; 19767 19768 /** 19769 * Always report new attributes at next traversal. 19770 */ 19771 boolean mForceReportNewAttributes; 19772 19773 /** 19774 * Set during a traveral if any views want to keep the screen on. 19775 */ 19776 boolean mKeepScreenOn; 19777 19778 /** 19779 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 19780 */ 19781 int mSystemUiVisibility; 19782 19783 /** 19784 * Hack to force certain system UI visibility flags to be cleared. 19785 */ 19786 int mDisabledSystemUiVisibility; 19787 19788 /** 19789 * Last global system UI visibility reported by the window manager. 19790 */ 19791 int mGlobalSystemUiVisibility; 19792 19793 /** 19794 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 19795 * attached. 19796 */ 19797 boolean mHasSystemUiListeners; 19798 19799 /** 19800 * Set if the window has requested to extend into the overscan region 19801 * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN. 19802 */ 19803 boolean mOverscanRequested; 19804 19805 /** 19806 * Set if the visibility of any views has changed. 19807 */ 19808 boolean mViewVisibilityChanged; 19809 19810 /** 19811 * Set to true if a view has been scrolled. 19812 */ 19813 boolean mViewScrollChanged; 19814 19815 /** 19816 * Global to the view hierarchy used as a temporary for dealing with 19817 * x/y points in the transparent region computations. 19818 */ 19819 final int[] mTransparentLocation = new int[2]; 19820 19821 /** 19822 * Global to the view hierarchy used as a temporary for dealing with 19823 * x/y points in the ViewGroup.invalidateChild implementation. 19824 */ 19825 final int[] mInvalidateChildLocation = new int[2]; 19826 19827 19828 /** 19829 * Global to the view hierarchy used as a temporary for dealing with 19830 * x/y location when view is transformed. 19831 */ 19832 final float[] mTmpTransformLocation = new float[2]; 19833 19834 /** 19835 * The view tree observer used to dispatch global events like 19836 * layout, pre-draw, touch mode change, etc. 19837 */ 19838 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 19839 19840 /** 19841 * A Canvas used by the view hierarchy to perform bitmap caching. 19842 */ 19843 Canvas mCanvas; 19844 19845 /** 19846 * The view root impl. 19847 */ 19848 final ViewRootImpl mViewRootImpl; 19849 19850 /** 19851 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 19852 * handler can be used to pump events in the UI events queue. 19853 */ 19854 final Handler mHandler; 19855 19856 /** 19857 * Temporary for use in computing invalidate rectangles while 19858 * calling up the hierarchy. 19859 */ 19860 final Rect mTmpInvalRect = new Rect(); 19861 19862 /** 19863 * Temporary for use in computing hit areas with transformed views 19864 */ 19865 final RectF mTmpTransformRect = new RectF(); 19866 19867 /** 19868 * Temporary for use in transforming invalidation rect 19869 */ 19870 final Matrix mTmpMatrix = new Matrix(); 19871 19872 /** 19873 * Temporary for use in transforming invalidation rect 19874 */ 19875 final Transformation mTmpTransformation = new Transformation(); 19876 19877 /** 19878 * Temporary list for use in collecting focusable descendents of a view. 19879 */ 19880 final ArrayList<View> mTempArrayList = new ArrayList<View>(24); 19881 19882 /** 19883 * The id of the window for accessibility purposes. 19884 */ 19885 int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 19886 19887 /** 19888 * Flags related to accessibility processing. 19889 * 19890 * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS 19891 * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS 19892 */ 19893 int mAccessibilityFetchFlags; 19894 19895 /** 19896 * The drawable for highlighting accessibility focus. 19897 */ 19898 Drawable mAccessibilityFocusDrawable; 19899 19900 /** 19901 * Show where the margins, bounds and layout bounds are for each view. 19902 */ 19903 boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false); 19904 19905 /** 19906 * Point used to compute visible regions. 19907 */ 19908 final Point mPoint = new Point(); 19909 19910 /** 19911 * Used to track which View originated a requestLayout() call, used when 19912 * requestLayout() is called during layout. 19913 */ 19914 View mViewRequestingLayout; 19915 19916 /** 19917 * Creates a new set of attachment information with the specified 19918 * events handler and thread. 19919 * 19920 * @param handler the events handler the view must use 19921 */ 19922 AttachInfo(IWindowSession session, IWindow window, Display display, 19923 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) { 19924 mSession = session; 19925 mWindow = window; 19926 mWindowToken = window.asBinder(); 19927 mDisplay = display; 19928 mViewRootImpl = viewRootImpl; 19929 mHandler = handler; 19930 mRootCallbacks = effectPlayer; 19931 } 19932 } 19933 19934 /** 19935 * <p>ScrollabilityCache holds various fields used by a View when scrolling 19936 * is supported. This avoids keeping too many unused fields in most 19937 * instances of View.</p> 19938 */ 19939 private static class ScrollabilityCache implements Runnable { 19940 19941 /** 19942 * Scrollbars are not visible 19943 */ 19944 public static final int OFF = 0; 19945 19946 /** 19947 * Scrollbars are visible 19948 */ 19949 public static final int ON = 1; 19950 19951 /** 19952 * Scrollbars are fading away 19953 */ 19954 public static final int FADING = 2; 19955 19956 public boolean fadeScrollBars; 19957 19958 public int fadingEdgeLength; 19959 public int scrollBarDefaultDelayBeforeFade; 19960 public int scrollBarFadeDuration; 19961 19962 public int scrollBarSize; 19963 public ScrollBarDrawable scrollBar; 19964 public float[] interpolatorValues; 19965 public View host; 19966 19967 public final Paint paint; 19968 public final Matrix matrix; 19969 public Shader shader; 19970 19971 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 19972 19973 private static final float[] OPAQUE = { 255 }; 19974 private static final float[] TRANSPARENT = { 0.0f }; 19975 19976 /** 19977 * When fading should start. This time moves into the future every time 19978 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 19979 */ 19980 public long fadeStartTime; 19981 19982 19983 /** 19984 * The current state of the scrollbars: ON, OFF, or FADING 19985 */ 19986 public int state = OFF; 19987 19988 private int mLastColor; 19989 19990 public ScrollabilityCache(ViewConfiguration configuration, View host) { 19991 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 19992 scrollBarSize = configuration.getScaledScrollBarSize(); 19993 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 19994 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 19995 19996 paint = new Paint(); 19997 matrix = new Matrix(); 19998 // use use a height of 1, and then wack the matrix each time we 19999 // actually use it. 20000 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 20001 paint.setShader(shader); 20002 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 20003 20004 this.host = host; 20005 } 20006 20007 public void setFadeColor(int color) { 20008 if (color != mLastColor) { 20009 mLastColor = color; 20010 20011 if (color != 0) { 20012 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 20013 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 20014 paint.setShader(shader); 20015 // Restore the default transfer mode (src_over) 20016 paint.setXfermode(null); 20017 } else { 20018 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 20019 paint.setShader(shader); 20020 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 20021 } 20022 } 20023 } 20024 20025 public void run() { 20026 long now = AnimationUtils.currentAnimationTimeMillis(); 20027 if (now >= fadeStartTime) { 20028 20029 // the animation fades the scrollbars out by changing 20030 // the opacity (alpha) from fully opaque to fully 20031 // transparent 20032 int nextFrame = (int) now; 20033 int framesCount = 0; 20034 20035 Interpolator interpolator = scrollBarInterpolator; 20036 20037 // Start opaque 20038 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 20039 20040 // End transparent 20041 nextFrame += scrollBarFadeDuration; 20042 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 20043 20044 state = FADING; 20045 20046 // Kick off the fade animation 20047 host.invalidate(true); 20048 } 20049 } 20050 } 20051 20052 /** 20053 * Resuable callback for sending 20054 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 20055 */ 20056 private class SendViewScrolledAccessibilityEvent implements Runnable { 20057 public volatile boolean mIsPending; 20058 20059 public void run() { 20060 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 20061 mIsPending = false; 20062 } 20063 } 20064 20065 /** 20066 * <p> 20067 * This class represents a delegate that can be registered in a {@link View} 20068 * to enhance accessibility support via composition rather via inheritance. 20069 * It is specifically targeted to widget developers that extend basic View 20070 * classes i.e. classes in package android.view, that would like their 20071 * applications to be backwards compatible. 20072 * </p> 20073 * <div class="special reference"> 20074 * <h3>Developer Guides</h3> 20075 * <p>For more information about making applications accessible, read the 20076 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a> 20077 * developer guide.</p> 20078 * </div> 20079 * <p> 20080 * A scenario in which a developer would like to use an accessibility delegate 20081 * is overriding a method introduced in a later API version then the minimal API 20082 * version supported by the application. For example, the method 20083 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 20084 * in API version 4 when the accessibility APIs were first introduced. If a 20085 * developer would like his application to run on API version 4 devices (assuming 20086 * all other APIs used by the application are version 4 or lower) and take advantage 20087 * of this method, instead of overriding the method which would break the application's 20088 * backwards compatibility, he can override the corresponding method in this 20089 * delegate and register the delegate in the target View if the API version of 20090 * the system is high enough i.e. the API version is same or higher to the API 20091 * version that introduced 20092 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 20093 * </p> 20094 * <p> 20095 * Here is an example implementation: 20096 * </p> 20097 * <code><pre><p> 20098 * if (Build.VERSION.SDK_INT >= 14) { 20099 * // If the API version is equal of higher than the version in 20100 * // which onInitializeAccessibilityNodeInfo was introduced we 20101 * // register a delegate with a customized implementation. 20102 * View view = findViewById(R.id.view_id); 20103 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 20104 * public void onInitializeAccessibilityNodeInfo(View host, 20105 * AccessibilityNodeInfo info) { 20106 * // Let the default implementation populate the info. 20107 * super.onInitializeAccessibilityNodeInfo(host, info); 20108 * // Set some other information. 20109 * info.setEnabled(host.isEnabled()); 20110 * } 20111 * }); 20112 * } 20113 * </code></pre></p> 20114 * <p> 20115 * This delegate contains methods that correspond to the accessibility methods 20116 * in View. If a delegate has been specified the implementation in View hands 20117 * off handling to the corresponding method in this delegate. The default 20118 * implementation the delegate methods behaves exactly as the corresponding 20119 * method in View for the case of no accessibility delegate been set. Hence, 20120 * to customize the behavior of a View method, clients can override only the 20121 * corresponding delegate method without altering the behavior of the rest 20122 * accessibility related methods of the host view. 20123 * </p> 20124 */ 20125 public static class AccessibilityDelegate { 20126 20127 /** 20128 * Sends an accessibility event of the given type. If accessibility is not 20129 * enabled this method has no effect. 20130 * <p> 20131 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 20132 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 20133 * been set. 20134 * </p> 20135 * 20136 * @param host The View hosting the delegate. 20137 * @param eventType The type of the event to send. 20138 * 20139 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 20140 */ 20141 public void sendAccessibilityEvent(View host, int eventType) { 20142 host.sendAccessibilityEventInternal(eventType); 20143 } 20144 20145 /** 20146 * Performs the specified accessibility action on the view. For 20147 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 20148 * <p> 20149 * The default implementation behaves as 20150 * {@link View#performAccessibilityAction(int, Bundle) 20151 * View#performAccessibilityAction(int, Bundle)} for the case of 20152 * no accessibility delegate been set. 20153 * </p> 20154 * 20155 * @param action The action to perform. 20156 * @return Whether the action was performed. 20157 * 20158 * @see View#performAccessibilityAction(int, Bundle) 20159 * View#performAccessibilityAction(int, Bundle) 20160 */ 20161 public boolean performAccessibilityAction(View host, int action, Bundle args) { 20162 return host.performAccessibilityActionInternal(action, args); 20163 } 20164 20165 /** 20166 * Sends an accessibility event. This method behaves exactly as 20167 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 20168 * empty {@link AccessibilityEvent} and does not perform a check whether 20169 * accessibility is enabled. 20170 * <p> 20171 * The default implementation behaves as 20172 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20173 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 20174 * the case of no accessibility delegate been set. 20175 * </p> 20176 * 20177 * @param host The View hosting the delegate. 20178 * @param event The event to send. 20179 * 20180 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20181 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20182 */ 20183 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 20184 host.sendAccessibilityEventUncheckedInternal(event); 20185 } 20186 20187 /** 20188 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 20189 * to its children for adding their text content to the event. 20190 * <p> 20191 * The default implementation behaves as 20192 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20193 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 20194 * the case of no accessibility delegate been set. 20195 * </p> 20196 * 20197 * @param host The View hosting the delegate. 20198 * @param event The event. 20199 * @return True if the event population was completed. 20200 * 20201 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20202 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20203 */ 20204 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 20205 return host.dispatchPopulateAccessibilityEventInternal(event); 20206 } 20207 20208 /** 20209 * Gives a chance to the host View to populate the accessibility event with its 20210 * text content. 20211 * <p> 20212 * The default implementation behaves as 20213 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 20214 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 20215 * the case of no accessibility delegate been set. 20216 * </p> 20217 * 20218 * @param host The View hosting the delegate. 20219 * @param event The accessibility event which to populate. 20220 * 20221 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 20222 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 20223 */ 20224 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 20225 host.onPopulateAccessibilityEventInternal(event); 20226 } 20227 20228 /** 20229 * Initializes an {@link AccessibilityEvent} with information about the 20230 * the host View which is the event source. 20231 * <p> 20232 * The default implementation behaves as 20233 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 20234 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 20235 * the case of no accessibility delegate been set. 20236 * </p> 20237 * 20238 * @param host The View hosting the delegate. 20239 * @param event The event to initialize. 20240 * 20241 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 20242 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 20243 */ 20244 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 20245 host.onInitializeAccessibilityEventInternal(event); 20246 } 20247 20248 /** 20249 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 20250 * <p> 20251 * The default implementation behaves as 20252 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20253 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 20254 * the case of no accessibility delegate been set. 20255 * </p> 20256 * 20257 * @param host The View hosting the delegate. 20258 * @param info The instance to initialize. 20259 * 20260 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20261 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20262 */ 20263 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 20264 host.onInitializeAccessibilityNodeInfoInternal(info); 20265 } 20266 20267 /** 20268 * Called when a child of the host View has requested sending an 20269 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 20270 * to augment the event. 20271 * <p> 20272 * The default implementation behaves as 20273 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20274 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 20275 * the case of no accessibility delegate been set. 20276 * </p> 20277 * 20278 * @param host The View hosting the delegate. 20279 * @param child The child which requests sending the event. 20280 * @param event The event to be sent. 20281 * @return True if the event should be sent 20282 * 20283 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20284 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20285 */ 20286 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 20287 AccessibilityEvent event) { 20288 return host.onRequestSendAccessibilityEventInternal(child, event); 20289 } 20290 20291 /** 20292 * Gets the provider for managing a virtual view hierarchy rooted at this View 20293 * and reported to {@link android.accessibilityservice.AccessibilityService}s 20294 * that explore the window content. 20295 * <p> 20296 * The default implementation behaves as 20297 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 20298 * the case of no accessibility delegate been set. 20299 * </p> 20300 * 20301 * @return The provider. 20302 * 20303 * @see AccessibilityNodeProvider 20304 */ 20305 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 20306 return null; 20307 } 20308 20309 /** 20310 * Returns an {@link AccessibilityNodeInfo} representing the host view from the 20311 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 20312 * This method is responsible for obtaining an accessibility node info from a 20313 * pool of reusable instances and calling 20314 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host 20315 * view to initialize the former. 20316 * <p> 20317 * <strong>Note:</strong> The client is responsible for recycling the obtained 20318 * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object 20319 * creation. 20320 * </p> 20321 * <p> 20322 * The default implementation behaves as 20323 * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for 20324 * the case of no accessibility delegate been set. 20325 * </p> 20326 * @return A populated {@link AccessibilityNodeInfo}. 20327 * 20328 * @see AccessibilityNodeInfo 20329 * 20330 * @hide 20331 */ 20332 public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) { 20333 return host.createAccessibilityNodeInfoInternal(); 20334 } 20335 } 20336 20337 private class MatchIdPredicate implements Predicate<View> { 20338 public int mId; 20339 20340 @Override 20341 public boolean apply(View view) { 20342 return (view.mID == mId); 20343 } 20344 } 20345 20346 private class MatchLabelForPredicate implements Predicate<View> { 20347 private int mLabeledId; 20348 20349 @Override 20350 public boolean apply(View view) { 20351 return (view.mLabelForId == mLabeledId); 20352 } 20353 } 20354 20355 private class SendViewStateChangedAccessibilityEvent implements Runnable { 20356 private int mChangeTypes = 0; 20357 private boolean mPosted; 20358 private boolean mPostedWithDelay; 20359 private long mLastEventTimeMillis; 20360 20361 @Override 20362 public void run() { 20363 mPosted = false; 20364 mPostedWithDelay = false; 20365 mLastEventTimeMillis = SystemClock.uptimeMillis(); 20366 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 20367 final AccessibilityEvent event = AccessibilityEvent.obtain(); 20368 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 20369 event.setContentChangeTypes(mChangeTypes); 20370 sendAccessibilityEventUnchecked(event); 20371 } 20372 mChangeTypes = 0; 20373 } 20374 20375 public void runOrPost(int changeType) { 20376 mChangeTypes |= changeType; 20377 20378 // If this is a live region or the child of a live region, collect 20379 // all events from this frame and send them on the next frame. 20380 if (inLiveRegion()) { 20381 // If we're already posted with a delay, remove that. 20382 if (mPostedWithDelay) { 20383 removeCallbacks(this); 20384 mPostedWithDelay = false; 20385 } 20386 // Only post if we're not already posted. 20387 if (!mPosted) { 20388 post(this); 20389 mPosted = true; 20390 } 20391 return; 20392 } 20393 20394 if (mPosted) { 20395 return; 20396 } 20397 final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis; 20398 final long minEventIntevalMillis = 20399 ViewConfiguration.getSendRecurringAccessibilityEventsInterval(); 20400 if (timeSinceLastMillis >= minEventIntevalMillis) { 20401 removeCallbacks(this); 20402 run(); 20403 } else { 20404 postDelayed(this, minEventIntevalMillis - timeSinceLastMillis); 20405 mPosted = true; 20406 mPostedWithDelay = true; 20407 } 20408 } 20409 } 20410 20411 private boolean inLiveRegion() { 20412 if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) { 20413 return true; 20414 } 20415 20416 ViewParent parent = getParent(); 20417 while (parent instanceof View) { 20418 if (((View) parent).getAccessibilityLiveRegion() 20419 != View.ACCESSIBILITY_LIVE_REGION_NONE) { 20420 return true; 20421 } 20422 parent = parent.getParent(); 20423 } 20424 20425 return false; 20426 } 20427 20428 /** 20429 * Dump all private flags in readable format, useful for documentation and 20430 * sanity checking. 20431 */ 20432 private static void dumpFlags() { 20433 final HashMap<String, String> found = Maps.newHashMap(); 20434 try { 20435 for (Field field : View.class.getDeclaredFields()) { 20436 final int modifiers = field.getModifiers(); 20437 if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { 20438 if (field.getType().equals(int.class)) { 20439 final int value = field.getInt(null); 20440 dumpFlag(found, field.getName(), value); 20441 } else if (field.getType().equals(int[].class)) { 20442 final int[] values = (int[]) field.get(null); 20443 for (int i = 0; i < values.length; i++) { 20444 dumpFlag(found, field.getName() + "[" + i + "]", values[i]); 20445 } 20446 } 20447 } 20448 } 20449 } catch (IllegalAccessException e) { 20450 throw new RuntimeException(e); 20451 } 20452 20453 final ArrayList<String> keys = Lists.newArrayList(); 20454 keys.addAll(found.keySet()); 20455 Collections.sort(keys); 20456 for (String key : keys) { 20457 Log.d(VIEW_LOG_TAG, found.get(key)); 20458 } 20459 } 20460 20461 private static void dumpFlag(HashMap<String, String> found, String name, int value) { 20462 // Sort flags by prefix, then by bits, always keeping unique keys 20463 final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' '); 20464 final int prefix = name.indexOf('_'); 20465 final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name; 20466 final String output = bits + " " + name; 20467 found.put(key, output); 20468 } 20469} 20470