View.java revision b6ab098bad4b126eaaaa3aaa5a512fefc4e0749b
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.view; 18 19import android.animation.AnimatorInflater; 20import android.animation.StateListAnimator; 21import android.annotation.IntDef; 22import android.annotation.NonNull; 23import android.annotation.Nullable; 24import android.content.ClipData; 25import android.content.Context; 26import android.content.res.ColorStateList; 27import android.content.res.Configuration; 28import android.content.res.Resources; 29import android.content.res.TypedArray; 30import android.graphics.Bitmap; 31import android.graphics.Canvas; 32import android.graphics.Insets; 33import android.graphics.Interpolator; 34import android.graphics.LinearGradient; 35import android.graphics.Matrix; 36import android.graphics.Outline; 37import android.graphics.Paint; 38import android.graphics.Path; 39import android.graphics.PathMeasure; 40import android.graphics.PixelFormat; 41import android.graphics.Point; 42import android.graphics.PorterDuff; 43import android.graphics.PorterDuffXfermode; 44import android.graphics.Rect; 45import android.graphics.RectF; 46import android.graphics.Region; 47import android.graphics.Shader; 48import android.graphics.drawable.ColorDrawable; 49import android.graphics.drawable.Drawable; 50import android.hardware.display.DisplayManagerGlobal; 51import android.os.Bundle; 52import android.os.Handler; 53import android.os.IBinder; 54import android.os.Parcel; 55import android.os.Parcelable; 56import android.os.RemoteException; 57import android.os.SystemClock; 58import android.os.SystemProperties; 59import android.os.Trace; 60import android.text.TextUtils; 61import android.util.AttributeSet; 62import android.util.FloatProperty; 63import android.util.LayoutDirection; 64import android.util.Log; 65import android.util.LongSparseLongArray; 66import android.util.Pools.SynchronizedPool; 67import android.util.Property; 68import android.util.SparseArray; 69import android.util.SuperNotCalledException; 70import android.util.TypedValue; 71import android.view.ContextMenu.ContextMenuInfo; 72import android.view.AccessibilityIterators.TextSegmentIterator; 73import android.view.AccessibilityIterators.CharacterTextSegmentIterator; 74import android.view.AccessibilityIterators.WordTextSegmentIterator; 75import android.view.AccessibilityIterators.ParagraphTextSegmentIterator; 76import android.view.accessibility.AccessibilityEvent; 77import android.view.accessibility.AccessibilityEventSource; 78import android.view.accessibility.AccessibilityManager; 79import android.view.accessibility.AccessibilityNodeInfo; 80import android.view.accessibility.AccessibilityNodeProvider; 81import android.view.animation.Animation; 82import android.view.animation.AnimationUtils; 83import android.view.animation.Transformation; 84import android.view.inputmethod.EditorInfo; 85import android.view.inputmethod.InputConnection; 86import android.view.inputmethod.InputMethodManager; 87import android.widget.ScrollBarDrawable; 88 89import static android.os.Build.VERSION_CODES.*; 90import static java.lang.Math.max; 91 92import com.android.internal.R; 93import com.android.internal.util.Predicate; 94import com.android.internal.view.menu.MenuBuilder; 95import com.google.android.collect.Lists; 96import com.google.android.collect.Maps; 97 98import java.lang.annotation.Retention; 99import java.lang.annotation.RetentionPolicy; 100import java.lang.ref.WeakReference; 101import java.lang.reflect.Field; 102import java.lang.reflect.InvocationTargetException; 103import java.lang.reflect.Method; 104import java.lang.reflect.Modifier; 105import java.util.ArrayList; 106import java.util.Arrays; 107import java.util.Collections; 108import java.util.HashMap; 109import java.util.List; 110import java.util.Locale; 111import java.util.Map; 112import java.util.concurrent.CopyOnWriteArrayList; 113import java.util.concurrent.atomic.AtomicInteger; 114 115/** 116 * <p> 117 * This class represents the basic building block for user interface components. A View 118 * occupies a rectangular area on the screen and is responsible for drawing and 119 * event handling. View is the base class for <em>widgets</em>, which are 120 * used to create interactive UI components (buttons, text fields, etc.). The 121 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which 122 * are invisible containers that hold other Views (or other ViewGroups) and define 123 * their layout properties. 124 * </p> 125 * 126 * <div class="special reference"> 127 * <h3>Developer Guides</h3> 128 * <p>For information about using this class to develop your application's user interface, 129 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide. 130 * </div> 131 * 132 * <a name="Using"></a> 133 * <h3>Using Views</h3> 134 * <p> 135 * All of the views in a window are arranged in a single tree. You can add views 136 * either from code or by specifying a tree of views in one or more XML layout 137 * files. There are many specialized subclasses of views that act as controls or 138 * are capable of displaying text, images, or other content. 139 * </p> 140 * <p> 141 * Once you have created a tree of views, there are typically a few types of 142 * common operations you may wish to perform: 143 * <ul> 144 * <li><strong>Set properties:</strong> for example setting the text of a 145 * {@link android.widget.TextView}. The available properties and the methods 146 * that set them will vary among the different subclasses of views. Note that 147 * properties that are known at build time can be set in the XML layout 148 * files.</li> 149 * <li><strong>Set focus:</strong> The framework will handled moving focus in 150 * response to user input. To force focus to a specific view, call 151 * {@link #requestFocus}.</li> 152 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 153 * that will be notified when something interesting happens to the view. For 154 * example, all views will let you set a listener to be notified when the view 155 * gains or loses focus. You can register such a listener using 156 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}. 157 * Other view subclasses offer more specialized listeners. For example, a Button 158 * exposes a listener to notify clients when the button is clicked.</li> 159 * <li><strong>Set visibility:</strong> You can hide or show views using 160 * {@link #setVisibility(int)}.</li> 161 * </ul> 162 * </p> 163 * <p><em> 164 * Note: The Android framework is responsible for measuring, laying out and 165 * drawing views. You should not call methods that perform these actions on 166 * views yourself unless you are actually implementing a 167 * {@link android.view.ViewGroup}. 168 * </em></p> 169 * 170 * <a name="Lifecycle"></a> 171 * <h3>Implementing a Custom View</h3> 172 * 173 * <p> 174 * To implement a custom view, you will usually begin by providing overrides for 175 * some of the standard methods that the framework calls on all views. You do 176 * not need to override all of these methods. In fact, you can start by just 177 * overriding {@link #onDraw(android.graphics.Canvas)}. 178 * <table border="2" width="85%" align="center" cellpadding="5"> 179 * <thead> 180 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 181 * </thead> 182 * 183 * <tbody> 184 * <tr> 185 * <td rowspan="2">Creation</td> 186 * <td>Constructors</td> 187 * <td>There is a form of the constructor that are called when the view 188 * is created from code and a form that is called when the view is 189 * inflated from a layout file. The second form should parse and apply 190 * any attributes defined in the layout file. 191 * </td> 192 * </tr> 193 * <tr> 194 * <td><code>{@link #onFinishInflate()}</code></td> 195 * <td>Called after a view and all of its children has been inflated 196 * from XML.</td> 197 * </tr> 198 * 199 * <tr> 200 * <td rowspan="3">Layout</td> 201 * <td><code>{@link #onMeasure(int, int)}</code></td> 202 * <td>Called to determine the size requirements for this view and all 203 * of its children. 204 * </td> 205 * </tr> 206 * <tr> 207 * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td> 208 * <td>Called when this view should assign a size and position to all 209 * of its children. 210 * </td> 211 * </tr> 212 * <tr> 213 * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td> 214 * <td>Called when the size of this view has changed. 215 * </td> 216 * </tr> 217 * 218 * <tr> 219 * <td>Drawing</td> 220 * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td> 221 * <td>Called when the view should render its content. 222 * </td> 223 * </tr> 224 * 225 * <tr> 226 * <td rowspan="4">Event processing</td> 227 * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td> 228 * <td>Called when a new hardware key event occurs. 229 * </td> 230 * </tr> 231 * <tr> 232 * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td> 233 * <td>Called when a hardware key up event occurs. 234 * </td> 235 * </tr> 236 * <tr> 237 * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td> 238 * <td>Called when a trackball motion event occurs. 239 * </td> 240 * </tr> 241 * <tr> 242 * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td> 243 * <td>Called when a touch screen motion event occurs. 244 * </td> 245 * </tr> 246 * 247 * <tr> 248 * <td rowspan="2">Focus</td> 249 * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td> 250 * <td>Called when the view gains or loses focus. 251 * </td> 252 * </tr> 253 * 254 * <tr> 255 * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td> 256 * <td>Called when the window containing the view gains or loses focus. 257 * </td> 258 * </tr> 259 * 260 * <tr> 261 * <td rowspan="3">Attaching</td> 262 * <td><code>{@link #onAttachedToWindow()}</code></td> 263 * <td>Called when the view is attached to a window. 264 * </td> 265 * </tr> 266 * 267 * <tr> 268 * <td><code>{@link #onDetachedFromWindow}</code></td> 269 * <td>Called when the view is detached from its window. 270 * </td> 271 * </tr> 272 * 273 * <tr> 274 * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td> 275 * <td>Called when the visibility of the window containing the view 276 * has changed. 277 * </td> 278 * </tr> 279 * </tbody> 280 * 281 * </table> 282 * </p> 283 * 284 * <a name="IDs"></a> 285 * <h3>IDs</h3> 286 * Views may have an integer id associated with them. These ids are typically 287 * assigned in the layout XML files, and are used to find specific views within 288 * the view tree. A common pattern is to: 289 * <ul> 290 * <li>Define a Button in the layout file and assign it a unique ID. 291 * <pre> 292 * <Button 293 * android:id="@+id/my_button" 294 * android:layout_width="wrap_content" 295 * android:layout_height="wrap_content" 296 * android:text="@string/my_button_text"/> 297 * </pre></li> 298 * <li>From the onCreate method of an Activity, find the Button 299 * <pre class="prettyprint"> 300 * Button myButton = (Button) findViewById(R.id.my_button); 301 * </pre></li> 302 * </ul> 303 * <p> 304 * View IDs need not be unique throughout the tree, but it is good practice to 305 * ensure that they are at least unique within the part of the tree you are 306 * searching. 307 * </p> 308 * 309 * <a name="Position"></a> 310 * <h3>Position</h3> 311 * <p> 312 * The geometry of a view is that of a rectangle. A view has a location, 313 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 314 * two dimensions, expressed as a width and a height. The unit for location 315 * and dimensions is the pixel. 316 * </p> 317 * 318 * <p> 319 * It is possible to retrieve the location of a view by invoking the methods 320 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 321 * coordinate of the rectangle representing the view. The latter returns the 322 * top, or Y, coordinate of the rectangle representing the view. These methods 323 * both return the location of the view relative to its parent. For instance, 324 * when getLeft() returns 20, that means the view is located 20 pixels to the 325 * right of the left edge of its direct parent. 326 * </p> 327 * 328 * <p> 329 * In addition, several convenience methods are offered to avoid unnecessary 330 * computations, namely {@link #getRight()} and {@link #getBottom()}. 331 * These methods return the coordinates of the right and bottom edges of the 332 * rectangle representing the view. For instance, calling {@link #getRight()} 333 * is similar to the following computation: <code>getLeft() + getWidth()</code> 334 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 335 * </p> 336 * 337 * <a name="SizePaddingMargins"></a> 338 * <h3>Size, padding and margins</h3> 339 * <p> 340 * The size of a view is expressed with a width and a height. A view actually 341 * possess two pairs of width and height values. 342 * </p> 343 * 344 * <p> 345 * The first pair is known as <em>measured width</em> and 346 * <em>measured height</em>. These dimensions define how big a view wants to be 347 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 348 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 349 * and {@link #getMeasuredHeight()}. 350 * </p> 351 * 352 * <p> 353 * The second pair is simply known as <em>width</em> and <em>height</em>, or 354 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 355 * dimensions define the actual size of the view on screen, at drawing time and 356 * after layout. These values may, but do not have to, be different from the 357 * measured width and height. The width and height can be obtained by calling 358 * {@link #getWidth()} and {@link #getHeight()}. 359 * </p> 360 * 361 * <p> 362 * To measure its dimensions, a view takes into account its padding. The padding 363 * is expressed in pixels for the left, top, right and bottom parts of the view. 364 * Padding can be used to offset the content of the view by a specific amount of 365 * pixels. For instance, a left padding of 2 will push the view's content by 366 * 2 pixels to the right of the left edge. Padding can be set using the 367 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)} 368 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 369 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()}, 370 * {@link #getPaddingEnd()}. 371 * </p> 372 * 373 * <p> 374 * Even though a view can define a padding, it does not provide any support for 375 * margins. However, view groups provide such a support. Refer to 376 * {@link android.view.ViewGroup} and 377 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 378 * </p> 379 * 380 * <a name="Layout"></a> 381 * <h3>Layout</h3> 382 * <p> 383 * Layout is a two pass process: a measure pass and a layout pass. The measuring 384 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 385 * of the view tree. Each view pushes dimension specifications down the tree 386 * during the recursion. At the end of the measure pass, every view has stored 387 * its measurements. The second pass happens in 388 * {@link #layout(int,int,int,int)} and is also top-down. During 389 * this pass each parent is responsible for positioning all of its children 390 * using the sizes computed in the measure pass. 391 * </p> 392 * 393 * <p> 394 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 395 * {@link #getMeasuredHeight()} values must be set, along with those for all of 396 * that view's descendants. A view's measured width and measured height values 397 * must respect the constraints imposed by the view's parents. This guarantees 398 * that at the end of the measure pass, all parents accept all of their 399 * children's measurements. A parent view may call measure() more than once on 400 * its children. For example, the parent may measure each child once with 401 * unspecified dimensions to find out how big they want to be, then call 402 * measure() on them again with actual numbers if the sum of all the children's 403 * unconstrained sizes is too big or too small. 404 * </p> 405 * 406 * <p> 407 * The measure pass uses two classes to communicate dimensions. The 408 * {@link MeasureSpec} class is used by views to tell their parents how they 409 * want to be measured and positioned. The base LayoutParams class just 410 * describes how big the view wants to be for both width and height. For each 411 * dimension, it can specify one of: 412 * <ul> 413 * <li> an exact number 414 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 415 * (minus padding) 416 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 417 * enclose its content (plus padding). 418 * </ul> 419 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 420 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 421 * an X and Y value. 422 * </p> 423 * 424 * <p> 425 * MeasureSpecs are used to push requirements down the tree from parent to 426 * child. A MeasureSpec can be in one of three modes: 427 * <ul> 428 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 429 * of a child view. For example, a LinearLayout may call measure() on its child 430 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 431 * tall the child view wants to be given a width of 240 pixels. 432 * <li>EXACTLY: This is used by the parent to impose an exact size on the 433 * child. The child must use this size, and guarantee that all of its 434 * descendants will fit within this size. 435 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 436 * child. The child must guarantee that it and all of its descendants will fit 437 * within this size. 438 * </ul> 439 * </p> 440 * 441 * <p> 442 * To intiate a layout, call {@link #requestLayout}. This method is typically 443 * called by a view on itself when it believes that is can no longer fit within 444 * its current bounds. 445 * </p> 446 * 447 * <a name="Drawing"></a> 448 * <h3>Drawing</h3> 449 * <p> 450 * Drawing is handled by walking the tree and recording the drawing commands of 451 * any View that needs to update. After this, the drawing commands of the 452 * entire tree are issued to screen, clipped to the newly damaged area. 453 * </p> 454 * 455 * <p> 456 * The tree is largely recorded and drawn in order, with parents drawn before 457 * (i.e., behind) their children, with siblings drawn in the order they appear 458 * in the tree. If you set a background drawable for a View, then the View will 459 * draw it before calling back to its <code>onDraw()</code> method. The child 460 * drawing order can be overridden with 461 * {@link ViewGroup#setChildrenDrawingOrderEnabled(boolean) custom child drawing order} 462 * in a ViewGroup, and with {@link #setZ(float)} custom Z values} set on Views. 463 * </p> 464 * 465 * <p> 466 * To force a view to draw, call {@link #invalidate()}. 467 * </p> 468 * 469 * <a name="EventHandlingThreading"></a> 470 * <h3>Event Handling and Threading</h3> 471 * <p> 472 * The basic cycle of a view is as follows: 473 * <ol> 474 * <li>An event comes in and is dispatched to the appropriate view. The view 475 * handles the event and notifies any listeners.</li> 476 * <li>If in the course of processing the event, the view's bounds may need 477 * to be changed, the view will call {@link #requestLayout()}.</li> 478 * <li>Similarly, if in the course of processing the event the view's appearance 479 * may need to be changed, the view will call {@link #invalidate()}.</li> 480 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 481 * the framework will take care of measuring, laying out, and drawing the tree 482 * as appropriate.</li> 483 * </ol> 484 * </p> 485 * 486 * <p><em>Note: The entire view tree is single threaded. You must always be on 487 * the UI thread when calling any method on any view.</em> 488 * If you are doing work on other threads and want to update the state of a view 489 * from that thread, you should use a {@link Handler}. 490 * </p> 491 * 492 * <a name="FocusHandling"></a> 493 * <h3>Focus Handling</h3> 494 * <p> 495 * The framework will handle routine focus movement in response to user input. 496 * This includes changing the focus as views are removed or hidden, or as new 497 * views become available. Views indicate their willingness to take focus 498 * through the {@link #isFocusable} method. To change whether a view can take 499 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 500 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 501 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 502 * </p> 503 * <p> 504 * Focus movement is based on an algorithm which finds the nearest neighbor in a 505 * given direction. In rare cases, the default algorithm may not match the 506 * intended behavior of the developer. In these situations, you can provide 507 * explicit overrides by using these XML attributes in the layout file: 508 * <pre> 509 * nextFocusDown 510 * nextFocusLeft 511 * nextFocusRight 512 * nextFocusUp 513 * </pre> 514 * </p> 515 * 516 * 517 * <p> 518 * To get a particular view to take focus, call {@link #requestFocus()}. 519 * </p> 520 * 521 * <a name="TouchMode"></a> 522 * <h3>Touch Mode</h3> 523 * <p> 524 * When a user is navigating a user interface via directional keys such as a D-pad, it is 525 * necessary to give focus to actionable items such as buttons so the user can see 526 * what will take input. If the device has touch capabilities, however, and the user 527 * begins interacting with the interface by touching it, it is no longer necessary to 528 * always highlight, or give focus to, a particular view. This motivates a mode 529 * for interaction named 'touch mode'. 530 * </p> 531 * <p> 532 * For a touch capable device, once the user touches the screen, the device 533 * will enter touch mode. From this point onward, only views for which 534 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 535 * Other views that are touchable, like buttons, will not take focus when touched; they will 536 * only fire the on click listeners. 537 * </p> 538 * <p> 539 * Any time a user hits a directional key, such as a D-pad direction, the view device will 540 * exit touch mode, and find a view to take focus, so that the user may resume interacting 541 * with the user interface without touching the screen again. 542 * </p> 543 * <p> 544 * The touch mode state is maintained across {@link android.app.Activity}s. Call 545 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 546 * </p> 547 * 548 * <a name="Scrolling"></a> 549 * <h3>Scrolling</h3> 550 * <p> 551 * The framework provides basic support for views that wish to internally 552 * scroll their content. This includes keeping track of the X and Y scroll 553 * offset as well as mechanisms for drawing scrollbars. See 554 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 555 * {@link #awakenScrollBars()} for more details. 556 * </p> 557 * 558 * <a name="Tags"></a> 559 * <h3>Tags</h3> 560 * <p> 561 * Unlike IDs, tags are not used to identify views. Tags are essentially an 562 * extra piece of information that can be associated with a view. They are most 563 * often used as a convenience to store data related to views in the views 564 * themselves rather than by putting them in a separate structure. 565 * </p> 566 * 567 * <a name="Properties"></a> 568 * <h3>Properties</h3> 569 * <p> 570 * The View class exposes an {@link #ALPHA} property, as well as several transform-related 571 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are 572 * available both in the {@link Property} form as well as in similarly-named setter/getter 573 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can 574 * be used to set persistent state associated with these rendering-related properties on the view. 575 * The properties and methods can also be used in conjunction with 576 * {@link android.animation.Animator Animator}-based animations, described more in the 577 * <a href="#Animation">Animation</a> section. 578 * </p> 579 * 580 * <a name="Animation"></a> 581 * <h3>Animation</h3> 582 * <p> 583 * Starting with Android 3.0, the preferred way of animating views is to use the 584 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based 585 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and 586 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0 587 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only 588 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class 589 * makes animating these View properties particularly easy and efficient. 590 * </p> 591 * <p> 592 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered. 593 * You can attach an {@link Animation} object to a view using 594 * {@link #setAnimation(Animation)} or 595 * {@link #startAnimation(Animation)}. The animation can alter the scale, 596 * rotation, translation and alpha of a view over time. If the animation is 597 * attached to a view that has children, the animation will affect the entire 598 * subtree rooted by that node. When an animation is started, the framework will 599 * take care of redrawing the appropriate views until the animation completes. 600 * </p> 601 * 602 * <a name="Security"></a> 603 * <h3>Security</h3> 604 * <p> 605 * Sometimes it is essential that an application be able to verify that an action 606 * is being performed with the full knowledge and consent of the user, such as 607 * granting a permission request, making a purchase or clicking on an advertisement. 608 * Unfortunately, a malicious application could try to spoof the user into 609 * performing these actions, unaware, by concealing the intended purpose of the view. 610 * As a remedy, the framework offers a touch filtering mechanism that can be used to 611 * improve the security of views that provide access to sensitive functionality. 612 * </p><p> 613 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 614 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 615 * will discard touches that are received whenever the view's window is obscured by 616 * another visible window. As a result, the view will not receive touches whenever a 617 * toast, dialog or other window appears above the view's window. 618 * </p><p> 619 * For more fine-grained control over security, consider overriding the 620 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 621 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 622 * </p> 623 * 624 * @attr ref android.R.styleable#View_alpha 625 * @attr ref android.R.styleable#View_background 626 * @attr ref android.R.styleable#View_clickable 627 * @attr ref android.R.styleable#View_contentDescription 628 * @attr ref android.R.styleable#View_drawingCacheQuality 629 * @attr ref android.R.styleable#View_duplicateParentState 630 * @attr ref android.R.styleable#View_id 631 * @attr ref android.R.styleable#View_requiresFadingEdge 632 * @attr ref android.R.styleable#View_fadeScrollbars 633 * @attr ref android.R.styleable#View_fadingEdgeLength 634 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 635 * @attr ref android.R.styleable#View_fitsSystemWindows 636 * @attr ref android.R.styleable#View_isScrollContainer 637 * @attr ref android.R.styleable#View_focusable 638 * @attr ref android.R.styleable#View_focusableInTouchMode 639 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 640 * @attr ref android.R.styleable#View_keepScreenOn 641 * @attr ref android.R.styleable#View_layerType 642 * @attr ref android.R.styleable#View_layoutDirection 643 * @attr ref android.R.styleable#View_longClickable 644 * @attr ref android.R.styleable#View_minHeight 645 * @attr ref android.R.styleable#View_minWidth 646 * @attr ref android.R.styleable#View_nextFocusDown 647 * @attr ref android.R.styleable#View_nextFocusLeft 648 * @attr ref android.R.styleable#View_nextFocusRight 649 * @attr ref android.R.styleable#View_nextFocusUp 650 * @attr ref android.R.styleable#View_onClick 651 * @attr ref android.R.styleable#View_padding 652 * @attr ref android.R.styleable#View_paddingBottom 653 * @attr ref android.R.styleable#View_paddingLeft 654 * @attr ref android.R.styleable#View_paddingRight 655 * @attr ref android.R.styleable#View_paddingTop 656 * @attr ref android.R.styleable#View_paddingStart 657 * @attr ref android.R.styleable#View_paddingEnd 658 * @attr ref android.R.styleable#View_saveEnabled 659 * @attr ref android.R.styleable#View_rotation 660 * @attr ref android.R.styleable#View_rotationX 661 * @attr ref android.R.styleable#View_rotationY 662 * @attr ref android.R.styleable#View_scaleX 663 * @attr ref android.R.styleable#View_scaleY 664 * @attr ref android.R.styleable#View_scrollX 665 * @attr ref android.R.styleable#View_scrollY 666 * @attr ref android.R.styleable#View_scrollbarSize 667 * @attr ref android.R.styleable#View_scrollbarStyle 668 * @attr ref android.R.styleable#View_scrollbars 669 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 670 * @attr ref android.R.styleable#View_scrollbarFadeDuration 671 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 672 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 673 * @attr ref android.R.styleable#View_scrollbarThumbVertical 674 * @attr ref android.R.styleable#View_scrollbarTrackVertical 675 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 676 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 677 * @attr ref android.R.styleable#View_stateListAnimator 678 * @attr ref android.R.styleable#View_transitionName 679 * @attr ref android.R.styleable#View_soundEffectsEnabled 680 * @attr ref android.R.styleable#View_tag 681 * @attr ref android.R.styleable#View_textAlignment 682 * @attr ref android.R.styleable#View_textDirection 683 * @attr ref android.R.styleable#View_transformPivotX 684 * @attr ref android.R.styleable#View_transformPivotY 685 * @attr ref android.R.styleable#View_translationX 686 * @attr ref android.R.styleable#View_translationY 687 * @attr ref android.R.styleable#View_translationZ 688 * @attr ref android.R.styleable#View_visibility 689 * 690 * @see android.view.ViewGroup 691 */ 692public class View implements Drawable.Callback, KeyEvent.Callback, 693 AccessibilityEventSource { 694 private static final boolean DBG = false; 695 696 /** 697 * The logging tag used by this class with android.util.Log. 698 */ 699 protected static final String VIEW_LOG_TAG = "View"; 700 701 /** 702 * When set to true, apps will draw debugging information about their layouts. 703 * 704 * @hide 705 */ 706 public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout"; 707 708 /** 709 * When set to true, this view will save its attribute data. 710 * 711 * @hide 712 */ 713 public static boolean mDebugViewAttributes = false; 714 715 /** 716 * Used to mark a View that has no ID. 717 */ 718 public static final int NO_ID = -1; 719 720 /** 721 * Signals that compatibility booleans have been initialized according to 722 * target SDK versions. 723 */ 724 private static boolean sCompatibilityDone = false; 725 726 /** 727 * Use the old (broken) way of building MeasureSpecs. 728 */ 729 private static boolean sUseBrokenMakeMeasureSpec = false; 730 731 /** 732 * Ignore any optimizations using the measure cache. 733 */ 734 private static boolean sIgnoreMeasureCache = false; 735 736 /** 737 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 738 * calling setFlags. 739 */ 740 private static final int NOT_FOCUSABLE = 0x00000000; 741 742 /** 743 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 744 * setFlags. 745 */ 746 private static final int FOCUSABLE = 0x00000001; 747 748 /** 749 * Mask for use with setFlags indicating bits used for focus. 750 */ 751 private static final int FOCUSABLE_MASK = 0x00000001; 752 753 /** 754 * This view will adjust its padding to fit sytem windows (e.g. status bar) 755 */ 756 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 757 758 /** @hide */ 759 @IntDef({VISIBLE, INVISIBLE, GONE}) 760 @Retention(RetentionPolicy.SOURCE) 761 public @interface Visibility {} 762 763 /** 764 * This view is visible. 765 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 766 * android:visibility}. 767 */ 768 public static final int VISIBLE = 0x00000000; 769 770 /** 771 * This view is invisible, but it still takes up space for layout purposes. 772 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 773 * android:visibility}. 774 */ 775 public static final int INVISIBLE = 0x00000004; 776 777 /** 778 * This view is invisible, and it doesn't take any space for layout 779 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 780 * android:visibility}. 781 */ 782 public static final int GONE = 0x00000008; 783 784 /** 785 * Mask for use with setFlags indicating bits used for visibility. 786 * {@hide} 787 */ 788 static final int VISIBILITY_MASK = 0x0000000C; 789 790 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 791 792 /** 793 * This view is enabled. Interpretation varies by subclass. 794 * Use with ENABLED_MASK when calling setFlags. 795 * {@hide} 796 */ 797 static final int ENABLED = 0x00000000; 798 799 /** 800 * This view is disabled. Interpretation varies by subclass. 801 * Use with ENABLED_MASK when calling setFlags. 802 * {@hide} 803 */ 804 static final int DISABLED = 0x00000020; 805 806 /** 807 * Mask for use with setFlags indicating bits used for indicating whether 808 * this view is enabled 809 * {@hide} 810 */ 811 static final int ENABLED_MASK = 0x00000020; 812 813 /** 814 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 815 * called and further optimizations will be performed. It is okay to have 816 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 817 * {@hide} 818 */ 819 static final int WILL_NOT_DRAW = 0x00000080; 820 821 /** 822 * Mask for use with setFlags indicating bits used for indicating whether 823 * this view is will draw 824 * {@hide} 825 */ 826 static final int DRAW_MASK = 0x00000080; 827 828 /** 829 * <p>This view doesn't show scrollbars.</p> 830 * {@hide} 831 */ 832 static final int SCROLLBARS_NONE = 0x00000000; 833 834 /** 835 * <p>This view shows horizontal scrollbars.</p> 836 * {@hide} 837 */ 838 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 839 840 /** 841 * <p>This view shows vertical scrollbars.</p> 842 * {@hide} 843 */ 844 static final int SCROLLBARS_VERTICAL = 0x00000200; 845 846 /** 847 * <p>Mask for use with setFlags indicating bits used for indicating which 848 * scrollbars are enabled.</p> 849 * {@hide} 850 */ 851 static final int SCROLLBARS_MASK = 0x00000300; 852 853 /** 854 * Indicates that the view should filter touches when its window is obscured. 855 * Refer to the class comments for more information about this security feature. 856 * {@hide} 857 */ 858 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 859 860 /** 861 * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate 862 * that they are optional and should be skipped if the window has 863 * requested system UI flags that ignore those insets for layout. 864 */ 865 static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800; 866 867 /** 868 * <p>This view doesn't show fading edges.</p> 869 * {@hide} 870 */ 871 static final int FADING_EDGE_NONE = 0x00000000; 872 873 /** 874 * <p>This view shows horizontal fading edges.</p> 875 * {@hide} 876 */ 877 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 878 879 /** 880 * <p>This view shows vertical fading edges.</p> 881 * {@hide} 882 */ 883 static final int FADING_EDGE_VERTICAL = 0x00002000; 884 885 /** 886 * <p>Mask for use with setFlags indicating bits used for indicating which 887 * fading edges are enabled.</p> 888 * {@hide} 889 */ 890 static final int FADING_EDGE_MASK = 0x00003000; 891 892 /** 893 * <p>Indicates this view can be clicked. When clickable, a View reacts 894 * to clicks by notifying the OnClickListener.<p> 895 * {@hide} 896 */ 897 static final int CLICKABLE = 0x00004000; 898 899 /** 900 * <p>Indicates this view is caching its drawing into a bitmap.</p> 901 * {@hide} 902 */ 903 static final int DRAWING_CACHE_ENABLED = 0x00008000; 904 905 /** 906 * <p>Indicates that no icicle should be saved for this view.<p> 907 * {@hide} 908 */ 909 static final int SAVE_DISABLED = 0x000010000; 910 911 /** 912 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 913 * property.</p> 914 * {@hide} 915 */ 916 static final int SAVE_DISABLED_MASK = 0x000010000; 917 918 /** 919 * <p>Indicates that no drawing cache should ever be created for this view.<p> 920 * {@hide} 921 */ 922 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 923 924 /** 925 * <p>Indicates this view can take / keep focus when int touch mode.</p> 926 * {@hide} 927 */ 928 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 929 930 /** @hide */ 931 @Retention(RetentionPolicy.SOURCE) 932 @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO}) 933 public @interface DrawingCacheQuality {} 934 935 /** 936 * <p>Enables low quality mode for the drawing cache.</p> 937 */ 938 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 939 940 /** 941 * <p>Enables high quality mode for the drawing cache.</p> 942 */ 943 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 944 945 /** 946 * <p>Enables automatic quality mode for the drawing cache.</p> 947 */ 948 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 949 950 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 951 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 952 }; 953 954 /** 955 * <p>Mask for use with setFlags indicating bits used for the cache 956 * quality property.</p> 957 * {@hide} 958 */ 959 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 960 961 /** 962 * <p> 963 * Indicates this view can be long clicked. When long clickable, a View 964 * reacts to long clicks by notifying the OnLongClickListener or showing a 965 * context menu. 966 * </p> 967 * {@hide} 968 */ 969 static final int LONG_CLICKABLE = 0x00200000; 970 971 /** 972 * <p>Indicates that this view gets its drawable states from its direct parent 973 * and ignores its original internal states.</p> 974 * 975 * @hide 976 */ 977 static final int DUPLICATE_PARENT_STATE = 0x00400000; 978 979 /** @hide */ 980 @IntDef({ 981 SCROLLBARS_INSIDE_OVERLAY, 982 SCROLLBARS_INSIDE_INSET, 983 SCROLLBARS_OUTSIDE_OVERLAY, 984 SCROLLBARS_OUTSIDE_INSET 985 }) 986 @Retention(RetentionPolicy.SOURCE) 987 public @interface ScrollBarStyle {} 988 989 /** 990 * The scrollbar style to display the scrollbars inside the content area, 991 * without increasing the padding. The scrollbars will be overlaid with 992 * translucency on the view's content. 993 */ 994 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 995 996 /** 997 * The scrollbar style to display the scrollbars inside the padded area, 998 * increasing the padding of the view. The scrollbars will not overlap the 999 * content area of the view. 1000 */ 1001 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 1002 1003 /** 1004 * The scrollbar style to display the scrollbars at the edge of the view, 1005 * without increasing the padding. The scrollbars will be overlaid with 1006 * translucency. 1007 */ 1008 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 1009 1010 /** 1011 * The scrollbar style to display the scrollbars at the edge of the view, 1012 * increasing the padding of the view. The scrollbars will only overlap the 1013 * background, if any. 1014 */ 1015 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 1016 1017 /** 1018 * Mask to check if the scrollbar style is overlay or inset. 1019 * {@hide} 1020 */ 1021 static final int SCROLLBARS_INSET_MASK = 0x01000000; 1022 1023 /** 1024 * Mask to check if the scrollbar style is inside or outside. 1025 * {@hide} 1026 */ 1027 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 1028 1029 /** 1030 * Mask for scrollbar style. 1031 * {@hide} 1032 */ 1033 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 1034 1035 /** 1036 * View flag indicating that the screen should remain on while the 1037 * window containing this view is visible to the user. This effectively 1038 * takes care of automatically setting the WindowManager's 1039 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 1040 */ 1041 public static final int KEEP_SCREEN_ON = 0x04000000; 1042 1043 /** 1044 * View flag indicating whether this view should have sound effects enabled 1045 * for events such as clicking and touching. 1046 */ 1047 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 1048 1049 /** 1050 * View flag indicating whether this view should have haptic feedback 1051 * enabled for events such as long presses. 1052 */ 1053 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 1054 1055 /** 1056 * <p>Indicates that the view hierarchy should stop saving state when 1057 * it reaches this view. If state saving is initiated immediately at 1058 * the view, it will be allowed. 1059 * {@hide} 1060 */ 1061 static final int PARENT_SAVE_DISABLED = 0x20000000; 1062 1063 /** 1064 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 1065 * {@hide} 1066 */ 1067 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 1068 1069 /** @hide */ 1070 @IntDef(flag = true, 1071 value = { 1072 FOCUSABLES_ALL, 1073 FOCUSABLES_TOUCH_MODE 1074 }) 1075 @Retention(RetentionPolicy.SOURCE) 1076 public @interface FocusableMode {} 1077 1078 /** 1079 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1080 * should add all focusable Views regardless if they are focusable in touch mode. 1081 */ 1082 public static final int FOCUSABLES_ALL = 0x00000000; 1083 1084 /** 1085 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1086 * should add only Views focusable in touch mode. 1087 */ 1088 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 1089 1090 /** @hide */ 1091 @IntDef({ 1092 FOCUS_BACKWARD, 1093 FOCUS_FORWARD, 1094 FOCUS_LEFT, 1095 FOCUS_UP, 1096 FOCUS_RIGHT, 1097 FOCUS_DOWN 1098 }) 1099 @Retention(RetentionPolicy.SOURCE) 1100 public @interface FocusDirection {} 1101 1102 /** @hide */ 1103 @IntDef({ 1104 FOCUS_LEFT, 1105 FOCUS_UP, 1106 FOCUS_RIGHT, 1107 FOCUS_DOWN 1108 }) 1109 @Retention(RetentionPolicy.SOURCE) 1110 public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward 1111 1112 /** 1113 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 1114 * item. 1115 */ 1116 public static final int FOCUS_BACKWARD = 0x00000001; 1117 1118 /** 1119 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 1120 * item. 1121 */ 1122 public static final int FOCUS_FORWARD = 0x00000002; 1123 1124 /** 1125 * Use with {@link #focusSearch(int)}. Move focus to the left. 1126 */ 1127 public static final int FOCUS_LEFT = 0x00000011; 1128 1129 /** 1130 * Use with {@link #focusSearch(int)}. Move focus up. 1131 */ 1132 public static final int FOCUS_UP = 0x00000021; 1133 1134 /** 1135 * Use with {@link #focusSearch(int)}. Move focus to the right. 1136 */ 1137 public static final int FOCUS_RIGHT = 0x00000042; 1138 1139 /** 1140 * Use with {@link #focusSearch(int)}. Move focus down. 1141 */ 1142 public static final int FOCUS_DOWN = 0x00000082; 1143 1144 /** 1145 * Bits of {@link #getMeasuredWidthAndState()} and 1146 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1147 */ 1148 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1149 1150 /** 1151 * Bits of {@link #getMeasuredWidthAndState()} and 1152 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1153 */ 1154 public static final int MEASURED_STATE_MASK = 0xff000000; 1155 1156 /** 1157 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1158 * for functions that combine both width and height into a single int, 1159 * such as {@link #getMeasuredState()} and the childState argument of 1160 * {@link #resolveSizeAndState(int, int, int)}. 1161 */ 1162 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1163 1164 /** 1165 * Bit of {@link #getMeasuredWidthAndState()} and 1166 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1167 * is smaller that the space the view would like to have. 1168 */ 1169 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1170 1171 /** 1172 * Base View state sets 1173 */ 1174 // Singles 1175 /** 1176 * Indicates the view has no states set. States are used with 1177 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1178 * view depending on its state. 1179 * 1180 * @see android.graphics.drawable.Drawable 1181 * @see #getDrawableState() 1182 */ 1183 protected static final int[] EMPTY_STATE_SET; 1184 /** 1185 * Indicates the view is enabled. States are used with 1186 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1187 * view depending on its state. 1188 * 1189 * @see android.graphics.drawable.Drawable 1190 * @see #getDrawableState() 1191 */ 1192 protected static final int[] ENABLED_STATE_SET; 1193 /** 1194 * Indicates the view is focused. States are used with 1195 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1196 * view depending on its state. 1197 * 1198 * @see android.graphics.drawable.Drawable 1199 * @see #getDrawableState() 1200 */ 1201 protected static final int[] FOCUSED_STATE_SET; 1202 /** 1203 * Indicates the view is selected. States are used with 1204 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1205 * view depending on its state. 1206 * 1207 * @see android.graphics.drawable.Drawable 1208 * @see #getDrawableState() 1209 */ 1210 protected static final int[] SELECTED_STATE_SET; 1211 /** 1212 * Indicates the view is pressed. States are used with 1213 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1214 * view depending on its state. 1215 * 1216 * @see android.graphics.drawable.Drawable 1217 * @see #getDrawableState() 1218 */ 1219 protected static final int[] PRESSED_STATE_SET; 1220 /** 1221 * Indicates the view's window has focus. States are used with 1222 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1223 * view depending on its state. 1224 * 1225 * @see android.graphics.drawable.Drawable 1226 * @see #getDrawableState() 1227 */ 1228 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1229 // Doubles 1230 /** 1231 * Indicates the view is enabled and has the focus. 1232 * 1233 * @see #ENABLED_STATE_SET 1234 * @see #FOCUSED_STATE_SET 1235 */ 1236 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1237 /** 1238 * Indicates the view is enabled and selected. 1239 * 1240 * @see #ENABLED_STATE_SET 1241 * @see #SELECTED_STATE_SET 1242 */ 1243 protected static final int[] ENABLED_SELECTED_STATE_SET; 1244 /** 1245 * Indicates the view is enabled and that its window has focus. 1246 * 1247 * @see #ENABLED_STATE_SET 1248 * @see #WINDOW_FOCUSED_STATE_SET 1249 */ 1250 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1251 /** 1252 * Indicates the view is focused and selected. 1253 * 1254 * @see #FOCUSED_STATE_SET 1255 * @see #SELECTED_STATE_SET 1256 */ 1257 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1258 /** 1259 * Indicates the view has the focus and that its window has the focus. 1260 * 1261 * @see #FOCUSED_STATE_SET 1262 * @see #WINDOW_FOCUSED_STATE_SET 1263 */ 1264 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1265 /** 1266 * Indicates the view is selected and that its window has the focus. 1267 * 1268 * @see #SELECTED_STATE_SET 1269 * @see #WINDOW_FOCUSED_STATE_SET 1270 */ 1271 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1272 // Triples 1273 /** 1274 * Indicates the view is enabled, focused and selected. 1275 * 1276 * @see #ENABLED_STATE_SET 1277 * @see #FOCUSED_STATE_SET 1278 * @see #SELECTED_STATE_SET 1279 */ 1280 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1281 /** 1282 * Indicates the view is enabled, focused and its window has the focus. 1283 * 1284 * @see #ENABLED_STATE_SET 1285 * @see #FOCUSED_STATE_SET 1286 * @see #WINDOW_FOCUSED_STATE_SET 1287 */ 1288 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1289 /** 1290 * Indicates the view is enabled, selected and its window has the focus. 1291 * 1292 * @see #ENABLED_STATE_SET 1293 * @see #SELECTED_STATE_SET 1294 * @see #WINDOW_FOCUSED_STATE_SET 1295 */ 1296 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1297 /** 1298 * Indicates the view is focused, selected and its window has the focus. 1299 * 1300 * @see #FOCUSED_STATE_SET 1301 * @see #SELECTED_STATE_SET 1302 * @see #WINDOW_FOCUSED_STATE_SET 1303 */ 1304 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1305 /** 1306 * Indicates the view is enabled, focused, selected and its window 1307 * has the focus. 1308 * 1309 * @see #ENABLED_STATE_SET 1310 * @see #FOCUSED_STATE_SET 1311 * @see #SELECTED_STATE_SET 1312 * @see #WINDOW_FOCUSED_STATE_SET 1313 */ 1314 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1315 /** 1316 * Indicates the view is pressed and its window has the focus. 1317 * 1318 * @see #PRESSED_STATE_SET 1319 * @see #WINDOW_FOCUSED_STATE_SET 1320 */ 1321 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1322 /** 1323 * Indicates the view is pressed and selected. 1324 * 1325 * @see #PRESSED_STATE_SET 1326 * @see #SELECTED_STATE_SET 1327 */ 1328 protected static final int[] PRESSED_SELECTED_STATE_SET; 1329 /** 1330 * Indicates the view is pressed, selected and its window has the focus. 1331 * 1332 * @see #PRESSED_STATE_SET 1333 * @see #SELECTED_STATE_SET 1334 * @see #WINDOW_FOCUSED_STATE_SET 1335 */ 1336 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1337 /** 1338 * Indicates the view is pressed and focused. 1339 * 1340 * @see #PRESSED_STATE_SET 1341 * @see #FOCUSED_STATE_SET 1342 */ 1343 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1344 /** 1345 * Indicates the view is pressed, focused and its window has the focus. 1346 * 1347 * @see #PRESSED_STATE_SET 1348 * @see #FOCUSED_STATE_SET 1349 * @see #WINDOW_FOCUSED_STATE_SET 1350 */ 1351 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1352 /** 1353 * Indicates the view is pressed, focused and selected. 1354 * 1355 * @see #PRESSED_STATE_SET 1356 * @see #SELECTED_STATE_SET 1357 * @see #FOCUSED_STATE_SET 1358 */ 1359 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1360 /** 1361 * Indicates the view is pressed, focused, selected and its window has the focus. 1362 * 1363 * @see #PRESSED_STATE_SET 1364 * @see #FOCUSED_STATE_SET 1365 * @see #SELECTED_STATE_SET 1366 * @see #WINDOW_FOCUSED_STATE_SET 1367 */ 1368 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1369 /** 1370 * Indicates the view is pressed and enabled. 1371 * 1372 * @see #PRESSED_STATE_SET 1373 * @see #ENABLED_STATE_SET 1374 */ 1375 protected static final int[] PRESSED_ENABLED_STATE_SET; 1376 /** 1377 * Indicates the view is pressed, enabled and its window has the focus. 1378 * 1379 * @see #PRESSED_STATE_SET 1380 * @see #ENABLED_STATE_SET 1381 * @see #WINDOW_FOCUSED_STATE_SET 1382 */ 1383 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1384 /** 1385 * Indicates the view is pressed, enabled and selected. 1386 * 1387 * @see #PRESSED_STATE_SET 1388 * @see #ENABLED_STATE_SET 1389 * @see #SELECTED_STATE_SET 1390 */ 1391 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1392 /** 1393 * Indicates the view is pressed, enabled, selected and its window has the 1394 * focus. 1395 * 1396 * @see #PRESSED_STATE_SET 1397 * @see #ENABLED_STATE_SET 1398 * @see #SELECTED_STATE_SET 1399 * @see #WINDOW_FOCUSED_STATE_SET 1400 */ 1401 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1402 /** 1403 * Indicates the view is pressed, enabled and focused. 1404 * 1405 * @see #PRESSED_STATE_SET 1406 * @see #ENABLED_STATE_SET 1407 * @see #FOCUSED_STATE_SET 1408 */ 1409 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1410 /** 1411 * Indicates the view is pressed, enabled, focused and its window has the 1412 * focus. 1413 * 1414 * @see #PRESSED_STATE_SET 1415 * @see #ENABLED_STATE_SET 1416 * @see #FOCUSED_STATE_SET 1417 * @see #WINDOW_FOCUSED_STATE_SET 1418 */ 1419 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1420 /** 1421 * Indicates the view is pressed, enabled, focused and selected. 1422 * 1423 * @see #PRESSED_STATE_SET 1424 * @see #ENABLED_STATE_SET 1425 * @see #SELECTED_STATE_SET 1426 * @see #FOCUSED_STATE_SET 1427 */ 1428 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1429 /** 1430 * Indicates the view is pressed, enabled, focused, selected and its window 1431 * has the focus. 1432 * 1433 * @see #PRESSED_STATE_SET 1434 * @see #ENABLED_STATE_SET 1435 * @see #SELECTED_STATE_SET 1436 * @see #FOCUSED_STATE_SET 1437 * @see #WINDOW_FOCUSED_STATE_SET 1438 */ 1439 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1440 1441 /** 1442 * The order here is very important to {@link #getDrawableState()} 1443 */ 1444 private static final int[][] VIEW_STATE_SETS; 1445 1446 static final int VIEW_STATE_WINDOW_FOCUSED = 1; 1447 static final int VIEW_STATE_SELECTED = 1 << 1; 1448 static final int VIEW_STATE_FOCUSED = 1 << 2; 1449 static final int VIEW_STATE_ENABLED = 1 << 3; 1450 static final int VIEW_STATE_PRESSED = 1 << 4; 1451 static final int VIEW_STATE_ACTIVATED = 1 << 5; 1452 static final int VIEW_STATE_ACCELERATED = 1 << 6; 1453 static final int VIEW_STATE_HOVERED = 1 << 7; 1454 static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8; 1455 static final int VIEW_STATE_DRAG_HOVERED = 1 << 9; 1456 1457 static final int[] VIEW_STATE_IDS = new int[] { 1458 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED, 1459 R.attr.state_selected, VIEW_STATE_SELECTED, 1460 R.attr.state_focused, VIEW_STATE_FOCUSED, 1461 R.attr.state_enabled, VIEW_STATE_ENABLED, 1462 R.attr.state_pressed, VIEW_STATE_PRESSED, 1463 R.attr.state_activated, VIEW_STATE_ACTIVATED, 1464 R.attr.state_accelerated, VIEW_STATE_ACCELERATED, 1465 R.attr.state_hovered, VIEW_STATE_HOVERED, 1466 R.attr.state_drag_can_accept, VIEW_STATE_DRAG_CAN_ACCEPT, 1467 R.attr.state_drag_hovered, VIEW_STATE_DRAG_HOVERED 1468 }; 1469 1470 static { 1471 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) { 1472 throw new IllegalStateException( 1473 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array"); 1474 } 1475 int[] orderedIds = new int[VIEW_STATE_IDS.length]; 1476 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) { 1477 int viewState = R.styleable.ViewDrawableStates[i]; 1478 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) { 1479 if (VIEW_STATE_IDS[j] == viewState) { 1480 orderedIds[i * 2] = viewState; 1481 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1]; 1482 } 1483 } 1484 } 1485 final int NUM_BITS = VIEW_STATE_IDS.length / 2; 1486 VIEW_STATE_SETS = new int[1 << NUM_BITS][]; 1487 for (int i = 0; i < VIEW_STATE_SETS.length; i++) { 1488 int numBits = Integer.bitCount(i); 1489 int[] set = new int[numBits]; 1490 int pos = 0; 1491 for (int j = 0; j < orderedIds.length; j += 2) { 1492 if ((i & orderedIds[j+1]) != 0) { 1493 set[pos++] = orderedIds[j]; 1494 } 1495 } 1496 VIEW_STATE_SETS[i] = set; 1497 } 1498 1499 EMPTY_STATE_SET = VIEW_STATE_SETS[0]; 1500 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED]; 1501 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED]; 1502 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1503 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED]; 1504 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED]; 1505 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1506 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED]; 1507 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1508 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED]; 1509 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1510 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1511 | VIEW_STATE_FOCUSED]; 1512 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED]; 1513 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1514 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED]; 1515 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1516 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED]; 1517 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1518 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1519 | VIEW_STATE_ENABLED]; 1520 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1521 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED]; 1522 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1523 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1524 | VIEW_STATE_ENABLED]; 1525 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1526 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1527 | VIEW_STATE_ENABLED]; 1528 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1529 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1530 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED]; 1531 1532 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED]; 1533 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1534 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED]; 1535 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1536 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED]; 1537 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1538 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1539 | VIEW_STATE_PRESSED]; 1540 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1541 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1542 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1543 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1544 | VIEW_STATE_PRESSED]; 1545 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1546 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1547 | VIEW_STATE_PRESSED]; 1548 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1549 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1550 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1551 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[ 1552 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1553 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1554 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED 1555 | VIEW_STATE_PRESSED]; 1556 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1557 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED 1558 | VIEW_STATE_PRESSED]; 1559 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1560 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1561 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1562 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1563 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED 1564 | VIEW_STATE_PRESSED]; 1565 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1566 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1567 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1568 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1569 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1570 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1571 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1572 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1573 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED 1574 | VIEW_STATE_PRESSED]; 1575 } 1576 1577 /** 1578 * Accessibility event types that are dispatched for text population. 1579 */ 1580 private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES = 1581 AccessibilityEvent.TYPE_VIEW_CLICKED 1582 | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED 1583 | AccessibilityEvent.TYPE_VIEW_SELECTED 1584 | AccessibilityEvent.TYPE_VIEW_FOCUSED 1585 | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED 1586 | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER 1587 | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT 1588 | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED 1589 | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED 1590 | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED 1591 | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY; 1592 1593 /** 1594 * Temporary Rect currently for use in setBackground(). This will probably 1595 * be extended in the future to hold our own class with more than just 1596 * a Rect. :) 1597 */ 1598 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1599 1600 /** 1601 * Map used to store views' tags. 1602 */ 1603 private SparseArray<Object> mKeyedTags; 1604 1605 /** 1606 * The next available accessibility id. 1607 */ 1608 private static int sNextAccessibilityViewId; 1609 1610 /** 1611 * The animation currently associated with this view. 1612 * @hide 1613 */ 1614 protected Animation mCurrentAnimation = null; 1615 1616 /** 1617 * Width as measured during measure pass. 1618 * {@hide} 1619 */ 1620 @ViewDebug.ExportedProperty(category = "measurement") 1621 int mMeasuredWidth; 1622 1623 /** 1624 * Height as measured during measure pass. 1625 * {@hide} 1626 */ 1627 @ViewDebug.ExportedProperty(category = "measurement") 1628 int mMeasuredHeight; 1629 1630 /** 1631 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1632 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1633 * its display list. This flag, used only when hw accelerated, allows us to clear the 1634 * flag while retaining this information until it's needed (at getDisplayList() time and 1635 * in drawChild(), when we decide to draw a view's children's display lists into our own). 1636 * 1637 * {@hide} 1638 */ 1639 boolean mRecreateDisplayList = false; 1640 1641 /** 1642 * The view's identifier. 1643 * {@hide} 1644 * 1645 * @see #setId(int) 1646 * @see #getId() 1647 */ 1648 @ViewDebug.ExportedProperty(resolveId = true) 1649 int mID = NO_ID; 1650 1651 /** 1652 * The stable ID of this view for accessibility purposes. 1653 */ 1654 int mAccessibilityViewId = NO_ID; 1655 1656 private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 1657 1658 SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent; 1659 1660 /** 1661 * The view's tag. 1662 * {@hide} 1663 * 1664 * @see #setTag(Object) 1665 * @see #getTag() 1666 */ 1667 protected Object mTag = null; 1668 1669 // for mPrivateFlags: 1670 /** {@hide} */ 1671 static final int PFLAG_WANTS_FOCUS = 0x00000001; 1672 /** {@hide} */ 1673 static final int PFLAG_FOCUSED = 0x00000002; 1674 /** {@hide} */ 1675 static final int PFLAG_SELECTED = 0x00000004; 1676 /** {@hide} */ 1677 static final int PFLAG_IS_ROOT_NAMESPACE = 0x00000008; 1678 /** {@hide} */ 1679 static final int PFLAG_HAS_BOUNDS = 0x00000010; 1680 /** {@hide} */ 1681 static final int PFLAG_DRAWN = 0x00000020; 1682 /** 1683 * When this flag is set, this view is running an animation on behalf of its 1684 * children and should therefore not cancel invalidate requests, even if they 1685 * lie outside of this view's bounds. 1686 * 1687 * {@hide} 1688 */ 1689 static final int PFLAG_DRAW_ANIMATION = 0x00000040; 1690 /** {@hide} */ 1691 static final int PFLAG_SKIP_DRAW = 0x00000080; 1692 /** {@hide} */ 1693 static final int PFLAG_ONLY_DRAWS_BACKGROUND = 0x00000100; 1694 /** {@hide} */ 1695 static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1696 /** {@hide} */ 1697 static final int PFLAG_DRAWABLE_STATE_DIRTY = 0x00000400; 1698 /** {@hide} */ 1699 static final int PFLAG_MEASURED_DIMENSION_SET = 0x00000800; 1700 /** {@hide} */ 1701 static final int PFLAG_FORCE_LAYOUT = 0x00001000; 1702 /** {@hide} */ 1703 static final int PFLAG_LAYOUT_REQUIRED = 0x00002000; 1704 1705 private static final int PFLAG_PRESSED = 0x00004000; 1706 1707 /** {@hide} */ 1708 static final int PFLAG_DRAWING_CACHE_VALID = 0x00008000; 1709 /** 1710 * Flag used to indicate that this view should be drawn once more (and only once 1711 * more) after its animation has completed. 1712 * {@hide} 1713 */ 1714 static final int PFLAG_ANIMATION_STARTED = 0x00010000; 1715 1716 private static final int PFLAG_SAVE_STATE_CALLED = 0x00020000; 1717 1718 /** 1719 * Indicates that the View returned true when onSetAlpha() was called and that 1720 * the alpha must be restored. 1721 * {@hide} 1722 */ 1723 static final int PFLAG_ALPHA_SET = 0x00040000; 1724 1725 /** 1726 * Set by {@link #setScrollContainer(boolean)}. 1727 */ 1728 static final int PFLAG_SCROLL_CONTAINER = 0x00080000; 1729 1730 /** 1731 * Set by {@link #setScrollContainer(boolean)}. 1732 */ 1733 static final int PFLAG_SCROLL_CONTAINER_ADDED = 0x00100000; 1734 1735 /** 1736 * View flag indicating whether this view was invalidated (fully or partially.) 1737 * 1738 * @hide 1739 */ 1740 static final int PFLAG_DIRTY = 0x00200000; 1741 1742 /** 1743 * View flag indicating whether this view was invalidated by an opaque 1744 * invalidate request. 1745 * 1746 * @hide 1747 */ 1748 static final int PFLAG_DIRTY_OPAQUE = 0x00400000; 1749 1750 /** 1751 * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}. 1752 * 1753 * @hide 1754 */ 1755 static final int PFLAG_DIRTY_MASK = 0x00600000; 1756 1757 /** 1758 * Indicates whether the background is opaque. 1759 * 1760 * @hide 1761 */ 1762 static final int PFLAG_OPAQUE_BACKGROUND = 0x00800000; 1763 1764 /** 1765 * Indicates whether the scrollbars are opaque. 1766 * 1767 * @hide 1768 */ 1769 static final int PFLAG_OPAQUE_SCROLLBARS = 0x01000000; 1770 1771 /** 1772 * Indicates whether the view is opaque. 1773 * 1774 * @hide 1775 */ 1776 static final int PFLAG_OPAQUE_MASK = 0x01800000; 1777 1778 /** 1779 * Indicates a prepressed state; 1780 * the short time between ACTION_DOWN and recognizing 1781 * a 'real' press. Prepressed is used to recognize quick taps 1782 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1783 * 1784 * @hide 1785 */ 1786 private static final int PFLAG_PREPRESSED = 0x02000000; 1787 1788 /** 1789 * Indicates whether the view is temporarily detached. 1790 * 1791 * @hide 1792 */ 1793 static final int PFLAG_CANCEL_NEXT_UP_EVENT = 0x04000000; 1794 1795 /** 1796 * Indicates that we should awaken scroll bars once attached 1797 * 1798 * @hide 1799 */ 1800 private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1801 1802 /** 1803 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 1804 * @hide 1805 */ 1806 private static final int PFLAG_HOVERED = 0x10000000; 1807 1808 /** 1809 * no longer needed, should be reused 1810 */ 1811 private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000; 1812 1813 /** {@hide} */ 1814 static final int PFLAG_ACTIVATED = 0x40000000; 1815 1816 /** 1817 * Indicates that this view was specifically invalidated, not just dirtied because some 1818 * child view was invalidated. The flag is used to determine when we need to recreate 1819 * a view's display list (as opposed to just returning a reference to its existing 1820 * display list). 1821 * 1822 * @hide 1823 */ 1824 static final int PFLAG_INVALIDATED = 0x80000000; 1825 1826 /** 1827 * Masks for mPrivateFlags2, as generated by dumpFlags(): 1828 * 1829 * |-------|-------|-------|-------| 1830 * 1 PFLAG2_DRAG_CAN_ACCEPT 1831 * 1 PFLAG2_DRAG_HOVERED 1832 * 11 PFLAG2_LAYOUT_DIRECTION_MASK 1833 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL 1834 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED 1835 * 11 PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK 1836 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[1] 1837 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[2] 1838 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[3] 1839 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[4] 1840 * 1 1 PFLAG2_TEXT_DIRECTION_FLAGS[5] 1841 * 111 PFLAG2_TEXT_DIRECTION_MASK 1842 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED 1843 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT 1844 * 111 PFLAG2_TEXT_DIRECTION_RESOLVED_MASK 1845 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[1] 1846 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[2] 1847 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[3] 1848 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[4] 1849 * 1 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[5] 1850 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[6] 1851 * 111 PFLAG2_TEXT_ALIGNMENT_MASK 1852 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED 1853 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT 1854 * 111 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK 1855 * 111 PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK 1856 * 11 PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK 1857 * 1 PFLAG2_ACCESSIBILITY_FOCUSED 1858 * 1 PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED 1859 * 1 PFLAG2_VIEW_QUICK_REJECTED 1860 * 1 PFLAG2_PADDING_RESOLVED 1861 * 1 PFLAG2_DRAWABLE_RESOLVED 1862 * 1 PFLAG2_HAS_TRANSIENT_STATE 1863 * |-------|-------|-------|-------| 1864 */ 1865 1866 /** 1867 * Indicates that this view has reported that it can accept the current drag's content. 1868 * Cleared when the drag operation concludes. 1869 * @hide 1870 */ 1871 static final int PFLAG2_DRAG_CAN_ACCEPT = 0x00000001; 1872 1873 /** 1874 * Indicates that this view is currently directly under the drag location in a 1875 * drag-and-drop operation involving content that it can accept. Cleared when 1876 * the drag exits the view, or when the drag operation concludes. 1877 * @hide 1878 */ 1879 static final int PFLAG2_DRAG_HOVERED = 0x00000002; 1880 1881 /** @hide */ 1882 @IntDef({ 1883 LAYOUT_DIRECTION_LTR, 1884 LAYOUT_DIRECTION_RTL, 1885 LAYOUT_DIRECTION_INHERIT, 1886 LAYOUT_DIRECTION_LOCALE 1887 }) 1888 @Retention(RetentionPolicy.SOURCE) 1889 // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection 1890 public @interface LayoutDir {} 1891 1892 /** @hide */ 1893 @IntDef({ 1894 LAYOUT_DIRECTION_LTR, 1895 LAYOUT_DIRECTION_RTL 1896 }) 1897 @Retention(RetentionPolicy.SOURCE) 1898 public @interface ResolvedLayoutDir {} 1899 1900 /** 1901 * Horizontal layout direction of this view is from Left to Right. 1902 * Use with {@link #setLayoutDirection}. 1903 */ 1904 public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR; 1905 1906 /** 1907 * Horizontal layout direction of this view is from Right to Left. 1908 * Use with {@link #setLayoutDirection}. 1909 */ 1910 public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL; 1911 1912 /** 1913 * Horizontal layout direction of this view is inherited from its parent. 1914 * Use with {@link #setLayoutDirection}. 1915 */ 1916 public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT; 1917 1918 /** 1919 * Horizontal layout direction of this view is from deduced from the default language 1920 * script for the locale. Use with {@link #setLayoutDirection}. 1921 */ 1922 public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE; 1923 1924 /** 1925 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 1926 * @hide 1927 */ 1928 static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2; 1929 1930 /** 1931 * Mask for use with private flags indicating bits used for horizontal layout direction. 1932 * @hide 1933 */ 1934 static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1935 1936 /** 1937 * Indicates whether the view horizontal layout direction has been resolved and drawn to the 1938 * right-to-left direction. 1939 * @hide 1940 */ 1941 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1942 1943 /** 1944 * Indicates whether the view horizontal layout direction has been resolved. 1945 * @hide 1946 */ 1947 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1948 1949 /** 1950 * Mask for use with private flags indicating bits used for resolved horizontal layout direction. 1951 * @hide 1952 */ 1953 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C 1954 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1955 1956 /* 1957 * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct 1958 * flag value. 1959 * @hide 1960 */ 1961 private static final int[] LAYOUT_DIRECTION_FLAGS = { 1962 LAYOUT_DIRECTION_LTR, 1963 LAYOUT_DIRECTION_RTL, 1964 LAYOUT_DIRECTION_INHERIT, 1965 LAYOUT_DIRECTION_LOCALE 1966 }; 1967 1968 /** 1969 * Default horizontal layout direction. 1970 */ 1971 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 1972 1973 /** 1974 * Default horizontal layout direction. 1975 * @hide 1976 */ 1977 static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR; 1978 1979 /** 1980 * Text direction is inherited thru {@link ViewGroup} 1981 */ 1982 public static final int TEXT_DIRECTION_INHERIT = 0; 1983 1984 /** 1985 * Text direction is using "first strong algorithm". The first strong directional character 1986 * determines the paragraph direction. If there is no strong directional character, the 1987 * paragraph direction is the view's resolved layout direction. 1988 */ 1989 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 1990 1991 /** 1992 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 1993 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 1994 * If there are neither, the paragraph direction is the view's resolved layout direction. 1995 */ 1996 public static final int TEXT_DIRECTION_ANY_RTL = 2; 1997 1998 /** 1999 * Text direction is forced to LTR. 2000 */ 2001 public static final int TEXT_DIRECTION_LTR = 3; 2002 2003 /** 2004 * Text direction is forced to RTL. 2005 */ 2006 public static final int TEXT_DIRECTION_RTL = 4; 2007 2008 /** 2009 * Text direction is coming from the system Locale. 2010 */ 2011 public static final int TEXT_DIRECTION_LOCALE = 5; 2012 2013 /** 2014 * Default text direction is inherited 2015 */ 2016 private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT; 2017 2018 /** 2019 * Default resolved text direction 2020 * @hide 2021 */ 2022 static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG; 2023 2024 /** 2025 * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED) 2026 * @hide 2027 */ 2028 static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6; 2029 2030 /** 2031 * Mask for use with private flags indicating bits used for text direction. 2032 * @hide 2033 */ 2034 static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007 2035 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2036 2037 /** 2038 * Array of text direction flags for mapping attribute "textDirection" to correct 2039 * flag value. 2040 * @hide 2041 */ 2042 private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = { 2043 TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2044 TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2045 TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2046 TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2047 TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2048 TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT 2049 }; 2050 2051 /** 2052 * Indicates whether the view text direction has been resolved. 2053 * @hide 2054 */ 2055 static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008 2056 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2057 2058 /** 2059 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2060 * @hide 2061 */ 2062 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10; 2063 2064 /** 2065 * Mask for use with private flags indicating bits used for resolved text direction. 2066 * @hide 2067 */ 2068 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 2069 << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2070 2071 /** 2072 * Indicates whether the view text direction has been resolved to the "first strong" heuristic. 2073 * @hide 2074 */ 2075 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT = 2076 TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2077 2078 /** @hide */ 2079 @IntDef({ 2080 TEXT_ALIGNMENT_INHERIT, 2081 TEXT_ALIGNMENT_GRAVITY, 2082 TEXT_ALIGNMENT_CENTER, 2083 TEXT_ALIGNMENT_TEXT_START, 2084 TEXT_ALIGNMENT_TEXT_END, 2085 TEXT_ALIGNMENT_VIEW_START, 2086 TEXT_ALIGNMENT_VIEW_END 2087 }) 2088 @Retention(RetentionPolicy.SOURCE) 2089 public @interface TextAlignment {} 2090 2091 /** 2092 * Default text alignment. The text alignment of this View is inherited from its parent. 2093 * Use with {@link #setTextAlignment(int)} 2094 */ 2095 public static final int TEXT_ALIGNMENT_INHERIT = 0; 2096 2097 /** 2098 * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL, 2099 * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction. 2100 * 2101 * Use with {@link #setTextAlignment(int)} 2102 */ 2103 public static final int TEXT_ALIGNMENT_GRAVITY = 1; 2104 2105 /** 2106 * Align to the start of the paragraph, e.g. ALIGN_NORMAL. 2107 * 2108 * Use with {@link #setTextAlignment(int)} 2109 */ 2110 public static final int TEXT_ALIGNMENT_TEXT_START = 2; 2111 2112 /** 2113 * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE. 2114 * 2115 * Use with {@link #setTextAlignment(int)} 2116 */ 2117 public static final int TEXT_ALIGNMENT_TEXT_END = 3; 2118 2119 /** 2120 * Center the paragraph, e.g. ALIGN_CENTER. 2121 * 2122 * Use with {@link #setTextAlignment(int)} 2123 */ 2124 public static final int TEXT_ALIGNMENT_CENTER = 4; 2125 2126 /** 2127 * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved 2128 * layoutDirection is LTR, and ALIGN_RIGHT otherwise. 2129 * 2130 * Use with {@link #setTextAlignment(int)} 2131 */ 2132 public static final int TEXT_ALIGNMENT_VIEW_START = 5; 2133 2134 /** 2135 * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved 2136 * layoutDirection is LTR, and ALIGN_LEFT otherwise. 2137 * 2138 * Use with {@link #setTextAlignment(int)} 2139 */ 2140 public static final int TEXT_ALIGNMENT_VIEW_END = 6; 2141 2142 /** 2143 * Default text alignment is inherited 2144 */ 2145 private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2146 2147 /** 2148 * Default resolved text alignment 2149 * @hide 2150 */ 2151 static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2152 2153 /** 2154 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2155 * @hide 2156 */ 2157 static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13; 2158 2159 /** 2160 * Mask for use with private flags indicating bits used for text alignment. 2161 * @hide 2162 */ 2163 static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2164 2165 /** 2166 * Array of text direction flags for mapping attribute "textAlignment" to correct 2167 * flag value. 2168 * @hide 2169 */ 2170 private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = { 2171 TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2172 TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2173 TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2174 TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2175 TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2176 TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2177 TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT 2178 }; 2179 2180 /** 2181 * Indicates whether the view text alignment has been resolved. 2182 * @hide 2183 */ 2184 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2185 2186 /** 2187 * Bit shift to get the resolved text alignment. 2188 * @hide 2189 */ 2190 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17; 2191 2192 /** 2193 * Mask for use with private flags indicating bits used for text alignment. 2194 * @hide 2195 */ 2196 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 2197 << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2198 2199 /** 2200 * Indicates whether if the view text alignment has been resolved to gravity 2201 */ 2202 private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT = 2203 TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2204 2205 // Accessiblity constants for mPrivateFlags2 2206 2207 /** 2208 * Shift for the bits in {@link #mPrivateFlags2} related to the 2209 * "importantForAccessibility" attribute. 2210 */ 2211 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20; 2212 2213 /** 2214 * Automatically determine whether a view is important for accessibility. 2215 */ 2216 public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000; 2217 2218 /** 2219 * The view is important for accessibility. 2220 */ 2221 public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001; 2222 2223 /** 2224 * The view is not important for accessibility. 2225 */ 2226 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002; 2227 2228 /** 2229 * The view is not important for accessibility, nor are any of its 2230 * descendant views. 2231 */ 2232 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004; 2233 2234 /** 2235 * The default whether the view is important for accessibility. 2236 */ 2237 static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO; 2238 2239 /** 2240 * Mask for obtainig the bits which specify how to determine 2241 * whether a view is important for accessibility. 2242 */ 2243 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO 2244 | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO 2245 | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) 2246 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2247 2248 /** 2249 * Shift for the bits in {@link #mPrivateFlags2} related to the 2250 * "accessibilityLiveRegion" attribute. 2251 */ 2252 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23; 2253 2254 /** 2255 * Live region mode specifying that accessibility services should not 2256 * automatically announce changes to this view. This is the default live 2257 * region mode for most views. 2258 * <p> 2259 * Use with {@link #setAccessibilityLiveRegion(int)}. 2260 */ 2261 public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000; 2262 2263 /** 2264 * Live region mode specifying that accessibility services should announce 2265 * changes to this view. 2266 * <p> 2267 * Use with {@link #setAccessibilityLiveRegion(int)}. 2268 */ 2269 public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001; 2270 2271 /** 2272 * Live region mode specifying that accessibility services should interrupt 2273 * ongoing speech to immediately announce changes to this view. 2274 * <p> 2275 * Use with {@link #setAccessibilityLiveRegion(int)}. 2276 */ 2277 public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002; 2278 2279 /** 2280 * The default whether the view is important for accessibility. 2281 */ 2282 static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE; 2283 2284 /** 2285 * Mask for obtaining the bits which specify a view's accessibility live 2286 * region mode. 2287 */ 2288 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE 2289 | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE) 2290 << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 2291 2292 /** 2293 * Flag indicating whether a view has accessibility focus. 2294 */ 2295 static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000; 2296 2297 /** 2298 * Flag whether the accessibility state of the subtree rooted at this view changed. 2299 */ 2300 static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000; 2301 2302 /** 2303 * Flag indicating whether a view failed the quickReject() check in draw(). This condition 2304 * is used to check whether later changes to the view's transform should invalidate the 2305 * view to force the quickReject test to run again. 2306 */ 2307 static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000; 2308 2309 /** 2310 * Flag indicating that start/end padding has been resolved into left/right padding 2311 * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()} 2312 * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved 2313 * during measurement. In some special cases this is required such as when an adapter-based 2314 * view measures prospective children without attaching them to a window. 2315 */ 2316 static final int PFLAG2_PADDING_RESOLVED = 0x20000000; 2317 2318 /** 2319 * Flag indicating that the start/end drawables has been resolved into left/right ones. 2320 */ 2321 static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000; 2322 2323 /** 2324 * Indicates that the view is tracking some sort of transient state 2325 * that the app should not need to be aware of, but that the framework 2326 * should take special care to preserve. 2327 */ 2328 static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000; 2329 2330 /** 2331 * Group of bits indicating that RTL properties resolution is done. 2332 */ 2333 static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED | 2334 PFLAG2_TEXT_DIRECTION_RESOLVED | 2335 PFLAG2_TEXT_ALIGNMENT_RESOLVED | 2336 PFLAG2_PADDING_RESOLVED | 2337 PFLAG2_DRAWABLE_RESOLVED; 2338 2339 // There are a couple of flags left in mPrivateFlags2 2340 2341 /* End of masks for mPrivateFlags2 */ 2342 2343 /** 2344 * Masks for mPrivateFlags3, as generated by dumpFlags(): 2345 * 2346 * |-------|-------|-------|-------| 2347 * 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM 2348 * 1 PFLAG3_VIEW_IS_ANIMATING_ALPHA 2349 * 1 PFLAG3_IS_LAID_OUT 2350 * 1 PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT 2351 * 1 PFLAG3_CALLED_SUPER 2352 * |-------|-------|-------|-------| 2353 */ 2354 2355 /** 2356 * Flag indicating that view has a transform animation set on it. This is used to track whether 2357 * an animation is cleared between successive frames, in order to tell the associated 2358 * DisplayList to clear its animation matrix. 2359 */ 2360 static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1; 2361 2362 /** 2363 * Flag indicating that view has an alpha animation set on it. This is used to track whether an 2364 * animation is cleared between successive frames, in order to tell the associated 2365 * DisplayList to restore its alpha value. 2366 */ 2367 static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2; 2368 2369 /** 2370 * Flag indicating that the view has been through at least one layout since it 2371 * was last attached to a window. 2372 */ 2373 static final int PFLAG3_IS_LAID_OUT = 0x4; 2374 2375 /** 2376 * Flag indicating that a call to measure() was skipped and should be done 2377 * instead when layout() is invoked. 2378 */ 2379 static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8; 2380 2381 /** 2382 * Flag indicating that an overridden method correctly called down to 2383 * the superclass implementation as required by the API spec. 2384 */ 2385 static final int PFLAG3_CALLED_SUPER = 0x10; 2386 2387 /** 2388 * Flag indicating that we're in the process of applying window insets. 2389 */ 2390 static final int PFLAG3_APPLYING_INSETS = 0x20; 2391 2392 /** 2393 * Flag indicating that we're in the process of fitting system windows using the old method. 2394 */ 2395 static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40; 2396 2397 /** 2398 * Flag indicating that nested scrolling is enabled for this view. 2399 * The view will optionally cooperate with views up its parent chain to allow for 2400 * integrated nested scrolling along the same axis. 2401 */ 2402 static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80; 2403 2404 /* End of masks for mPrivateFlags3 */ 2405 2406 static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED; 2407 2408 /** 2409 * Always allow a user to over-scroll this view, provided it is a 2410 * view that can scroll. 2411 * 2412 * @see #getOverScrollMode() 2413 * @see #setOverScrollMode(int) 2414 */ 2415 public static final int OVER_SCROLL_ALWAYS = 0; 2416 2417 /** 2418 * Allow a user to over-scroll this view only if the content is large 2419 * enough to meaningfully scroll, provided it is a view that can scroll. 2420 * 2421 * @see #getOverScrollMode() 2422 * @see #setOverScrollMode(int) 2423 */ 2424 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 2425 2426 /** 2427 * Never allow a user to over-scroll this view. 2428 * 2429 * @see #getOverScrollMode() 2430 * @see #setOverScrollMode(int) 2431 */ 2432 public static final int OVER_SCROLL_NEVER = 2; 2433 2434 /** 2435 * Special constant for {@link #setSystemUiVisibility(int)}: View has 2436 * requested the system UI (status bar) to be visible (the default). 2437 * 2438 * @see #setSystemUiVisibility(int) 2439 */ 2440 public static final int SYSTEM_UI_FLAG_VISIBLE = 0; 2441 2442 /** 2443 * Flag for {@link #setSystemUiVisibility(int)}: View has requested the 2444 * system UI to enter an unobtrusive "low profile" mode. 2445 * 2446 * <p>This is for use in games, book readers, video players, or any other 2447 * "immersive" application where the usual system chrome is deemed too distracting. 2448 * 2449 * <p>In low profile mode, the status bar and/or navigation icons may dim. 2450 * 2451 * @see #setSystemUiVisibility(int) 2452 */ 2453 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001; 2454 2455 /** 2456 * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the 2457 * system navigation be temporarily hidden. 2458 * 2459 * <p>This is an even less obtrusive state than that called for by 2460 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls 2461 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause 2462 * those to disappear. This is useful (in conjunction with the 2463 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and 2464 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN} 2465 * window flags) for displaying content using every last pixel on the display. 2466 * 2467 * <p>There is a limitation: because navigation controls are so important, the least user 2468 * interaction will cause them to reappear immediately. When this happens, both 2469 * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically, 2470 * so that both elements reappear at the same time. 2471 * 2472 * @see #setSystemUiVisibility(int) 2473 */ 2474 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002; 2475 2476 /** 2477 * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go 2478 * into the normal fullscreen mode so that its content can take over the screen 2479 * while still allowing the user to interact with the application. 2480 * 2481 * <p>This has the same visual effect as 2482 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN 2483 * WindowManager.LayoutParams.FLAG_FULLSCREEN}, 2484 * meaning that non-critical screen decorations (such as the status bar) will be 2485 * hidden while the user is in the View's window, focusing the experience on 2486 * that content. Unlike the window flag, if you are using ActionBar in 2487 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2488 * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also 2489 * hide the action bar. 2490 * 2491 * <p>This approach to going fullscreen is best used over the window flag when 2492 * it is a transient state -- that is, the application does this at certain 2493 * points in its user interaction where it wants to allow the user to focus 2494 * on content, but not as a continuous state. For situations where the application 2495 * would like to simply stay full screen the entire time (such as a game that 2496 * wants to take over the screen), the 2497 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag} 2498 * is usually a better approach. The state set here will be removed by the system 2499 * in various situations (such as the user moving to another application) like 2500 * the other system UI states. 2501 * 2502 * <p>When using this flag, the application should provide some easy facility 2503 * for the user to go out of it. A common example would be in an e-book 2504 * reader, where tapping on the screen brings back whatever screen and UI 2505 * decorations that had been hidden while the user was immersed in reading 2506 * the book. 2507 * 2508 * @see #setSystemUiVisibility(int) 2509 */ 2510 public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004; 2511 2512 /** 2513 * Flag for {@link #setSystemUiVisibility(int)}: When using other layout 2514 * flags, we would like a stable view of the content insets given to 2515 * {@link #fitSystemWindows(Rect)}. This means that the insets seen there 2516 * will always represent the worst case that the application can expect 2517 * as a continuous state. In the stock Android UI this is the space for 2518 * the system bar, nav bar, and status bar, but not more transient elements 2519 * such as an input method. 2520 * 2521 * The stable layout your UI sees is based on the system UI modes you can 2522 * switch to. That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 2523 * then you will get a stable layout for changes of the 2524 * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify 2525 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and 2526 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition 2527 * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} 2528 * with a stable layout. (Note that you should avoid using 2529 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.) 2530 * 2531 * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN} 2532 * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}), 2533 * then a hidden status bar will be considered a "stable" state for purposes 2534 * here. This allows your UI to continually hide the status bar, while still 2535 * using the system UI flags to hide the action bar while still retaining 2536 * a stable layout. Note that changing the window fullscreen flag will never 2537 * provide a stable layout for a clean transition. 2538 * 2539 * <p>If you are using ActionBar in 2540 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2541 * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the 2542 * insets it adds to those given to the application. 2543 */ 2544 public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100; 2545 2546 /** 2547 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2548 * to be layed out as if it has requested 2549 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't. This 2550 * allows it to avoid artifacts when switching in and out of that mode, at 2551 * the expense that some of its user interface may be covered by screen 2552 * decorations when they are shown. You can perform layout of your inner 2553 * UI elements to account for the navigation system UI through the 2554 * {@link #fitSystemWindows(Rect)} method. 2555 */ 2556 public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200; 2557 2558 /** 2559 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2560 * to be layed out as if it has requested 2561 * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't. This 2562 * allows it to avoid artifacts when switching in and out of that mode, at 2563 * the expense that some of its user interface may be covered by screen 2564 * decorations when they are shown. You can perform layout of your inner 2565 * UI elements to account for non-fullscreen system UI through the 2566 * {@link #fitSystemWindows(Rect)} method. 2567 */ 2568 public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400; 2569 2570 /** 2571 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2572 * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. If this flag is 2573 * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any 2574 * user interaction. 2575 * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only 2576 * has an effect when used in combination with that flag.</p> 2577 */ 2578 public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800; 2579 2580 /** 2581 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2582 * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation 2583 * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. Use this flag to create an immersive 2584 * experience while also hiding the system bars. If this flag is not set, 2585 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user 2586 * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system 2587 * if the user swipes from the top of the screen. 2588 * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with 2589 * system gestures, such as swiping from the top of the screen. These transient system bars 2590 * will overlay app’s content, may have some degree of transparency, and will automatically 2591 * hide after a short timeout. 2592 * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and 2593 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination 2594 * with one or both of those flags.</p> 2595 */ 2596 public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000; 2597 2598 /** 2599 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead. 2600 */ 2601 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE; 2602 2603 /** 2604 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead. 2605 */ 2606 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE; 2607 2608 /** 2609 * @hide 2610 * 2611 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2612 * out of the public fields to keep the undefined bits out of the developer's way. 2613 * 2614 * Flag to make the status bar not expandable. Unless you also 2615 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 2616 */ 2617 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 2618 2619 /** 2620 * @hide 2621 * 2622 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2623 * out of the public fields to keep the undefined bits out of the developer's way. 2624 * 2625 * Flag to hide notification icons and scrolling ticker text. 2626 */ 2627 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 2628 2629 /** 2630 * @hide 2631 * 2632 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2633 * out of the public fields to keep the undefined bits out of the developer's way. 2634 * 2635 * Flag to disable incoming notification alerts. This will not block 2636 * icons, but it will block sound, vibrating and other visual or aural notifications. 2637 */ 2638 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 2639 2640 /** 2641 * @hide 2642 * 2643 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2644 * out of the public fields to keep the undefined bits out of the developer's way. 2645 * 2646 * Flag to hide only the scrolling ticker. Note that 2647 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 2648 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 2649 */ 2650 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 2651 2652 /** 2653 * @hide 2654 * 2655 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2656 * out of the public fields to keep the undefined bits out of the developer's way. 2657 * 2658 * Flag to hide the center system info area. 2659 */ 2660 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 2661 2662 /** 2663 * @hide 2664 * 2665 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2666 * out of the public fields to keep the undefined bits out of the developer's way. 2667 * 2668 * Flag to hide only the home button. Don't use this 2669 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2670 */ 2671 public static final int STATUS_BAR_DISABLE_HOME = 0x00200000; 2672 2673 /** 2674 * @hide 2675 * 2676 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2677 * out of the public fields to keep the undefined bits out of the developer's way. 2678 * 2679 * Flag to hide only the back button. Don't use this 2680 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2681 */ 2682 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 2683 2684 /** 2685 * @hide 2686 * 2687 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2688 * out of the public fields to keep the undefined bits out of the developer's way. 2689 * 2690 * Flag to hide only the clock. You might use this if your activity has 2691 * its own clock making the status bar's clock redundant. 2692 */ 2693 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 2694 2695 /** 2696 * @hide 2697 * 2698 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2699 * out of the public fields to keep the undefined bits out of the developer's way. 2700 * 2701 * Flag to hide only the recent apps button. Don't use this 2702 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2703 */ 2704 public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000; 2705 2706 /** 2707 * @hide 2708 * 2709 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2710 * out of the public fields to keep the undefined bits out of the developer's way. 2711 * 2712 * Flag to disable the global search gesture. Don't use this 2713 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2714 */ 2715 public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000; 2716 2717 /** 2718 * @hide 2719 * 2720 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2721 * out of the public fields to keep the undefined bits out of the developer's way. 2722 * 2723 * Flag to specify that the status bar is displayed in transient mode. 2724 */ 2725 public static final int STATUS_BAR_TRANSIENT = 0x04000000; 2726 2727 /** 2728 * @hide 2729 * 2730 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2731 * out of the public fields to keep the undefined bits out of the developer's way. 2732 * 2733 * Flag to specify that the navigation bar is displayed in transient mode. 2734 */ 2735 public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000; 2736 2737 /** 2738 * @hide 2739 * 2740 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2741 * out of the public fields to keep the undefined bits out of the developer's way. 2742 * 2743 * Flag to specify that the hidden status bar would like to be shown. 2744 */ 2745 public static final int STATUS_BAR_UNHIDE = 0x10000000; 2746 2747 /** 2748 * @hide 2749 * 2750 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2751 * out of the public fields to keep the undefined bits out of the developer's way. 2752 * 2753 * Flag to specify that the hidden navigation bar would like to be shown. 2754 */ 2755 public static final int NAVIGATION_BAR_UNHIDE = 0x20000000; 2756 2757 /** 2758 * @hide 2759 * 2760 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2761 * out of the public fields to keep the undefined bits out of the developer's way. 2762 * 2763 * Flag to specify that the status bar is displayed in translucent mode. 2764 */ 2765 public static final int STATUS_BAR_TRANSLUCENT = 0x40000000; 2766 2767 /** 2768 * @hide 2769 * 2770 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2771 * out of the public fields to keep the undefined bits out of the developer's way. 2772 * 2773 * Flag to specify that the navigation bar is displayed in translucent mode. 2774 */ 2775 public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000; 2776 2777 /** 2778 * @hide 2779 * 2780 * Whether Recents is visible or not. 2781 */ 2782 public static final int RECENT_APPS_VISIBLE = 0x00004000; 2783 2784 /** 2785 * @hide 2786 * 2787 * Makes system ui transparent. 2788 */ 2789 public static final int SYSTEM_UI_TRANSPARENT = 0x00008000; 2790 2791 /** 2792 * @hide 2793 */ 2794 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FFF; 2795 2796 /** 2797 * These are the system UI flags that can be cleared by events outside 2798 * of an application. Currently this is just the ability to tap on the 2799 * screen while hiding the navigation bar to have it return. 2800 * @hide 2801 */ 2802 public static final int SYSTEM_UI_CLEARABLE_FLAGS = 2803 SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION 2804 | SYSTEM_UI_FLAG_FULLSCREEN; 2805 2806 /** 2807 * Flags that can impact the layout in relation to system UI. 2808 */ 2809 public static final int SYSTEM_UI_LAYOUT_FLAGS = 2810 SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 2811 | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; 2812 2813 /** @hide */ 2814 @IntDef(flag = true, 2815 value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION }) 2816 @Retention(RetentionPolicy.SOURCE) 2817 public @interface FindViewFlags {} 2818 2819 /** 2820 * Find views that render the specified text. 2821 * 2822 * @see #findViewsWithText(ArrayList, CharSequence, int) 2823 */ 2824 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001; 2825 2826 /** 2827 * Find find views that contain the specified content description. 2828 * 2829 * @see #findViewsWithText(ArrayList, CharSequence, int) 2830 */ 2831 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002; 2832 2833 /** 2834 * Find views that contain {@link AccessibilityNodeProvider}. Such 2835 * a View is a root of virtual view hierarchy and may contain the searched 2836 * text. If this flag is set Views with providers are automatically 2837 * added and it is a responsibility of the client to call the APIs of 2838 * the provider to determine whether the virtual tree rooted at this View 2839 * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s 2840 * representing the virtual views with this text. 2841 * 2842 * @see #findViewsWithText(ArrayList, CharSequence, int) 2843 * 2844 * @hide 2845 */ 2846 public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004; 2847 2848 /** 2849 * The undefined cursor position. 2850 * 2851 * @hide 2852 */ 2853 public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1; 2854 2855 /** 2856 * Indicates that the screen has changed state and is now off. 2857 * 2858 * @see #onScreenStateChanged(int) 2859 */ 2860 public static final int SCREEN_STATE_OFF = 0x0; 2861 2862 /** 2863 * Indicates that the screen has changed state and is now on. 2864 * 2865 * @see #onScreenStateChanged(int) 2866 */ 2867 public static final int SCREEN_STATE_ON = 0x1; 2868 2869 /** 2870 * Indicates no axis of view scrolling. 2871 */ 2872 public static final int SCROLL_AXIS_NONE = 0; 2873 2874 /** 2875 * Indicates scrolling along the horizontal axis. 2876 */ 2877 public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0; 2878 2879 /** 2880 * Indicates scrolling along the vertical axis. 2881 */ 2882 public static final int SCROLL_AXIS_VERTICAL = 1 << 1; 2883 2884 /** 2885 * Controls the over-scroll mode for this view. 2886 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 2887 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 2888 * and {@link #OVER_SCROLL_NEVER}. 2889 */ 2890 private int mOverScrollMode; 2891 2892 /** 2893 * The parent this view is attached to. 2894 * {@hide} 2895 * 2896 * @see #getParent() 2897 */ 2898 protected ViewParent mParent; 2899 2900 /** 2901 * {@hide} 2902 */ 2903 AttachInfo mAttachInfo; 2904 2905 /** 2906 * {@hide} 2907 */ 2908 @ViewDebug.ExportedProperty(flagMapping = { 2909 @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT, 2910 name = "FORCE_LAYOUT"), 2911 @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED, 2912 name = "LAYOUT_REQUIRED"), 2913 @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID, 2914 name = "DRAWING_CACHE_INVALID", outputIf = false), 2915 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true), 2916 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false), 2917 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 2918 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY") 2919 }, formatToHexString = true) 2920 int mPrivateFlags; 2921 int mPrivateFlags2; 2922 int mPrivateFlags3; 2923 2924 /** 2925 * This view's request for the visibility of the status bar. 2926 * @hide 2927 */ 2928 @ViewDebug.ExportedProperty(flagMapping = { 2929 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 2930 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 2931 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 2932 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2933 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2934 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 2935 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 2936 equals = SYSTEM_UI_FLAG_VISIBLE, 2937 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 2938 }, formatToHexString = true) 2939 int mSystemUiVisibility; 2940 2941 /** 2942 * Reference count for transient state. 2943 * @see #setHasTransientState(boolean) 2944 */ 2945 int mTransientStateCount = 0; 2946 2947 /** 2948 * Count of how many windows this view has been attached to. 2949 */ 2950 int mWindowAttachCount; 2951 2952 /** 2953 * The layout parameters associated with this view and used by the parent 2954 * {@link android.view.ViewGroup} to determine how this view should be 2955 * laid out. 2956 * {@hide} 2957 */ 2958 protected ViewGroup.LayoutParams mLayoutParams; 2959 2960 /** 2961 * The view flags hold various views states. 2962 * {@hide} 2963 */ 2964 @ViewDebug.ExportedProperty(formatToHexString = true) 2965 int mViewFlags; 2966 2967 static class TransformationInfo { 2968 /** 2969 * The transform matrix for the View. This transform is calculated internally 2970 * based on the translation, rotation, and scale properties. 2971 * 2972 * Do *not* use this variable directly; instead call getMatrix(), which will 2973 * load the value from the View's RenderNode. 2974 */ 2975 private final Matrix mMatrix = new Matrix(); 2976 2977 /** 2978 * The inverse transform matrix for the View. This transform is calculated 2979 * internally based on the translation, rotation, and scale properties. 2980 * 2981 * Do *not* use this variable directly; instead call getInverseMatrix(), 2982 * which will load the value from the View's RenderNode. 2983 */ 2984 private Matrix mInverseMatrix; 2985 2986 /** 2987 * The opacity of the View. This is a value from 0 to 1, where 0 means 2988 * completely transparent and 1 means completely opaque. 2989 */ 2990 @ViewDebug.ExportedProperty 2991 float mAlpha = 1f; 2992 2993 /** 2994 * The opacity of the view as manipulated by the Fade transition. This is a hidden 2995 * property only used by transitions, which is composited with the other alpha 2996 * values to calculate the final visual alpha value. 2997 */ 2998 float mTransitionAlpha = 1f; 2999 } 3000 3001 TransformationInfo mTransformationInfo; 3002 3003 /** 3004 * Current clip bounds. to which all drawing of this view are constrained. 3005 */ 3006 Rect mClipBounds = null; 3007 3008 private boolean mLastIsOpaque; 3009 3010 /** 3011 * The distance in pixels from the left edge of this view's parent 3012 * to the left edge of this view. 3013 * {@hide} 3014 */ 3015 @ViewDebug.ExportedProperty(category = "layout") 3016 protected int mLeft; 3017 /** 3018 * The distance in pixels from the left edge of this view's parent 3019 * to the right edge of this view. 3020 * {@hide} 3021 */ 3022 @ViewDebug.ExportedProperty(category = "layout") 3023 protected int mRight; 3024 /** 3025 * The distance in pixels from the top edge of this view's parent 3026 * to the top edge of this view. 3027 * {@hide} 3028 */ 3029 @ViewDebug.ExportedProperty(category = "layout") 3030 protected int mTop; 3031 /** 3032 * The distance in pixels from the top edge of this view's parent 3033 * to the bottom edge of this view. 3034 * {@hide} 3035 */ 3036 @ViewDebug.ExportedProperty(category = "layout") 3037 protected int mBottom; 3038 3039 /** 3040 * The offset, in pixels, by which the content of this view is scrolled 3041 * horizontally. 3042 * {@hide} 3043 */ 3044 @ViewDebug.ExportedProperty(category = "scrolling") 3045 protected int mScrollX; 3046 /** 3047 * The offset, in pixels, by which the content of this view is scrolled 3048 * vertically. 3049 * {@hide} 3050 */ 3051 @ViewDebug.ExportedProperty(category = "scrolling") 3052 protected int mScrollY; 3053 3054 /** 3055 * The left padding in pixels, that is the distance in pixels between the 3056 * left edge of this view and the left edge of its content. 3057 * {@hide} 3058 */ 3059 @ViewDebug.ExportedProperty(category = "padding") 3060 protected int mPaddingLeft = 0; 3061 /** 3062 * The right padding in pixels, that is the distance in pixels between the 3063 * right edge of this view and the right edge of its content. 3064 * {@hide} 3065 */ 3066 @ViewDebug.ExportedProperty(category = "padding") 3067 protected int mPaddingRight = 0; 3068 /** 3069 * The top padding in pixels, that is the distance in pixels between the 3070 * top edge of this view and the top edge of its content. 3071 * {@hide} 3072 */ 3073 @ViewDebug.ExportedProperty(category = "padding") 3074 protected int mPaddingTop; 3075 /** 3076 * The bottom padding in pixels, that is the distance in pixels between the 3077 * bottom edge of this view and the bottom edge of its content. 3078 * {@hide} 3079 */ 3080 @ViewDebug.ExportedProperty(category = "padding") 3081 protected int mPaddingBottom; 3082 3083 /** 3084 * The layout insets in pixels, that is the distance in pixels between the 3085 * visible edges of this view its bounds. 3086 */ 3087 private Insets mLayoutInsets; 3088 3089 /** 3090 * Briefly describes the view and is primarily used for accessibility support. 3091 */ 3092 private CharSequence mContentDescription; 3093 3094 /** 3095 * Specifies the id of a view for which this view serves as a label for 3096 * accessibility purposes. 3097 */ 3098 private int mLabelForId = View.NO_ID; 3099 3100 /** 3101 * Predicate for matching labeled view id with its label for 3102 * accessibility purposes. 3103 */ 3104 private MatchLabelForPredicate mMatchLabelForPredicate; 3105 3106 /** 3107 * Specifies a view before which this one is visited in accessibility traversal. 3108 */ 3109 private int mAccessibilityTraversalBeforeId = NO_ID; 3110 3111 /** 3112 * Specifies a view after which this one is visited in accessibility traversal. 3113 */ 3114 private int mAccessibilityTraversalAfterId = NO_ID; 3115 3116 /** 3117 * Predicate for matching a view by its id. 3118 */ 3119 private MatchIdPredicate mMatchIdPredicate; 3120 3121 /** 3122 * Cache the paddingRight set by the user to append to the scrollbar's size. 3123 * 3124 * @hide 3125 */ 3126 @ViewDebug.ExportedProperty(category = "padding") 3127 protected int mUserPaddingRight; 3128 3129 /** 3130 * Cache the paddingBottom set by the user to append to the scrollbar's size. 3131 * 3132 * @hide 3133 */ 3134 @ViewDebug.ExportedProperty(category = "padding") 3135 protected int mUserPaddingBottom; 3136 3137 /** 3138 * Cache the paddingLeft set by the user to append to the scrollbar's size. 3139 * 3140 * @hide 3141 */ 3142 @ViewDebug.ExportedProperty(category = "padding") 3143 protected int mUserPaddingLeft; 3144 3145 /** 3146 * Cache the paddingStart set by the user to append to the scrollbar's size. 3147 * 3148 */ 3149 @ViewDebug.ExportedProperty(category = "padding") 3150 int mUserPaddingStart; 3151 3152 /** 3153 * Cache the paddingEnd set by the user to append to the scrollbar's size. 3154 * 3155 */ 3156 @ViewDebug.ExportedProperty(category = "padding") 3157 int mUserPaddingEnd; 3158 3159 /** 3160 * Cache initial left padding. 3161 * 3162 * @hide 3163 */ 3164 int mUserPaddingLeftInitial; 3165 3166 /** 3167 * Cache initial right padding. 3168 * 3169 * @hide 3170 */ 3171 int mUserPaddingRightInitial; 3172 3173 /** 3174 * Default undefined padding 3175 */ 3176 private static final int UNDEFINED_PADDING = Integer.MIN_VALUE; 3177 3178 /** 3179 * Cache if a left padding has been defined 3180 */ 3181 private boolean mLeftPaddingDefined = false; 3182 3183 /** 3184 * Cache if a right padding has been defined 3185 */ 3186 private boolean mRightPaddingDefined = false; 3187 3188 /** 3189 * @hide 3190 */ 3191 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 3192 /** 3193 * @hide 3194 */ 3195 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 3196 3197 private LongSparseLongArray mMeasureCache; 3198 3199 @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_") 3200 private Drawable mBackground; 3201 private TintInfo mBackgroundTint; 3202 3203 /** 3204 * RenderNode used for backgrounds. 3205 * <p> 3206 * When non-null and valid, this is expected to contain an up-to-date copy 3207 * of the background drawable. It is cleared on temporary detach, and reset 3208 * on cleanup. 3209 */ 3210 private RenderNode mBackgroundRenderNode; 3211 3212 private int mBackgroundResource; 3213 private boolean mBackgroundSizeChanged; 3214 3215 private String mTransitionName; 3216 3217 private static class TintInfo { 3218 ColorStateList mTintList; 3219 PorterDuff.Mode mTintMode; 3220 boolean mHasTintMode; 3221 boolean mHasTintList; 3222 } 3223 3224 static class ListenerInfo { 3225 /** 3226 * Listener used to dispatch focus change events. 3227 * This field should be made private, so it is hidden from the SDK. 3228 * {@hide} 3229 */ 3230 protected OnFocusChangeListener mOnFocusChangeListener; 3231 3232 /** 3233 * Listeners for layout change events. 3234 */ 3235 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 3236 3237 protected OnScrollChangeListener mOnScrollChangeListener; 3238 3239 /** 3240 * Listeners for attach events. 3241 */ 3242 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 3243 3244 /** 3245 * Listener used to dispatch click events. 3246 * This field should be made private, so it is hidden from the SDK. 3247 * {@hide} 3248 */ 3249 public OnClickListener mOnClickListener; 3250 3251 /** 3252 * Listener used to dispatch long click events. 3253 * This field should be made private, so it is hidden from the SDK. 3254 * {@hide} 3255 */ 3256 protected OnLongClickListener mOnLongClickListener; 3257 3258 /** 3259 * Listener used to build the context menu. 3260 * This field should be made private, so it is hidden from the SDK. 3261 * {@hide} 3262 */ 3263 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 3264 3265 private OnKeyListener mOnKeyListener; 3266 3267 private OnTouchListener mOnTouchListener; 3268 3269 private OnHoverListener mOnHoverListener; 3270 3271 private OnGenericMotionListener mOnGenericMotionListener; 3272 3273 private OnDragListener mOnDragListener; 3274 3275 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 3276 3277 OnApplyWindowInsetsListener mOnApplyWindowInsetsListener; 3278 } 3279 3280 ListenerInfo mListenerInfo; 3281 3282 /** 3283 * The application environment this view lives in. 3284 * This field should be made private, so it is hidden from the SDK. 3285 * {@hide} 3286 */ 3287 @ViewDebug.ExportedProperty(deepExport = true) 3288 protected Context mContext; 3289 3290 private final Resources mResources; 3291 3292 private ScrollabilityCache mScrollCache; 3293 3294 private int[] mDrawableState = null; 3295 3296 ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND; 3297 3298 /** 3299 * Animator that automatically runs based on state changes. 3300 */ 3301 private StateListAnimator mStateListAnimator; 3302 3303 /** 3304 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 3305 * the user may specify which view to go to next. 3306 */ 3307 private int mNextFocusLeftId = View.NO_ID; 3308 3309 /** 3310 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 3311 * the user may specify which view to go to next. 3312 */ 3313 private int mNextFocusRightId = View.NO_ID; 3314 3315 /** 3316 * When this view has focus and the next focus is {@link #FOCUS_UP}, 3317 * the user may specify which view to go to next. 3318 */ 3319 private int mNextFocusUpId = View.NO_ID; 3320 3321 /** 3322 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 3323 * the user may specify which view to go to next. 3324 */ 3325 private int mNextFocusDownId = View.NO_ID; 3326 3327 /** 3328 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 3329 * the user may specify which view to go to next. 3330 */ 3331 int mNextFocusForwardId = View.NO_ID; 3332 3333 private CheckForLongPress mPendingCheckForLongPress; 3334 private CheckForTap mPendingCheckForTap = null; 3335 private PerformClick mPerformClick; 3336 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 3337 3338 private UnsetPressedState mUnsetPressedState; 3339 3340 /** 3341 * Whether the long press's action has been invoked. The tap's action is invoked on the 3342 * up event while a long press is invoked as soon as the long press duration is reached, so 3343 * a long press could be performed before the tap is checked, in which case the tap's action 3344 * should not be invoked. 3345 */ 3346 private boolean mHasPerformedLongPress; 3347 3348 /** 3349 * The minimum height of the view. We'll try our best to have the height 3350 * of this view to at least this amount. 3351 */ 3352 @ViewDebug.ExportedProperty(category = "measurement") 3353 private int mMinHeight; 3354 3355 /** 3356 * The minimum width of the view. We'll try our best to have the width 3357 * of this view to at least this amount. 3358 */ 3359 @ViewDebug.ExportedProperty(category = "measurement") 3360 private int mMinWidth; 3361 3362 /** 3363 * The delegate to handle touch events that are physically in this view 3364 * but should be handled by another view. 3365 */ 3366 private TouchDelegate mTouchDelegate = null; 3367 3368 /** 3369 * Solid color to use as a background when creating the drawing cache. Enables 3370 * the cache to use 16 bit bitmaps instead of 32 bit. 3371 */ 3372 private int mDrawingCacheBackgroundColor = 0; 3373 3374 /** 3375 * Special tree observer used when mAttachInfo is null. 3376 */ 3377 private ViewTreeObserver mFloatingTreeObserver; 3378 3379 /** 3380 * Cache the touch slop from the context that created the view. 3381 */ 3382 private int mTouchSlop; 3383 3384 /** 3385 * Object that handles automatic animation of view properties. 3386 */ 3387 private ViewPropertyAnimator mAnimator = null; 3388 3389 /** 3390 * Flag indicating that a drag can cross window boundaries. When 3391 * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called 3392 * with this flag set, all visible applications will be able to participate 3393 * in the drag operation and receive the dragged content. 3394 * 3395 * @hide 3396 */ 3397 public static final int DRAG_FLAG_GLOBAL = 1; 3398 3399 /** 3400 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 3401 */ 3402 private float mVerticalScrollFactor; 3403 3404 /** 3405 * Position of the vertical scroll bar. 3406 */ 3407 private int mVerticalScrollbarPosition; 3408 3409 /** 3410 * Position the scroll bar at the default position as determined by the system. 3411 */ 3412 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 3413 3414 /** 3415 * Position the scroll bar along the left edge. 3416 */ 3417 public static final int SCROLLBAR_POSITION_LEFT = 1; 3418 3419 /** 3420 * Position the scroll bar along the right edge. 3421 */ 3422 public static final int SCROLLBAR_POSITION_RIGHT = 2; 3423 3424 /** 3425 * Indicates that the view does not have a layer. 3426 * 3427 * @see #getLayerType() 3428 * @see #setLayerType(int, android.graphics.Paint) 3429 * @see #LAYER_TYPE_SOFTWARE 3430 * @see #LAYER_TYPE_HARDWARE 3431 */ 3432 public static final int LAYER_TYPE_NONE = 0; 3433 3434 /** 3435 * <p>Indicates that the view has a software layer. A software layer is backed 3436 * by a bitmap and causes the view to be rendered using Android's software 3437 * rendering pipeline, even if hardware acceleration is enabled.</p> 3438 * 3439 * <p>Software layers have various usages:</p> 3440 * <p>When the application is not using hardware acceleration, a software layer 3441 * is useful to apply a specific color filter and/or blending mode and/or 3442 * translucency to a view and all its children.</p> 3443 * <p>When the application is using hardware acceleration, a software layer 3444 * is useful to render drawing primitives not supported by the hardware 3445 * accelerated pipeline. It can also be used to cache a complex view tree 3446 * into a texture and reduce the complexity of drawing operations. For instance, 3447 * when animating a complex view tree with a translation, a software layer can 3448 * be used to render the view tree only once.</p> 3449 * <p>Software layers should be avoided when the affected view tree updates 3450 * often. Every update will require to re-render the software layer, which can 3451 * potentially be slow (particularly when hardware acceleration is turned on 3452 * since the layer will have to be uploaded into a hardware texture after every 3453 * update.)</p> 3454 * 3455 * @see #getLayerType() 3456 * @see #setLayerType(int, android.graphics.Paint) 3457 * @see #LAYER_TYPE_NONE 3458 * @see #LAYER_TYPE_HARDWARE 3459 */ 3460 public static final int LAYER_TYPE_SOFTWARE = 1; 3461 3462 /** 3463 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 3464 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 3465 * OpenGL hardware) and causes the view to be rendered using Android's hardware 3466 * rendering pipeline, but only if hardware acceleration is turned on for the 3467 * view hierarchy. When hardware acceleration is turned off, hardware layers 3468 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 3469 * 3470 * <p>A hardware layer is useful to apply a specific color filter and/or 3471 * blending mode and/or translucency to a view and all its children.</p> 3472 * <p>A hardware layer can be used to cache a complex view tree into a 3473 * texture and reduce the complexity of drawing operations. For instance, 3474 * when animating a complex view tree with a translation, a hardware layer can 3475 * be used to render the view tree only once.</p> 3476 * <p>A hardware layer can also be used to increase the rendering quality when 3477 * rotation transformations are applied on a view. It can also be used to 3478 * prevent potential clipping issues when applying 3D transforms on a view.</p> 3479 * 3480 * @see #getLayerType() 3481 * @see #setLayerType(int, android.graphics.Paint) 3482 * @see #LAYER_TYPE_NONE 3483 * @see #LAYER_TYPE_SOFTWARE 3484 */ 3485 public static final int LAYER_TYPE_HARDWARE = 2; 3486 3487 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 3488 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 3489 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 3490 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 3491 }) 3492 int mLayerType = LAYER_TYPE_NONE; 3493 Paint mLayerPaint; 3494 3495 /** 3496 * Set to true when drawing cache is enabled and cannot be created. 3497 * 3498 * @hide 3499 */ 3500 public boolean mCachingFailed; 3501 private Bitmap mDrawingCache; 3502 private Bitmap mUnscaledDrawingCache; 3503 3504 /** 3505 * RenderNode holding View properties, potentially holding a DisplayList of View content. 3506 * <p> 3507 * When non-null and valid, this is expected to contain an up-to-date copy 3508 * of the View content. Its DisplayList content is cleared on temporary detach and reset on 3509 * cleanup. 3510 */ 3511 final RenderNode mRenderNode; 3512 3513 /** 3514 * Set to true when the view is sending hover accessibility events because it 3515 * is the innermost hovered view. 3516 */ 3517 private boolean mSendingHoverAccessibilityEvents; 3518 3519 /** 3520 * Delegate for injecting accessibility functionality. 3521 */ 3522 AccessibilityDelegate mAccessibilityDelegate; 3523 3524 /** 3525 * The view's overlay layer. Developers get a reference to the overlay via getOverlay() 3526 * and add/remove objects to/from the overlay directly through the Overlay methods. 3527 */ 3528 ViewOverlay mOverlay; 3529 3530 /** 3531 * The currently active parent view for receiving delegated nested scrolling events. 3532 * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared 3533 * by {@link #stopNestedScroll()} at the same point where we clear 3534 * requestDisallowInterceptTouchEvent. 3535 */ 3536 private ViewParent mNestedScrollingParent; 3537 3538 /** 3539 * Consistency verifier for debugging purposes. 3540 * @hide 3541 */ 3542 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 3543 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 3544 new InputEventConsistencyVerifier(this, 0) : null; 3545 3546 private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); 3547 3548 private int[] mTempNestedScrollConsumed; 3549 3550 /** 3551 * An overlay is going to draw this View instead of being drawn as part of this 3552 * View's parent. mGhostView is the View in the Overlay that must be invalidated 3553 * when this view is invalidated. 3554 */ 3555 GhostView mGhostView; 3556 3557 /** 3558 * Holds pairs of adjacent attribute data: attribute name followed by its value. 3559 * @hide 3560 */ 3561 @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true) 3562 public String[] mAttributes; 3563 3564 /** 3565 * Maps a Resource id to its name. 3566 */ 3567 private static SparseArray<String> mAttributeMap; 3568 3569 /** 3570 * Simple constructor to use when creating a view from code. 3571 * 3572 * @param context The Context the view is running in, through which it can 3573 * access the current theme, resources, etc. 3574 */ 3575 public View(Context context) { 3576 mContext = context; 3577 mResources = context != null ? context.getResources() : null; 3578 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED; 3579 // Set some flags defaults 3580 mPrivateFlags2 = 3581 (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) | 3582 (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) | 3583 (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) | 3584 (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) | 3585 (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) | 3586 (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT); 3587 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 3588 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 3589 mUserPaddingStart = UNDEFINED_PADDING; 3590 mUserPaddingEnd = UNDEFINED_PADDING; 3591 mRenderNode = RenderNode.create(getClass().getName(), this); 3592 3593 if (!sCompatibilityDone && context != null) { 3594 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3595 3596 // Older apps may need this compatibility hack for measurement. 3597 sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1; 3598 3599 // Older apps expect onMeasure() to always be called on a layout pass, regardless 3600 // of whether a layout was requested on that View. 3601 sIgnoreMeasureCache = targetSdkVersion < KITKAT; 3602 3603 sCompatibilityDone = true; 3604 } 3605 } 3606 3607 /** 3608 * Constructor that is called when inflating a view from XML. This is called 3609 * when a view is being constructed from an XML file, supplying attributes 3610 * that were specified in the XML file. This version uses a default style of 3611 * 0, so the only attribute values applied are those in the Context's Theme 3612 * and the given AttributeSet. 3613 * 3614 * <p> 3615 * The method onFinishInflate() will be called after all children have been 3616 * added. 3617 * 3618 * @param context The Context the view is running in, through which it can 3619 * access the current theme, resources, etc. 3620 * @param attrs The attributes of the XML tag that is inflating the view. 3621 * @see #View(Context, AttributeSet, int) 3622 */ 3623 public View(Context context, AttributeSet attrs) { 3624 this(context, attrs, 0); 3625 } 3626 3627 /** 3628 * Perform inflation from XML and apply a class-specific base style from a 3629 * theme attribute. This constructor of View allows subclasses to use their 3630 * own base style when they are inflating. For example, a Button class's 3631 * constructor would call this version of the super class constructor and 3632 * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this 3633 * allows the theme's button style to modify all of the base view attributes 3634 * (in particular its background) as well as the Button class's attributes. 3635 * 3636 * @param context The Context the view is running in, through which it can 3637 * access the current theme, resources, etc. 3638 * @param attrs The attributes of the XML tag that is inflating the view. 3639 * @param defStyleAttr An attribute in the current theme that contains a 3640 * reference to a style resource that supplies default values for 3641 * the view. Can be 0 to not look for defaults. 3642 * @see #View(Context, AttributeSet) 3643 */ 3644 public View(Context context, AttributeSet attrs, int defStyleAttr) { 3645 this(context, attrs, defStyleAttr, 0); 3646 } 3647 3648 /** 3649 * Perform inflation from XML and apply a class-specific base style from a 3650 * theme attribute or style resource. This constructor of View allows 3651 * subclasses to use their own base style when they are inflating. 3652 * <p> 3653 * When determining the final value of a particular attribute, there are 3654 * four inputs that come into play: 3655 * <ol> 3656 * <li>Any attribute values in the given AttributeSet. 3657 * <li>The style resource specified in the AttributeSet (named "style"). 3658 * <li>The default style specified by <var>defStyleAttr</var>. 3659 * <li>The default style specified by <var>defStyleRes</var>. 3660 * <li>The base values in this theme. 3661 * </ol> 3662 * <p> 3663 * Each of these inputs is considered in-order, with the first listed taking 3664 * precedence over the following ones. In other words, if in the 3665 * AttributeSet you have supplied <code><Button * textColor="#ff000000"></code> 3666 * , then the button's text will <em>always</em> be black, regardless of 3667 * what is specified in any of the styles. 3668 * 3669 * @param context The Context the view is running in, through which it can 3670 * access the current theme, resources, etc. 3671 * @param attrs The attributes of the XML tag that is inflating the view. 3672 * @param defStyleAttr An attribute in the current theme that contains a 3673 * reference to a style resource that supplies default values for 3674 * the view. Can be 0 to not look for defaults. 3675 * @param defStyleRes A resource identifier of a style resource that 3676 * supplies default values for the view, used only if 3677 * defStyleAttr is 0 or can not be found in the theme. Can be 0 3678 * to not look for defaults. 3679 * @see #View(Context, AttributeSet, int) 3680 */ 3681 public View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { 3682 this(context); 3683 3684 final TypedArray a = context.obtainStyledAttributes( 3685 attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes); 3686 3687 if (mDebugViewAttributes) { 3688 saveAttributeData(attrs, a); 3689 } 3690 3691 Drawable background = null; 3692 3693 int leftPadding = -1; 3694 int topPadding = -1; 3695 int rightPadding = -1; 3696 int bottomPadding = -1; 3697 int startPadding = UNDEFINED_PADDING; 3698 int endPadding = UNDEFINED_PADDING; 3699 3700 int padding = -1; 3701 3702 int viewFlagValues = 0; 3703 int viewFlagMasks = 0; 3704 3705 boolean setScrollContainer = false; 3706 3707 int x = 0; 3708 int y = 0; 3709 3710 float tx = 0; 3711 float ty = 0; 3712 float tz = 0; 3713 float elevation = 0; 3714 float rotation = 0; 3715 float rotationX = 0; 3716 float rotationY = 0; 3717 float sx = 1f; 3718 float sy = 1f; 3719 boolean transformSet = false; 3720 3721 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 3722 int overScrollMode = mOverScrollMode; 3723 boolean initializeScrollbars = false; 3724 3725 boolean startPaddingDefined = false; 3726 boolean endPaddingDefined = false; 3727 boolean leftPaddingDefined = false; 3728 boolean rightPaddingDefined = false; 3729 3730 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3731 3732 final int N = a.getIndexCount(); 3733 for (int i = 0; i < N; i++) { 3734 int attr = a.getIndex(i); 3735 switch (attr) { 3736 case com.android.internal.R.styleable.View_background: 3737 background = a.getDrawable(attr); 3738 break; 3739 case com.android.internal.R.styleable.View_padding: 3740 padding = a.getDimensionPixelSize(attr, -1); 3741 mUserPaddingLeftInitial = padding; 3742 mUserPaddingRightInitial = padding; 3743 leftPaddingDefined = true; 3744 rightPaddingDefined = true; 3745 break; 3746 case com.android.internal.R.styleable.View_paddingLeft: 3747 leftPadding = a.getDimensionPixelSize(attr, -1); 3748 mUserPaddingLeftInitial = leftPadding; 3749 leftPaddingDefined = true; 3750 break; 3751 case com.android.internal.R.styleable.View_paddingTop: 3752 topPadding = a.getDimensionPixelSize(attr, -1); 3753 break; 3754 case com.android.internal.R.styleable.View_paddingRight: 3755 rightPadding = a.getDimensionPixelSize(attr, -1); 3756 mUserPaddingRightInitial = rightPadding; 3757 rightPaddingDefined = true; 3758 break; 3759 case com.android.internal.R.styleable.View_paddingBottom: 3760 bottomPadding = a.getDimensionPixelSize(attr, -1); 3761 break; 3762 case com.android.internal.R.styleable.View_paddingStart: 3763 startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3764 startPaddingDefined = (startPadding != UNDEFINED_PADDING); 3765 break; 3766 case com.android.internal.R.styleable.View_paddingEnd: 3767 endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3768 endPaddingDefined = (endPadding != UNDEFINED_PADDING); 3769 break; 3770 case com.android.internal.R.styleable.View_scrollX: 3771 x = a.getDimensionPixelOffset(attr, 0); 3772 break; 3773 case com.android.internal.R.styleable.View_scrollY: 3774 y = a.getDimensionPixelOffset(attr, 0); 3775 break; 3776 case com.android.internal.R.styleable.View_alpha: 3777 setAlpha(a.getFloat(attr, 1f)); 3778 break; 3779 case com.android.internal.R.styleable.View_transformPivotX: 3780 setPivotX(a.getDimensionPixelOffset(attr, 0)); 3781 break; 3782 case com.android.internal.R.styleable.View_transformPivotY: 3783 setPivotY(a.getDimensionPixelOffset(attr, 0)); 3784 break; 3785 case com.android.internal.R.styleable.View_translationX: 3786 tx = a.getDimensionPixelOffset(attr, 0); 3787 transformSet = true; 3788 break; 3789 case com.android.internal.R.styleable.View_translationY: 3790 ty = a.getDimensionPixelOffset(attr, 0); 3791 transformSet = true; 3792 break; 3793 case com.android.internal.R.styleable.View_translationZ: 3794 tz = a.getDimensionPixelOffset(attr, 0); 3795 transformSet = true; 3796 break; 3797 case com.android.internal.R.styleable.View_elevation: 3798 elevation = a.getDimensionPixelOffset(attr, 0); 3799 transformSet = true; 3800 break; 3801 case com.android.internal.R.styleable.View_rotation: 3802 rotation = a.getFloat(attr, 0); 3803 transformSet = true; 3804 break; 3805 case com.android.internal.R.styleable.View_rotationX: 3806 rotationX = a.getFloat(attr, 0); 3807 transformSet = true; 3808 break; 3809 case com.android.internal.R.styleable.View_rotationY: 3810 rotationY = a.getFloat(attr, 0); 3811 transformSet = true; 3812 break; 3813 case com.android.internal.R.styleable.View_scaleX: 3814 sx = a.getFloat(attr, 1f); 3815 transformSet = true; 3816 break; 3817 case com.android.internal.R.styleable.View_scaleY: 3818 sy = a.getFloat(attr, 1f); 3819 transformSet = true; 3820 break; 3821 case com.android.internal.R.styleable.View_id: 3822 mID = a.getResourceId(attr, NO_ID); 3823 break; 3824 case com.android.internal.R.styleable.View_tag: 3825 mTag = a.getText(attr); 3826 break; 3827 case com.android.internal.R.styleable.View_fitsSystemWindows: 3828 if (a.getBoolean(attr, false)) { 3829 viewFlagValues |= FITS_SYSTEM_WINDOWS; 3830 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 3831 } 3832 break; 3833 case com.android.internal.R.styleable.View_focusable: 3834 if (a.getBoolean(attr, false)) { 3835 viewFlagValues |= FOCUSABLE; 3836 viewFlagMasks |= FOCUSABLE_MASK; 3837 } 3838 break; 3839 case com.android.internal.R.styleable.View_focusableInTouchMode: 3840 if (a.getBoolean(attr, false)) { 3841 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 3842 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 3843 } 3844 break; 3845 case com.android.internal.R.styleable.View_clickable: 3846 if (a.getBoolean(attr, false)) { 3847 viewFlagValues |= CLICKABLE; 3848 viewFlagMasks |= CLICKABLE; 3849 } 3850 break; 3851 case com.android.internal.R.styleable.View_longClickable: 3852 if (a.getBoolean(attr, false)) { 3853 viewFlagValues |= LONG_CLICKABLE; 3854 viewFlagMasks |= LONG_CLICKABLE; 3855 } 3856 break; 3857 case com.android.internal.R.styleable.View_saveEnabled: 3858 if (!a.getBoolean(attr, true)) { 3859 viewFlagValues |= SAVE_DISABLED; 3860 viewFlagMasks |= SAVE_DISABLED_MASK; 3861 } 3862 break; 3863 case com.android.internal.R.styleable.View_duplicateParentState: 3864 if (a.getBoolean(attr, false)) { 3865 viewFlagValues |= DUPLICATE_PARENT_STATE; 3866 viewFlagMasks |= DUPLICATE_PARENT_STATE; 3867 } 3868 break; 3869 case com.android.internal.R.styleable.View_visibility: 3870 final int visibility = a.getInt(attr, 0); 3871 if (visibility != 0) { 3872 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 3873 viewFlagMasks |= VISIBILITY_MASK; 3874 } 3875 break; 3876 case com.android.internal.R.styleable.View_layoutDirection: 3877 // Clear any layout direction flags (included resolved bits) already set 3878 mPrivateFlags2 &= 3879 ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK); 3880 // Set the layout direction flags depending on the value of the attribute 3881 final int layoutDirection = a.getInt(attr, -1); 3882 final int value = (layoutDirection != -1) ? 3883 LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT; 3884 mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT); 3885 break; 3886 case com.android.internal.R.styleable.View_drawingCacheQuality: 3887 final int cacheQuality = a.getInt(attr, 0); 3888 if (cacheQuality != 0) { 3889 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 3890 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 3891 } 3892 break; 3893 case com.android.internal.R.styleable.View_contentDescription: 3894 setContentDescription(a.getString(attr)); 3895 break; 3896 case com.android.internal.R.styleable.View_accessibilityTraversalBefore: 3897 setAccessibilityTraversalBefore(a.getResourceId(attr, NO_ID)); 3898 break; 3899 case com.android.internal.R.styleable.View_accessibilityTraversalAfter: 3900 setAccessibilityTraversalAfter(a.getResourceId(attr, NO_ID)); 3901 break; 3902 case com.android.internal.R.styleable.View_labelFor: 3903 setLabelFor(a.getResourceId(attr, NO_ID)); 3904 break; 3905 case com.android.internal.R.styleable.View_soundEffectsEnabled: 3906 if (!a.getBoolean(attr, true)) { 3907 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 3908 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 3909 } 3910 break; 3911 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 3912 if (!a.getBoolean(attr, true)) { 3913 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 3914 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 3915 } 3916 break; 3917 case R.styleable.View_scrollbars: 3918 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 3919 if (scrollbars != SCROLLBARS_NONE) { 3920 viewFlagValues |= scrollbars; 3921 viewFlagMasks |= SCROLLBARS_MASK; 3922 initializeScrollbars = true; 3923 } 3924 break; 3925 //noinspection deprecation 3926 case R.styleable.View_fadingEdge: 3927 if (targetSdkVersion >= ICE_CREAM_SANDWICH) { 3928 // Ignore the attribute starting with ICS 3929 break; 3930 } 3931 // With builds < ICS, fall through and apply fading edges 3932 case R.styleable.View_requiresFadingEdge: 3933 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 3934 if (fadingEdge != FADING_EDGE_NONE) { 3935 viewFlagValues |= fadingEdge; 3936 viewFlagMasks |= FADING_EDGE_MASK; 3937 initializeFadingEdgeInternal(a); 3938 } 3939 break; 3940 case R.styleable.View_scrollbarStyle: 3941 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 3942 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3943 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 3944 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 3945 } 3946 break; 3947 case R.styleable.View_isScrollContainer: 3948 setScrollContainer = true; 3949 if (a.getBoolean(attr, false)) { 3950 setScrollContainer(true); 3951 } 3952 break; 3953 case com.android.internal.R.styleable.View_keepScreenOn: 3954 if (a.getBoolean(attr, false)) { 3955 viewFlagValues |= KEEP_SCREEN_ON; 3956 viewFlagMasks |= KEEP_SCREEN_ON; 3957 } 3958 break; 3959 case R.styleable.View_filterTouchesWhenObscured: 3960 if (a.getBoolean(attr, false)) { 3961 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 3962 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 3963 } 3964 break; 3965 case R.styleable.View_nextFocusLeft: 3966 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 3967 break; 3968 case R.styleable.View_nextFocusRight: 3969 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 3970 break; 3971 case R.styleable.View_nextFocusUp: 3972 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 3973 break; 3974 case R.styleable.View_nextFocusDown: 3975 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 3976 break; 3977 case R.styleable.View_nextFocusForward: 3978 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 3979 break; 3980 case R.styleable.View_minWidth: 3981 mMinWidth = a.getDimensionPixelSize(attr, 0); 3982 break; 3983 case R.styleable.View_minHeight: 3984 mMinHeight = a.getDimensionPixelSize(attr, 0); 3985 break; 3986 case R.styleable.View_onClick: 3987 if (context.isRestricted()) { 3988 throw new IllegalStateException("The android:onClick attribute cannot " 3989 + "be used within a restricted context"); 3990 } 3991 3992 final String handlerName = a.getString(attr); 3993 if (handlerName != null) { 3994 setOnClickListener(new OnClickListener() { 3995 private Method mHandler; 3996 3997 public void onClick(View v) { 3998 if (mHandler == null) { 3999 try { 4000 mHandler = getContext().getClass().getMethod(handlerName, 4001 View.class); 4002 } catch (NoSuchMethodException e) { 4003 int id = getId(); 4004 String idText = id == NO_ID ? "" : " with id '" 4005 + getContext().getResources().getResourceEntryName( 4006 id) + "'"; 4007 throw new IllegalStateException("Could not find a method " + 4008 handlerName + "(View) in the activity " 4009 + getContext().getClass() + " for onClick handler" 4010 + " on view " + View.this.getClass() + idText, e); 4011 } 4012 } 4013 4014 try { 4015 mHandler.invoke(getContext(), View.this); 4016 } catch (IllegalAccessException e) { 4017 throw new IllegalStateException("Could not execute non " 4018 + "public method of the activity", e); 4019 } catch (InvocationTargetException e) { 4020 throw new IllegalStateException("Could not execute " 4021 + "method of the activity", e); 4022 } 4023 } 4024 }); 4025 } 4026 break; 4027 case R.styleable.View_overScrollMode: 4028 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 4029 break; 4030 case R.styleable.View_verticalScrollbarPosition: 4031 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 4032 break; 4033 case R.styleable.View_layerType: 4034 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 4035 break; 4036 case R.styleable.View_textDirection: 4037 // Clear any text direction flag already set 4038 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 4039 // Set the text direction flags depending on the value of the attribute 4040 final int textDirection = a.getInt(attr, -1); 4041 if (textDirection != -1) { 4042 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection]; 4043 } 4044 break; 4045 case R.styleable.View_textAlignment: 4046 // Clear any text alignment flag already set 4047 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 4048 // Set the text alignment flag depending on the value of the attribute 4049 final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT); 4050 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment]; 4051 break; 4052 case R.styleable.View_importantForAccessibility: 4053 setImportantForAccessibility(a.getInt(attr, 4054 IMPORTANT_FOR_ACCESSIBILITY_DEFAULT)); 4055 break; 4056 case R.styleable.View_accessibilityLiveRegion: 4057 setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT)); 4058 break; 4059 case R.styleable.View_transitionName: 4060 setTransitionName(a.getString(attr)); 4061 break; 4062 case R.styleable.View_nestedScrollingEnabled: 4063 setNestedScrollingEnabled(a.getBoolean(attr, false)); 4064 break; 4065 case R.styleable.View_stateListAnimator: 4066 setStateListAnimator(AnimatorInflater.loadStateListAnimator(context, 4067 a.getResourceId(attr, 0))); 4068 break; 4069 case R.styleable.View_backgroundTint: 4070 // This will get applied later during setBackground(). 4071 if (mBackgroundTint == null) { 4072 mBackgroundTint = new TintInfo(); 4073 } 4074 mBackgroundTint.mTintList = a.getColorStateList( 4075 R.styleable.View_backgroundTint); 4076 mBackgroundTint.mHasTintList = true; 4077 break; 4078 case R.styleable.View_backgroundTintMode: 4079 // This will get applied later during setBackground(). 4080 if (mBackgroundTint == null) { 4081 mBackgroundTint = new TintInfo(); 4082 } 4083 mBackgroundTint.mTintMode = Drawable.parseTintMode(a.getInt( 4084 R.styleable.View_backgroundTintMode, -1), null); 4085 mBackgroundTint.mHasTintMode = true; 4086 break; 4087 case R.styleable.View_outlineProvider: 4088 setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider, 4089 PROVIDER_BACKGROUND)); 4090 break; 4091 } 4092 } 4093 4094 setOverScrollMode(overScrollMode); 4095 4096 // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet 4097 // the resolved layout direction). Those cached values will be used later during padding 4098 // resolution. 4099 mUserPaddingStart = startPadding; 4100 mUserPaddingEnd = endPadding; 4101 4102 if (background != null) { 4103 setBackground(background); 4104 } 4105 4106 // setBackground above will record that padding is currently provided by the background. 4107 // If we have padding specified via xml, record that here instead and use it. 4108 mLeftPaddingDefined = leftPaddingDefined; 4109 mRightPaddingDefined = rightPaddingDefined; 4110 4111 if (padding >= 0) { 4112 leftPadding = padding; 4113 topPadding = padding; 4114 rightPadding = padding; 4115 bottomPadding = padding; 4116 mUserPaddingLeftInitial = padding; 4117 mUserPaddingRightInitial = padding; 4118 } 4119 4120 if (isRtlCompatibilityMode()) { 4121 // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case. 4122 // left / right padding are used if defined (meaning here nothing to do). If they are not 4123 // defined and start / end padding are defined (e.g. in Frameworks resources), then we use 4124 // start / end and resolve them as left / right (layout direction is not taken into account). 4125 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4126 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4127 // defined. 4128 if (!mLeftPaddingDefined && startPaddingDefined) { 4129 leftPadding = startPadding; 4130 } 4131 mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial; 4132 if (!mRightPaddingDefined && endPaddingDefined) { 4133 rightPadding = endPadding; 4134 } 4135 mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial; 4136 } else { 4137 // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right 4138 // values defined. Otherwise, left /right values are used. 4139 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4140 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4141 // defined. 4142 final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined; 4143 4144 if (mLeftPaddingDefined && !hasRelativePadding) { 4145 mUserPaddingLeftInitial = leftPadding; 4146 } 4147 if (mRightPaddingDefined && !hasRelativePadding) { 4148 mUserPaddingRightInitial = rightPadding; 4149 } 4150 } 4151 4152 internalSetPadding( 4153 mUserPaddingLeftInitial, 4154 topPadding >= 0 ? topPadding : mPaddingTop, 4155 mUserPaddingRightInitial, 4156 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 4157 4158 if (viewFlagMasks != 0) { 4159 setFlags(viewFlagValues, viewFlagMasks); 4160 } 4161 4162 if (initializeScrollbars) { 4163 initializeScrollbarsInternal(a); 4164 } 4165 4166 a.recycle(); 4167 4168 // Needs to be called after mViewFlags is set 4169 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 4170 recomputePadding(); 4171 } 4172 4173 if (x != 0 || y != 0) { 4174 scrollTo(x, y); 4175 } 4176 4177 if (transformSet) { 4178 setTranslationX(tx); 4179 setTranslationY(ty); 4180 setTranslationZ(tz); 4181 setElevation(elevation); 4182 setRotation(rotation); 4183 setRotationX(rotationX); 4184 setRotationY(rotationY); 4185 setScaleX(sx); 4186 setScaleY(sy); 4187 } 4188 4189 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 4190 setScrollContainer(true); 4191 } 4192 4193 computeOpaqueFlags(); 4194 } 4195 4196 /** 4197 * Non-public constructor for use in testing 4198 */ 4199 View() { 4200 mResources = null; 4201 mRenderNode = RenderNode.create(getClass().getName(), this); 4202 } 4203 4204 private static SparseArray<String> getAttributeMap() { 4205 if (mAttributeMap == null) { 4206 mAttributeMap = new SparseArray<String>(); 4207 } 4208 return mAttributeMap; 4209 } 4210 4211 private void saveAttributeData(AttributeSet attrs, TypedArray a) { 4212 int length = ((attrs == null ? 0 : attrs.getAttributeCount()) + a.getIndexCount()) * 2; 4213 mAttributes = new String[length]; 4214 4215 int i = 0; 4216 if (attrs != null) { 4217 for (i = 0; i < attrs.getAttributeCount(); i += 2) { 4218 mAttributes[i] = attrs.getAttributeName(i); 4219 mAttributes[i + 1] = attrs.getAttributeValue(i); 4220 } 4221 4222 } 4223 4224 SparseArray<String> attributeMap = getAttributeMap(); 4225 for (int j = 0; j < a.length(); ++j) { 4226 if (a.hasValue(j)) { 4227 try { 4228 int resourceId = a.getResourceId(j, 0); 4229 if (resourceId == 0) { 4230 continue; 4231 } 4232 4233 String resourceName = attributeMap.get(resourceId); 4234 if (resourceName == null) { 4235 resourceName = a.getResources().getResourceName(resourceId); 4236 attributeMap.put(resourceId, resourceName); 4237 } 4238 4239 mAttributes[i] = resourceName; 4240 mAttributes[i + 1] = a.getText(j).toString(); 4241 i += 2; 4242 } catch (Resources.NotFoundException e) { 4243 // if we can't get the resource name, we just ignore it 4244 } 4245 } 4246 } 4247 } 4248 4249 public String toString() { 4250 StringBuilder out = new StringBuilder(128); 4251 out.append(getClass().getName()); 4252 out.append('{'); 4253 out.append(Integer.toHexString(System.identityHashCode(this))); 4254 out.append(' '); 4255 switch (mViewFlags&VISIBILITY_MASK) { 4256 case VISIBLE: out.append('V'); break; 4257 case INVISIBLE: out.append('I'); break; 4258 case GONE: out.append('G'); break; 4259 default: out.append('.'); break; 4260 } 4261 out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.'); 4262 out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.'); 4263 out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D'); 4264 out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.'); 4265 out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.'); 4266 out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.'); 4267 out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.'); 4268 out.append(' '); 4269 out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.'); 4270 out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.'); 4271 out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.'); 4272 if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) { 4273 out.append('p'); 4274 } else { 4275 out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.'); 4276 } 4277 out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.'); 4278 out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.'); 4279 out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.'); 4280 out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.'); 4281 out.append(' '); 4282 out.append(mLeft); 4283 out.append(','); 4284 out.append(mTop); 4285 out.append('-'); 4286 out.append(mRight); 4287 out.append(','); 4288 out.append(mBottom); 4289 final int id = getId(); 4290 if (id != NO_ID) { 4291 out.append(" #"); 4292 out.append(Integer.toHexString(id)); 4293 final Resources r = mResources; 4294 if (Resources.resourceHasPackage(id) && r != null) { 4295 try { 4296 String pkgname; 4297 switch (id&0xff000000) { 4298 case 0x7f000000: 4299 pkgname="app"; 4300 break; 4301 case 0x01000000: 4302 pkgname="android"; 4303 break; 4304 default: 4305 pkgname = r.getResourcePackageName(id); 4306 break; 4307 } 4308 String typename = r.getResourceTypeName(id); 4309 String entryname = r.getResourceEntryName(id); 4310 out.append(" "); 4311 out.append(pkgname); 4312 out.append(":"); 4313 out.append(typename); 4314 out.append("/"); 4315 out.append(entryname); 4316 } catch (Resources.NotFoundException e) { 4317 } 4318 } 4319 } 4320 out.append("}"); 4321 return out.toString(); 4322 } 4323 4324 /** 4325 * <p> 4326 * Initializes the fading edges from a given set of styled attributes. This 4327 * method should be called by subclasses that need fading edges and when an 4328 * instance of these subclasses is created programmatically rather than 4329 * being inflated from XML. This method is automatically called when the XML 4330 * is inflated. 4331 * </p> 4332 * 4333 * @param a the styled attributes set to initialize the fading edges from 4334 * 4335 * @removed 4336 */ 4337 protected void initializeFadingEdge(TypedArray a) { 4338 // This method probably shouldn't have been included in the SDK to begin with. 4339 // It relies on 'a' having been initialized using an attribute filter array that is 4340 // not publicly available to the SDK. The old method has been renamed 4341 // to initializeFadingEdgeInternal and hidden for framework use only; 4342 // this one initializes using defaults to make it safe to call for apps. 4343 4344 TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View); 4345 4346 initializeFadingEdgeInternal(arr); 4347 4348 arr.recycle(); 4349 } 4350 4351 /** 4352 * <p> 4353 * Initializes the fading edges from a given set of styled attributes. This 4354 * method should be called by subclasses that need fading edges and when an 4355 * instance of these subclasses is created programmatically rather than 4356 * being inflated from XML. This method is automatically called when the XML 4357 * is inflated. 4358 * </p> 4359 * 4360 * @param a the styled attributes set to initialize the fading edges from 4361 * @hide This is the real method; the public one is shimmed to be safe to call from apps. 4362 */ 4363 protected void initializeFadingEdgeInternal(TypedArray a) { 4364 initScrollCache(); 4365 4366 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 4367 R.styleable.View_fadingEdgeLength, 4368 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 4369 } 4370 4371 /** 4372 * Returns the size of the vertical faded edges used to indicate that more 4373 * content in this view is visible. 4374 * 4375 * @return The size in pixels of the vertical faded edge or 0 if vertical 4376 * faded edges are not enabled for this view. 4377 * @attr ref android.R.styleable#View_fadingEdgeLength 4378 */ 4379 public int getVerticalFadingEdgeLength() { 4380 if (isVerticalFadingEdgeEnabled()) { 4381 ScrollabilityCache cache = mScrollCache; 4382 if (cache != null) { 4383 return cache.fadingEdgeLength; 4384 } 4385 } 4386 return 0; 4387 } 4388 4389 /** 4390 * Set the size of the faded edge used to indicate that more content in this 4391 * view is available. Will not change whether the fading edge is enabled; use 4392 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 4393 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 4394 * for the vertical or horizontal fading edges. 4395 * 4396 * @param length The size in pixels of the faded edge used to indicate that more 4397 * content in this view is visible. 4398 */ 4399 public void setFadingEdgeLength(int length) { 4400 initScrollCache(); 4401 mScrollCache.fadingEdgeLength = length; 4402 } 4403 4404 /** 4405 * Returns the size of the horizontal faded edges used to indicate that more 4406 * content in this view is visible. 4407 * 4408 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 4409 * faded edges are not enabled for this view. 4410 * @attr ref android.R.styleable#View_fadingEdgeLength 4411 */ 4412 public int getHorizontalFadingEdgeLength() { 4413 if (isHorizontalFadingEdgeEnabled()) { 4414 ScrollabilityCache cache = mScrollCache; 4415 if (cache != null) { 4416 return cache.fadingEdgeLength; 4417 } 4418 } 4419 return 0; 4420 } 4421 4422 /** 4423 * Returns the width of the vertical scrollbar. 4424 * 4425 * @return The width in pixels of the vertical scrollbar or 0 if there 4426 * is no vertical scrollbar. 4427 */ 4428 public int getVerticalScrollbarWidth() { 4429 ScrollabilityCache cache = mScrollCache; 4430 if (cache != null) { 4431 ScrollBarDrawable scrollBar = cache.scrollBar; 4432 if (scrollBar != null) { 4433 int size = scrollBar.getSize(true); 4434 if (size <= 0) { 4435 size = cache.scrollBarSize; 4436 } 4437 return size; 4438 } 4439 return 0; 4440 } 4441 return 0; 4442 } 4443 4444 /** 4445 * Returns the height of the horizontal scrollbar. 4446 * 4447 * @return The height in pixels of the horizontal scrollbar or 0 if 4448 * there is no horizontal scrollbar. 4449 */ 4450 protected int getHorizontalScrollbarHeight() { 4451 ScrollabilityCache cache = mScrollCache; 4452 if (cache != null) { 4453 ScrollBarDrawable scrollBar = cache.scrollBar; 4454 if (scrollBar != null) { 4455 int size = scrollBar.getSize(false); 4456 if (size <= 0) { 4457 size = cache.scrollBarSize; 4458 } 4459 return size; 4460 } 4461 return 0; 4462 } 4463 return 0; 4464 } 4465 4466 /** 4467 * <p> 4468 * Initializes the scrollbars from a given set of styled attributes. This 4469 * method should be called by subclasses that need scrollbars and when an 4470 * instance of these subclasses is created programmatically rather than 4471 * being inflated from XML. This method is automatically called when the XML 4472 * is inflated. 4473 * </p> 4474 * 4475 * @param a the styled attributes set to initialize the scrollbars from 4476 * 4477 * @removed 4478 */ 4479 protected void initializeScrollbars(TypedArray a) { 4480 // It's not safe to use this method from apps. The parameter 'a' must have been obtained 4481 // using the View filter array which is not available to the SDK. As such, internal 4482 // framework usage now uses initializeScrollbarsInternal and we grab a default 4483 // TypedArray with the right filter instead here. 4484 TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View); 4485 4486 initializeScrollbarsInternal(arr); 4487 4488 // We ignored the method parameter. Recycle the one we actually did use. 4489 arr.recycle(); 4490 } 4491 4492 /** 4493 * <p> 4494 * Initializes the scrollbars from a given set of styled attributes. This 4495 * method should be called by subclasses that need scrollbars and when an 4496 * instance of these subclasses is created programmatically rather than 4497 * being inflated from XML. This method is automatically called when the XML 4498 * is inflated. 4499 * </p> 4500 * 4501 * @param a the styled attributes set to initialize the scrollbars from 4502 * @hide 4503 */ 4504 protected void initializeScrollbarsInternal(TypedArray a) { 4505 initScrollCache(); 4506 4507 final ScrollabilityCache scrollabilityCache = mScrollCache; 4508 4509 if (scrollabilityCache.scrollBar == null) { 4510 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 4511 } 4512 4513 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 4514 4515 if (!fadeScrollbars) { 4516 scrollabilityCache.state = ScrollabilityCache.ON; 4517 } 4518 scrollabilityCache.fadeScrollBars = fadeScrollbars; 4519 4520 4521 scrollabilityCache.scrollBarFadeDuration = a.getInt( 4522 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 4523 .getScrollBarFadeDuration()); 4524 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 4525 R.styleable.View_scrollbarDefaultDelayBeforeFade, 4526 ViewConfiguration.getScrollDefaultDelay()); 4527 4528 4529 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 4530 com.android.internal.R.styleable.View_scrollbarSize, 4531 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 4532 4533 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 4534 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 4535 4536 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 4537 if (thumb != null) { 4538 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 4539 } 4540 4541 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 4542 false); 4543 if (alwaysDraw) { 4544 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 4545 } 4546 4547 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 4548 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 4549 4550 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 4551 if (thumb != null) { 4552 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 4553 } 4554 4555 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 4556 false); 4557 if (alwaysDraw) { 4558 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 4559 } 4560 4561 // Apply layout direction to the new Drawables if needed 4562 final int layoutDirection = getLayoutDirection(); 4563 if (track != null) { 4564 track.setLayoutDirection(layoutDirection); 4565 } 4566 if (thumb != null) { 4567 thumb.setLayoutDirection(layoutDirection); 4568 } 4569 4570 // Re-apply user/background padding so that scrollbar(s) get added 4571 resolvePadding(); 4572 } 4573 4574 /** 4575 * <p> 4576 * Initalizes the scrollability cache if necessary. 4577 * </p> 4578 */ 4579 private void initScrollCache() { 4580 if (mScrollCache == null) { 4581 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 4582 } 4583 } 4584 4585 private ScrollabilityCache getScrollCache() { 4586 initScrollCache(); 4587 return mScrollCache; 4588 } 4589 4590 /** 4591 * Set the position of the vertical scroll bar. Should be one of 4592 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 4593 * {@link #SCROLLBAR_POSITION_RIGHT}. 4594 * 4595 * @param position Where the vertical scroll bar should be positioned. 4596 */ 4597 public void setVerticalScrollbarPosition(int position) { 4598 if (mVerticalScrollbarPosition != position) { 4599 mVerticalScrollbarPosition = position; 4600 computeOpaqueFlags(); 4601 resolvePadding(); 4602 } 4603 } 4604 4605 /** 4606 * @return The position where the vertical scroll bar will show, if applicable. 4607 * @see #setVerticalScrollbarPosition(int) 4608 */ 4609 public int getVerticalScrollbarPosition() { 4610 return mVerticalScrollbarPosition; 4611 } 4612 4613 ListenerInfo getListenerInfo() { 4614 if (mListenerInfo != null) { 4615 return mListenerInfo; 4616 } 4617 mListenerInfo = new ListenerInfo(); 4618 return mListenerInfo; 4619 } 4620 4621 /** 4622 * Register a callback to be invoked when the scroll position of this view 4623 * changed. 4624 * 4625 * @param l The callback that will run. 4626 * @hide Only used internally. 4627 */ 4628 public void setOnScrollChangeListener(OnScrollChangeListener l) { 4629 getListenerInfo().mOnScrollChangeListener = l; 4630 } 4631 4632 /** 4633 * Register a callback to be invoked when focus of this view changed. 4634 * 4635 * @param l The callback that will run. 4636 */ 4637 public void setOnFocusChangeListener(OnFocusChangeListener l) { 4638 getListenerInfo().mOnFocusChangeListener = l; 4639 } 4640 4641 /** 4642 * Add a listener that will be called when the bounds of the view change due to 4643 * layout processing. 4644 * 4645 * @param listener The listener that will be called when layout bounds change. 4646 */ 4647 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 4648 ListenerInfo li = getListenerInfo(); 4649 if (li.mOnLayoutChangeListeners == null) { 4650 li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 4651 } 4652 if (!li.mOnLayoutChangeListeners.contains(listener)) { 4653 li.mOnLayoutChangeListeners.add(listener); 4654 } 4655 } 4656 4657 /** 4658 * Remove a listener for layout changes. 4659 * 4660 * @param listener The listener for layout bounds change. 4661 */ 4662 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 4663 ListenerInfo li = mListenerInfo; 4664 if (li == null || li.mOnLayoutChangeListeners == null) { 4665 return; 4666 } 4667 li.mOnLayoutChangeListeners.remove(listener); 4668 } 4669 4670 /** 4671 * Add a listener for attach state changes. 4672 * 4673 * This listener will be called whenever this view is attached or detached 4674 * from a window. Remove the listener using 4675 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 4676 * 4677 * @param listener Listener to attach 4678 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 4679 */ 4680 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4681 ListenerInfo li = getListenerInfo(); 4682 if (li.mOnAttachStateChangeListeners == null) { 4683 li.mOnAttachStateChangeListeners 4684 = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 4685 } 4686 li.mOnAttachStateChangeListeners.add(listener); 4687 } 4688 4689 /** 4690 * Remove a listener for attach state changes. The listener will receive no further 4691 * notification of window attach/detach events. 4692 * 4693 * @param listener Listener to remove 4694 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 4695 */ 4696 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4697 ListenerInfo li = mListenerInfo; 4698 if (li == null || li.mOnAttachStateChangeListeners == null) { 4699 return; 4700 } 4701 li.mOnAttachStateChangeListeners.remove(listener); 4702 } 4703 4704 /** 4705 * Returns the focus-change callback registered for this view. 4706 * 4707 * @return The callback, or null if one is not registered. 4708 */ 4709 public OnFocusChangeListener getOnFocusChangeListener() { 4710 ListenerInfo li = mListenerInfo; 4711 return li != null ? li.mOnFocusChangeListener : null; 4712 } 4713 4714 /** 4715 * Register a callback to be invoked when this view is clicked. If this view is not 4716 * clickable, it becomes clickable. 4717 * 4718 * @param l The callback that will run 4719 * 4720 * @see #setClickable(boolean) 4721 */ 4722 public void setOnClickListener(OnClickListener l) { 4723 if (!isClickable()) { 4724 setClickable(true); 4725 } 4726 getListenerInfo().mOnClickListener = l; 4727 } 4728 4729 /** 4730 * Return whether this view has an attached OnClickListener. Returns 4731 * true if there is a listener, false if there is none. 4732 */ 4733 public boolean hasOnClickListeners() { 4734 ListenerInfo li = mListenerInfo; 4735 return (li != null && li.mOnClickListener != null); 4736 } 4737 4738 /** 4739 * Register a callback to be invoked when this view is clicked and held. If this view is not 4740 * long clickable, it becomes long clickable. 4741 * 4742 * @param l The callback that will run 4743 * 4744 * @see #setLongClickable(boolean) 4745 */ 4746 public void setOnLongClickListener(OnLongClickListener l) { 4747 if (!isLongClickable()) { 4748 setLongClickable(true); 4749 } 4750 getListenerInfo().mOnLongClickListener = l; 4751 } 4752 4753 /** 4754 * Register a callback to be invoked when the context menu for this view is 4755 * being built. If this view is not long clickable, it becomes long clickable. 4756 * 4757 * @param l The callback that will run 4758 * 4759 */ 4760 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 4761 if (!isLongClickable()) { 4762 setLongClickable(true); 4763 } 4764 getListenerInfo().mOnCreateContextMenuListener = l; 4765 } 4766 4767 /** 4768 * Call this view's OnClickListener, if it is defined. Performs all normal 4769 * actions associated with clicking: reporting accessibility event, playing 4770 * a sound, etc. 4771 * 4772 * @return True there was an assigned OnClickListener that was called, false 4773 * otherwise is returned. 4774 */ 4775 public boolean performClick() { 4776 final boolean result; 4777 final ListenerInfo li = mListenerInfo; 4778 if (li != null && li.mOnClickListener != null) { 4779 playSoundEffect(SoundEffectConstants.CLICK); 4780 li.mOnClickListener.onClick(this); 4781 result = true; 4782 } else { 4783 result = false; 4784 } 4785 4786 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 4787 return result; 4788 } 4789 4790 /** 4791 * Directly call any attached OnClickListener. Unlike {@link #performClick()}, 4792 * this only calls the listener, and does not do any associated clicking 4793 * actions like reporting an accessibility event. 4794 * 4795 * @return True there was an assigned OnClickListener that was called, false 4796 * otherwise is returned. 4797 */ 4798 public boolean callOnClick() { 4799 ListenerInfo li = mListenerInfo; 4800 if (li != null && li.mOnClickListener != null) { 4801 li.mOnClickListener.onClick(this); 4802 return true; 4803 } 4804 return false; 4805 } 4806 4807 /** 4808 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the 4809 * OnLongClickListener did not consume the event. 4810 * 4811 * @return True if one of the above receivers consumed the event, false otherwise. 4812 */ 4813 public boolean performLongClick() { 4814 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 4815 4816 boolean handled = false; 4817 ListenerInfo li = mListenerInfo; 4818 if (li != null && li.mOnLongClickListener != null) { 4819 handled = li.mOnLongClickListener.onLongClick(View.this); 4820 } 4821 if (!handled) { 4822 handled = showContextMenu(); 4823 } 4824 if (handled) { 4825 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 4826 } 4827 return handled; 4828 } 4829 4830 /** 4831 * Performs button-related actions during a touch down event. 4832 * 4833 * @param event The event. 4834 * @return True if the down was consumed. 4835 * 4836 * @hide 4837 */ 4838 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 4839 if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 4840 if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) { 4841 return true; 4842 } 4843 } 4844 return false; 4845 } 4846 4847 /** 4848 * Bring up the context menu for this view. 4849 * 4850 * @return Whether a context menu was displayed. 4851 */ 4852 public boolean showContextMenu() { 4853 return getParent().showContextMenuForChild(this); 4854 } 4855 4856 /** 4857 * Bring up the context menu for this view, referring to the item under the specified point. 4858 * 4859 * @param x The referenced x coordinate. 4860 * @param y The referenced y coordinate. 4861 * @param metaState The keyboard modifiers that were pressed. 4862 * @return Whether a context menu was displayed. 4863 * 4864 * @hide 4865 */ 4866 public boolean showContextMenu(float x, float y, int metaState) { 4867 return showContextMenu(); 4868 } 4869 4870 /** 4871 * Start an action mode. 4872 * 4873 * @param callback Callback that will control the lifecycle of the action mode 4874 * @return The new action mode if it is started, null otherwise 4875 * 4876 * @see ActionMode 4877 */ 4878 public ActionMode startActionMode(ActionMode.Callback callback) { 4879 ViewParent parent = getParent(); 4880 if (parent == null) return null; 4881 return parent.startActionModeForChild(this, callback); 4882 } 4883 4884 /** 4885 * Register a callback to be invoked when a hardware key is pressed in this view. 4886 * Key presses in software input methods will generally not trigger the methods of 4887 * this listener. 4888 * @param l the key listener to attach to this view 4889 */ 4890 public void setOnKeyListener(OnKeyListener l) { 4891 getListenerInfo().mOnKeyListener = l; 4892 } 4893 4894 /** 4895 * Register a callback to be invoked when a touch event is sent to this view. 4896 * @param l the touch listener to attach to this view 4897 */ 4898 public void setOnTouchListener(OnTouchListener l) { 4899 getListenerInfo().mOnTouchListener = l; 4900 } 4901 4902 /** 4903 * Register a callback to be invoked when a generic motion event is sent to this view. 4904 * @param l the generic motion listener to attach to this view 4905 */ 4906 public void setOnGenericMotionListener(OnGenericMotionListener l) { 4907 getListenerInfo().mOnGenericMotionListener = l; 4908 } 4909 4910 /** 4911 * Register a callback to be invoked when a hover event is sent to this view. 4912 * @param l the hover listener to attach to this view 4913 */ 4914 public void setOnHoverListener(OnHoverListener l) { 4915 getListenerInfo().mOnHoverListener = l; 4916 } 4917 4918 /** 4919 * Register a drag event listener callback object for this View. The parameter is 4920 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 4921 * View, the system calls the 4922 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 4923 * @param l An implementation of {@link android.view.View.OnDragListener}. 4924 */ 4925 public void setOnDragListener(OnDragListener l) { 4926 getListenerInfo().mOnDragListener = l; 4927 } 4928 4929 /** 4930 * Give this view focus. This will cause 4931 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 4932 * 4933 * Note: this does not check whether this {@link View} should get focus, it just 4934 * gives it focus no matter what. It should only be called internally by framework 4935 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 4936 * 4937 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 4938 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 4939 * focus moved when requestFocus() is called. It may not always 4940 * apply, in which case use the default View.FOCUS_DOWN. 4941 * @param previouslyFocusedRect The rectangle of the view that had focus 4942 * prior in this View's coordinate system. 4943 */ 4944 void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) { 4945 if (DBG) { 4946 System.out.println(this + " requestFocus()"); 4947 } 4948 4949 if ((mPrivateFlags & PFLAG_FOCUSED) == 0) { 4950 mPrivateFlags |= PFLAG_FOCUSED; 4951 4952 View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null; 4953 4954 if (mParent != null) { 4955 mParent.requestChildFocus(this, this); 4956 } 4957 4958 if (mAttachInfo != null) { 4959 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this); 4960 } 4961 4962 onFocusChanged(true, direction, previouslyFocusedRect); 4963 refreshDrawableState(); 4964 } 4965 } 4966 4967 /** 4968 * Populates <code>outRect</code> with the hotspot bounds. By default, 4969 * the hotspot bounds are identical to the screen bounds. 4970 * 4971 * @param outRect rect to populate with hotspot bounds 4972 * @hide Only for internal use by views and widgets. 4973 */ 4974 public void getHotspotBounds(Rect outRect) { 4975 final Drawable background = getBackground(); 4976 if (background != null) { 4977 background.getHotspotBounds(outRect); 4978 } else { 4979 getBoundsOnScreen(outRect); 4980 } 4981 } 4982 4983 /** 4984 * Request that a rectangle of this view be visible on the screen, 4985 * scrolling if necessary just enough. 4986 * 4987 * <p>A View should call this if it maintains some notion of which part 4988 * of its content is interesting. For example, a text editing view 4989 * should call this when its cursor moves. 4990 * 4991 * @param rectangle The rectangle. 4992 * @return Whether any parent scrolled. 4993 */ 4994 public boolean requestRectangleOnScreen(Rect rectangle) { 4995 return requestRectangleOnScreen(rectangle, false); 4996 } 4997 4998 /** 4999 * Request that a rectangle of this view be visible on the screen, 5000 * scrolling if necessary just enough. 5001 * 5002 * <p>A View should call this if it maintains some notion of which part 5003 * of its content is interesting. For example, a text editing view 5004 * should call this when its cursor moves. 5005 * 5006 * <p>When <code>immediate</code> is set to true, scrolling will not be 5007 * animated. 5008 * 5009 * @param rectangle The rectangle. 5010 * @param immediate True to forbid animated scrolling, false otherwise 5011 * @return Whether any parent scrolled. 5012 */ 5013 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 5014 if (mParent == null) { 5015 return false; 5016 } 5017 5018 View child = this; 5019 5020 RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF(); 5021 position.set(rectangle); 5022 5023 ViewParent parent = mParent; 5024 boolean scrolled = false; 5025 while (parent != null) { 5026 rectangle.set((int) position.left, (int) position.top, 5027 (int) position.right, (int) position.bottom); 5028 5029 scrolled |= parent.requestChildRectangleOnScreen(child, 5030 rectangle, immediate); 5031 5032 if (!child.hasIdentityMatrix()) { 5033 child.getMatrix().mapRect(position); 5034 } 5035 5036 position.offset(child.mLeft, child.mTop); 5037 5038 if (!(parent instanceof View)) { 5039 break; 5040 } 5041 5042 View parentView = (View) parent; 5043 5044 position.offset(-parentView.getScrollX(), -parentView.getScrollY()); 5045 5046 child = parentView; 5047 parent = child.getParent(); 5048 } 5049 5050 return scrolled; 5051 } 5052 5053 /** 5054 * Called when this view wants to give up focus. If focus is cleared 5055 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called. 5056 * <p> 5057 * <strong>Note:</strong> When a View clears focus the framework is trying 5058 * to give focus to the first focusable View from the top. Hence, if this 5059 * View is the first from the top that can take focus, then all callbacks 5060 * related to clearing focus will be invoked after which the framework will 5061 * give focus to this view. 5062 * </p> 5063 */ 5064 public void clearFocus() { 5065 if (DBG) { 5066 System.out.println(this + " clearFocus()"); 5067 } 5068 5069 clearFocusInternal(null, true, true); 5070 } 5071 5072 /** 5073 * Clears focus from the view, optionally propagating the change up through 5074 * the parent hierarchy and requesting that the root view place new focus. 5075 * 5076 * @param propagate whether to propagate the change up through the parent 5077 * hierarchy 5078 * @param refocus when propagate is true, specifies whether to request the 5079 * root view place new focus 5080 */ 5081 void clearFocusInternal(View focused, boolean propagate, boolean refocus) { 5082 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 5083 mPrivateFlags &= ~PFLAG_FOCUSED; 5084 5085 if (propagate && mParent != null) { 5086 mParent.clearChildFocus(this); 5087 } 5088 5089 onFocusChanged(false, 0, null); 5090 refreshDrawableState(); 5091 5092 if (propagate && (!refocus || !rootViewRequestFocus())) { 5093 notifyGlobalFocusCleared(this); 5094 } 5095 } 5096 } 5097 5098 void notifyGlobalFocusCleared(View oldFocus) { 5099 if (oldFocus != null && mAttachInfo != null) { 5100 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null); 5101 } 5102 } 5103 5104 boolean rootViewRequestFocus() { 5105 final View root = getRootView(); 5106 return root != null && root.requestFocus(); 5107 } 5108 5109 /** 5110 * Called internally by the view system when a new view is getting focus. 5111 * This is what clears the old focus. 5112 * <p> 5113 * <b>NOTE:</b> The parent view's focused child must be updated manually 5114 * after calling this method. Otherwise, the view hierarchy may be left in 5115 * an inconstent state. 5116 */ 5117 void unFocus(View focused) { 5118 if (DBG) { 5119 System.out.println(this + " unFocus()"); 5120 } 5121 5122 clearFocusInternal(focused, false, false); 5123 } 5124 5125 /** 5126 * Returns true if this view has focus iteself, or is the ancestor of the 5127 * view that has focus. 5128 * 5129 * @return True if this view has or contains focus, false otherwise. 5130 */ 5131 @ViewDebug.ExportedProperty(category = "focus") 5132 public boolean hasFocus() { 5133 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 5134 } 5135 5136 /** 5137 * Returns true if this view is focusable or if it contains a reachable View 5138 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 5139 * is a View whose parents do not block descendants focus. 5140 * 5141 * Only {@link #VISIBLE} views are considered focusable. 5142 * 5143 * @return True if the view is focusable or if the view contains a focusable 5144 * View, false otherwise. 5145 * 5146 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 5147 * @see ViewGroup#getTouchscreenBlocksFocus() 5148 */ 5149 public boolean hasFocusable() { 5150 if (!isFocusableInTouchMode()) { 5151 for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) { 5152 final ViewGroup g = (ViewGroup) p; 5153 if (g.shouldBlockFocusForTouchscreen()) { 5154 return false; 5155 } 5156 } 5157 } 5158 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 5159 } 5160 5161 /** 5162 * Called by the view system when the focus state of this view changes. 5163 * When the focus change event is caused by directional navigation, direction 5164 * and previouslyFocusedRect provide insight into where the focus is coming from. 5165 * When overriding, be sure to call up through to the super class so that 5166 * the standard focus handling will occur. 5167 * 5168 * @param gainFocus True if the View has focus; false otherwise. 5169 * @param direction The direction focus has moved when requestFocus() 5170 * is called to give this view focus. Values are 5171 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 5172 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 5173 * It may not always apply, in which case use the default. 5174 * @param previouslyFocusedRect The rectangle, in this view's coordinate 5175 * system, of the previously focused view. If applicable, this will be 5176 * passed in as finer grained information about where the focus is coming 5177 * from (in addition to direction). Will be <code>null</code> otherwise. 5178 */ 5179 protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction, 5180 @Nullable Rect previouslyFocusedRect) { 5181 if (gainFocus) { 5182 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 5183 } else { 5184 notifyViewAccessibilityStateChangedIfNeeded( 5185 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 5186 } 5187 5188 InputMethodManager imm = InputMethodManager.peekInstance(); 5189 if (!gainFocus) { 5190 if (isPressed()) { 5191 setPressed(false); 5192 } 5193 if (imm != null && mAttachInfo != null 5194 && mAttachInfo.mHasWindowFocus) { 5195 imm.focusOut(this); 5196 } 5197 onFocusLost(); 5198 } else if (imm != null && mAttachInfo != null 5199 && mAttachInfo.mHasWindowFocus) { 5200 imm.focusIn(this); 5201 } 5202 5203 invalidate(true); 5204 ListenerInfo li = mListenerInfo; 5205 if (li != null && li.mOnFocusChangeListener != null) { 5206 li.mOnFocusChangeListener.onFocusChange(this, gainFocus); 5207 } 5208 5209 if (mAttachInfo != null) { 5210 mAttachInfo.mKeyDispatchState.reset(this); 5211 } 5212 } 5213 5214 /** 5215 * Sends an accessibility event of the given type. If accessibility is 5216 * not enabled this method has no effect. The default implementation calls 5217 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 5218 * to populate information about the event source (this View), then calls 5219 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 5220 * populate the text content of the event source including its descendants, 5221 * and last calls 5222 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 5223 * on its parent to resuest sending of the event to interested parties. 5224 * <p> 5225 * If an {@link AccessibilityDelegate} has been specified via calling 5226 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5227 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 5228 * responsible for handling this call. 5229 * </p> 5230 * 5231 * @param eventType The type of the event to send, as defined by several types from 5232 * {@link android.view.accessibility.AccessibilityEvent}, such as 5233 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or 5234 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}. 5235 * 5236 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 5237 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5238 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 5239 * @see AccessibilityDelegate 5240 */ 5241 public void sendAccessibilityEvent(int eventType) { 5242 if (mAccessibilityDelegate != null) { 5243 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 5244 } else { 5245 sendAccessibilityEventInternal(eventType); 5246 } 5247 } 5248 5249 /** 5250 * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT} 5251 * {@link AccessibilityEvent} to make an announcement which is related to some 5252 * sort of a context change for which none of the events representing UI transitions 5253 * is a good fit. For example, announcing a new page in a book. If accessibility 5254 * is not enabled this method does nothing. 5255 * 5256 * @param text The announcement text. 5257 */ 5258 public void announceForAccessibility(CharSequence text) { 5259 if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) { 5260 AccessibilityEvent event = AccessibilityEvent.obtain( 5261 AccessibilityEvent.TYPE_ANNOUNCEMENT); 5262 onInitializeAccessibilityEvent(event); 5263 event.getText().add(text); 5264 event.setContentDescription(null); 5265 mParent.requestSendAccessibilityEvent(this, event); 5266 } 5267 } 5268 5269 /** 5270 * @see #sendAccessibilityEvent(int) 5271 * 5272 * Note: Called from the default {@link AccessibilityDelegate}. 5273 */ 5274 void sendAccessibilityEventInternal(int eventType) { 5275 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 5276 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 5277 } 5278 } 5279 5280 /** 5281 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 5282 * takes as an argument an empty {@link AccessibilityEvent} and does not 5283 * perform a check whether accessibility is enabled. 5284 * <p> 5285 * If an {@link AccessibilityDelegate} has been specified via calling 5286 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5287 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 5288 * is responsible for handling this call. 5289 * </p> 5290 * 5291 * @param event The event to send. 5292 * 5293 * @see #sendAccessibilityEvent(int) 5294 */ 5295 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 5296 if (mAccessibilityDelegate != null) { 5297 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 5298 } else { 5299 sendAccessibilityEventUncheckedInternal(event); 5300 } 5301 } 5302 5303 /** 5304 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 5305 * 5306 * Note: Called from the default {@link AccessibilityDelegate}. 5307 */ 5308 void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 5309 if (!isShown()) { 5310 return; 5311 } 5312 onInitializeAccessibilityEvent(event); 5313 // Only a subset of accessibility events populates text content. 5314 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) { 5315 dispatchPopulateAccessibilityEvent(event); 5316 } 5317 // In the beginning we called #isShown(), so we know that getParent() is not null. 5318 getParent().requestSendAccessibilityEvent(this, event); 5319 } 5320 5321 /** 5322 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 5323 * to its children for adding their text content to the event. Note that the 5324 * event text is populated in a separate dispatch path since we add to the 5325 * event not only the text of the source but also the text of all its descendants. 5326 * A typical implementation will call 5327 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 5328 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 5329 * on each child. Override this method if custom population of the event text 5330 * content is required. 5331 * <p> 5332 * If an {@link AccessibilityDelegate} has been specified via calling 5333 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5334 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 5335 * is responsible for handling this call. 5336 * </p> 5337 * <p> 5338 * <em>Note:</em> Accessibility events of certain types are not dispatched for 5339 * populating the event text via this method. For details refer to {@link AccessibilityEvent}. 5340 * </p> 5341 * 5342 * @param event The event. 5343 * 5344 * @return True if the event population was completed. 5345 */ 5346 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 5347 if (mAccessibilityDelegate != null) { 5348 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 5349 } else { 5350 return dispatchPopulateAccessibilityEventInternal(event); 5351 } 5352 } 5353 5354 /** 5355 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5356 * 5357 * Note: Called from the default {@link AccessibilityDelegate}. 5358 */ 5359 boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5360 onPopulateAccessibilityEvent(event); 5361 return false; 5362 } 5363 5364 /** 5365 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 5366 * giving a chance to this View to populate the accessibility event with its 5367 * text content. While this method is free to modify event 5368 * attributes other than text content, doing so should normally be performed in 5369 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 5370 * <p> 5371 * Example: Adding formatted date string to an accessibility event in addition 5372 * to the text added by the super implementation: 5373 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5374 * super.onPopulateAccessibilityEvent(event); 5375 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 5376 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 5377 * mCurrentDate.getTimeInMillis(), flags); 5378 * event.getText().add(selectedDateUtterance); 5379 * }</pre> 5380 * <p> 5381 * If an {@link AccessibilityDelegate} has been specified via calling 5382 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5383 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 5384 * is responsible for handling this call. 5385 * </p> 5386 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5387 * information to the event, in case the default implementation has basic information to add. 5388 * </p> 5389 * 5390 * @param event The accessibility event which to populate. 5391 * 5392 * @see #sendAccessibilityEvent(int) 5393 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5394 */ 5395 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5396 if (mAccessibilityDelegate != null) { 5397 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 5398 } else { 5399 onPopulateAccessibilityEventInternal(event); 5400 } 5401 } 5402 5403 /** 5404 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 5405 * 5406 * Note: Called from the default {@link AccessibilityDelegate}. 5407 */ 5408 void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5409 } 5410 5411 /** 5412 * Initializes an {@link AccessibilityEvent} with information about 5413 * this View which is the event source. In other words, the source of 5414 * an accessibility event is the view whose state change triggered firing 5415 * the event. 5416 * <p> 5417 * Example: Setting the password property of an event in addition 5418 * to properties set by the super implementation: 5419 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5420 * super.onInitializeAccessibilityEvent(event); 5421 * event.setPassword(true); 5422 * }</pre> 5423 * <p> 5424 * If an {@link AccessibilityDelegate} has been specified via calling 5425 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5426 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 5427 * is responsible for handling this call. 5428 * </p> 5429 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5430 * information to the event, in case the default implementation has basic information to add. 5431 * </p> 5432 * @param event The event to initialize. 5433 * 5434 * @see #sendAccessibilityEvent(int) 5435 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5436 */ 5437 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5438 if (mAccessibilityDelegate != null) { 5439 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 5440 } else { 5441 onInitializeAccessibilityEventInternal(event); 5442 } 5443 } 5444 5445 /** 5446 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 5447 * 5448 * Note: Called from the default {@link AccessibilityDelegate}. 5449 */ 5450 void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 5451 event.setSource(this); 5452 event.setClassName(View.class.getName()); 5453 event.setPackageName(getContext().getPackageName()); 5454 event.setEnabled(isEnabled()); 5455 event.setContentDescription(mContentDescription); 5456 5457 switch (event.getEventType()) { 5458 case AccessibilityEvent.TYPE_VIEW_FOCUSED: { 5459 ArrayList<View> focusablesTempList = (mAttachInfo != null) 5460 ? mAttachInfo.mTempArrayList : new ArrayList<View>(); 5461 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL); 5462 event.setItemCount(focusablesTempList.size()); 5463 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 5464 if (mAttachInfo != null) { 5465 focusablesTempList.clear(); 5466 } 5467 } break; 5468 case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: { 5469 CharSequence text = getIterableTextForAccessibility(); 5470 if (text != null && text.length() > 0) { 5471 event.setFromIndex(getAccessibilitySelectionStart()); 5472 event.setToIndex(getAccessibilitySelectionEnd()); 5473 event.setItemCount(text.length()); 5474 } 5475 } break; 5476 } 5477 } 5478 5479 /** 5480 * Returns an {@link AccessibilityNodeInfo} representing this view from the 5481 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 5482 * This method is responsible for obtaining an accessibility node info from a 5483 * pool of reusable instances and calling 5484 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 5485 * initialize the former. 5486 * <p> 5487 * Note: The client is responsible for recycling the obtained instance by calling 5488 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 5489 * </p> 5490 * 5491 * @return A populated {@link AccessibilityNodeInfo}. 5492 * 5493 * @see AccessibilityNodeInfo 5494 */ 5495 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 5496 if (mAccessibilityDelegate != null) { 5497 return mAccessibilityDelegate.createAccessibilityNodeInfo(this); 5498 } else { 5499 return createAccessibilityNodeInfoInternal(); 5500 } 5501 } 5502 5503 /** 5504 * @see #createAccessibilityNodeInfo() 5505 */ 5506 AccessibilityNodeInfo createAccessibilityNodeInfoInternal() { 5507 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 5508 if (provider != null) { 5509 return provider.createAccessibilityNodeInfo(View.NO_ID); 5510 } else { 5511 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 5512 onInitializeAccessibilityNodeInfo(info); 5513 return info; 5514 } 5515 } 5516 5517 /** 5518 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 5519 * The base implementation sets: 5520 * <ul> 5521 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 5522 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 5523 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 5524 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 5525 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 5526 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 5527 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 5528 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 5529 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 5530 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 5531 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 5532 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 5533 * </ul> 5534 * <p> 5535 * Subclasses should override this method, call the super implementation, 5536 * and set additional attributes. 5537 * </p> 5538 * <p> 5539 * If an {@link AccessibilityDelegate} has been specified via calling 5540 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5541 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 5542 * is responsible for handling this call. 5543 * </p> 5544 * 5545 * @param info The instance to initialize. 5546 */ 5547 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 5548 if (mAccessibilityDelegate != null) { 5549 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 5550 } else { 5551 onInitializeAccessibilityNodeInfoInternal(info); 5552 } 5553 } 5554 5555 /** 5556 * Gets the location of this view in screen coordintates. 5557 * 5558 * @param outRect The output location 5559 * @hide 5560 */ 5561 public void getBoundsOnScreen(Rect outRect) { 5562 if (mAttachInfo == null) { 5563 return; 5564 } 5565 5566 RectF position = mAttachInfo.mTmpTransformRect; 5567 position.set(0, 0, mRight - mLeft, mBottom - mTop); 5568 5569 if (!hasIdentityMatrix()) { 5570 getMatrix().mapRect(position); 5571 } 5572 5573 position.offset(mLeft, mTop); 5574 5575 ViewParent parent = mParent; 5576 while (parent instanceof View) { 5577 View parentView = (View) parent; 5578 5579 position.offset(-parentView.mScrollX, -parentView.mScrollY); 5580 5581 if (!parentView.hasIdentityMatrix()) { 5582 parentView.getMatrix().mapRect(position); 5583 } 5584 5585 position.offset(parentView.mLeft, parentView.mTop); 5586 5587 parent = parentView.mParent; 5588 } 5589 5590 if (parent instanceof ViewRootImpl) { 5591 ViewRootImpl viewRootImpl = (ViewRootImpl) parent; 5592 position.offset(0, -viewRootImpl.mCurScrollY); 5593 } 5594 5595 position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 5596 5597 outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f), 5598 (int) (position.right + 0.5f), (int) (position.bottom + 0.5f)); 5599 } 5600 5601 /** 5602 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 5603 * 5604 * Note: Called from the default {@link AccessibilityDelegate}. 5605 */ 5606 void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 5607 Rect bounds = mAttachInfo.mTmpInvalRect; 5608 5609 getDrawingRect(bounds); 5610 info.setBoundsInParent(bounds); 5611 5612 getBoundsOnScreen(bounds); 5613 info.setBoundsInScreen(bounds); 5614 5615 ViewParent parent = getParentForAccessibility(); 5616 if (parent instanceof View) { 5617 info.setParent((View) parent); 5618 } 5619 5620 if (mID != View.NO_ID) { 5621 View rootView = getRootView(); 5622 if (rootView == null) { 5623 rootView = this; 5624 } 5625 5626 View label = rootView.findLabelForView(this, mID); 5627 if (label != null) { 5628 info.setLabeledBy(label); 5629 } 5630 5631 if ((mAttachInfo.mAccessibilityFetchFlags 5632 & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0 5633 && Resources.resourceHasPackage(mID)) { 5634 try { 5635 String viewId = getResources().getResourceName(mID); 5636 info.setViewIdResourceName(viewId); 5637 } catch (Resources.NotFoundException nfe) { 5638 /* ignore */ 5639 } 5640 } 5641 } 5642 5643 if (mLabelForId != View.NO_ID) { 5644 View rootView = getRootView(); 5645 if (rootView == null) { 5646 rootView = this; 5647 } 5648 View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId); 5649 if (labeled != null) { 5650 info.setLabelFor(labeled); 5651 } 5652 } 5653 5654 if (mAccessibilityTraversalBeforeId != View.NO_ID) { 5655 View rootView = getRootView(); 5656 if (rootView == null) { 5657 rootView = this; 5658 } 5659 View next = rootView.findViewInsideOutShouldExist(this, 5660 mAccessibilityTraversalBeforeId); 5661 if (next != null) { 5662 info.setTraversalBefore(next); 5663 } 5664 } 5665 5666 if (mAccessibilityTraversalAfterId != View.NO_ID) { 5667 View rootView = getRootView(); 5668 if (rootView == null) { 5669 rootView = this; 5670 } 5671 View next = rootView.findViewInsideOutShouldExist(this, 5672 mAccessibilityTraversalAfterId); 5673 if (next != null) { 5674 info.setTraversalAfter(next); 5675 } 5676 } 5677 5678 info.setVisibleToUser(isVisibleToUser()); 5679 5680 info.setPackageName(mContext.getPackageName()); 5681 info.setClassName(View.class.getName()); 5682 info.setContentDescription(getContentDescription()); 5683 5684 info.setEnabled(isEnabled()); 5685 info.setClickable(isClickable()); 5686 info.setFocusable(isFocusable()); 5687 info.setFocused(isFocused()); 5688 info.setAccessibilityFocused(isAccessibilityFocused()); 5689 info.setSelected(isSelected()); 5690 info.setLongClickable(isLongClickable()); 5691 info.setLiveRegion(getAccessibilityLiveRegion()); 5692 5693 // TODO: These make sense only if we are in an AdapterView but all 5694 // views can be selected. Maybe from accessibility perspective 5695 // we should report as selectable view in an AdapterView. 5696 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 5697 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 5698 5699 if (isFocusable()) { 5700 if (isFocused()) { 5701 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 5702 } else { 5703 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 5704 } 5705 } 5706 5707 if (!isAccessibilityFocused()) { 5708 info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); 5709 } else { 5710 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); 5711 } 5712 5713 if (isClickable() && isEnabled()) { 5714 info.addAction(AccessibilityNodeInfo.ACTION_CLICK); 5715 } 5716 5717 if (isLongClickable() && isEnabled()) { 5718 info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); 5719 } 5720 5721 CharSequence text = getIterableTextForAccessibility(); 5722 if (text != null && text.length() > 0) { 5723 info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd()); 5724 5725 info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION); 5726 info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); 5727 info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); 5728 info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER 5729 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD 5730 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH); 5731 } 5732 } 5733 5734 private View findLabelForView(View view, int labeledId) { 5735 if (mMatchLabelForPredicate == null) { 5736 mMatchLabelForPredicate = new MatchLabelForPredicate(); 5737 } 5738 mMatchLabelForPredicate.mLabeledId = labeledId; 5739 return findViewByPredicateInsideOut(view, mMatchLabelForPredicate); 5740 } 5741 5742 /** 5743 * Computes whether this view is visible to the user. Such a view is 5744 * attached, visible, all its predecessors are visible, it is not clipped 5745 * entirely by its predecessors, and has an alpha greater than zero. 5746 * 5747 * @return Whether the view is visible on the screen. 5748 * 5749 * @hide 5750 */ 5751 protected boolean isVisibleToUser() { 5752 return isVisibleToUser(null); 5753 } 5754 5755 /** 5756 * Computes whether the given portion of this view is visible to the user. 5757 * Such a view is attached, visible, all its predecessors are visible, 5758 * has an alpha greater than zero, and the specified portion is not 5759 * clipped entirely by its predecessors. 5760 * 5761 * @param boundInView the portion of the view to test; coordinates should be relative; may be 5762 * <code>null</code>, and the entire view will be tested in this case. 5763 * When <code>true</code> is returned by the function, the actual visible 5764 * region will be stored in this parameter; that is, if boundInView is fully 5765 * contained within the view, no modification will be made, otherwise regions 5766 * outside of the visible area of the view will be clipped. 5767 * 5768 * @return Whether the specified portion of the view is visible on the screen. 5769 * 5770 * @hide 5771 */ 5772 protected boolean isVisibleToUser(Rect boundInView) { 5773 if (mAttachInfo != null) { 5774 // Attached to invisible window means this view is not visible. 5775 if (mAttachInfo.mWindowVisibility != View.VISIBLE) { 5776 return false; 5777 } 5778 // An invisible predecessor or one with alpha zero means 5779 // that this view is not visible to the user. 5780 Object current = this; 5781 while (current instanceof View) { 5782 View view = (View) current; 5783 // We have attach info so this view is attached and there is no 5784 // need to check whether we reach to ViewRootImpl on the way up. 5785 if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 || 5786 view.getVisibility() != VISIBLE) { 5787 return false; 5788 } 5789 current = view.mParent; 5790 } 5791 // Check if the view is entirely covered by its predecessors. 5792 Rect visibleRect = mAttachInfo.mTmpInvalRect; 5793 Point offset = mAttachInfo.mPoint; 5794 if (!getGlobalVisibleRect(visibleRect, offset)) { 5795 return false; 5796 } 5797 // Check if the visible portion intersects the rectangle of interest. 5798 if (boundInView != null) { 5799 visibleRect.offset(-offset.x, -offset.y); 5800 return boundInView.intersect(visibleRect); 5801 } 5802 return true; 5803 } 5804 return false; 5805 } 5806 5807 /** 5808 * Computes a point on which a sequence of a down/up event can be sent to 5809 * trigger clicking this view. This method is for the exclusive use by the 5810 * accessibility layer to determine where to send a click event in explore 5811 * by touch mode. 5812 * 5813 * @param interactiveRegion The interactive portion of this window. 5814 * @param outPoint The point to populate. 5815 * @return True of such a point exists. 5816 */ 5817 boolean computeClickPointInScreenForAccessibility(Region interactiveRegion, 5818 Point outPoint) { 5819 // Since the interactive portion of the view is a region but as a view 5820 // may have a transformation matrix which cannot be applied to a 5821 // region we compute the view bounds rectangle and all interactive 5822 // predecessor's and sibling's (siblings of predecessors included) 5823 // rectangles that intersect the view bounds. At the 5824 // end if the view was partially covered by another interactive 5825 // view we compute the view's interactive region and pick a point 5826 // on its boundary path as regions do not offer APIs to get inner 5827 // points. Note that the the code is optimized to fail early and 5828 // avoid unnecessary allocations plus computations. 5829 5830 // The current approach has edge cases that may produce false 5831 // positives or false negatives. For example, a portion of the 5832 // view may be covered by an interactive descendant of a 5833 // predecessor, which we do not compute. Also a view may be handling 5834 // raw touch events instead registering click listeners, which 5835 // we cannot compute. Despite these limitations this approach will 5836 // work most of the time and it is a huge improvement over just 5837 // blindly sending the down and up events in the center of the 5838 // view. 5839 5840 // Cannot click on an unattached view. 5841 if (mAttachInfo == null) { 5842 return false; 5843 } 5844 5845 // Attached to an invisible window means this view is not visible. 5846 if (mAttachInfo.mWindowVisibility != View.VISIBLE) { 5847 return false; 5848 } 5849 5850 RectF bounds = mAttachInfo.mTmpTransformRect; 5851 bounds.set(0, 0, getWidth(), getHeight()); 5852 List<RectF> intersections = mAttachInfo.mTmpRectList; 5853 intersections.clear(); 5854 5855 if (mParent instanceof ViewGroup) { 5856 ViewGroup parentGroup = (ViewGroup) mParent; 5857 if (!parentGroup.translateBoundsAndIntersectionsInWindowCoordinates( 5858 this, bounds, intersections)) { 5859 intersections.clear(); 5860 return false; 5861 } 5862 } 5863 5864 // Take into account the window location. 5865 final int dx = mAttachInfo.mWindowLeft; 5866 final int dy = mAttachInfo.mWindowTop; 5867 bounds.offset(dx, dy); 5868 offsetRects(intersections, dx, dy); 5869 5870 if (intersections.isEmpty() && interactiveRegion == null) { 5871 outPoint.set((int) bounds.centerX(), (int) bounds.centerY()); 5872 } else { 5873 // This view is partially covered by other views, then compute 5874 // the not covered region and pick a point on its boundary. 5875 Region region = new Region(); 5876 region.set((int) bounds.left, (int) bounds.top, 5877 (int) bounds.right, (int) bounds.bottom); 5878 5879 final int intersectionCount = intersections.size(); 5880 for (int i = intersectionCount - 1; i >= 0; i--) { 5881 RectF intersection = intersections.remove(i); 5882 region.op((int) intersection.left, (int) intersection.top, 5883 (int) intersection.right, (int) intersection.bottom, 5884 Region.Op.DIFFERENCE); 5885 } 5886 5887 // If the view is completely covered, done. 5888 if (region.isEmpty()) { 5889 return false; 5890 } 5891 5892 // Take into account the interactive portion of the window 5893 // as the rest is covered by other windows. If no such a region 5894 // then the whole window is interactive. 5895 if (interactiveRegion != null) { 5896 region.op(interactiveRegion, Region.Op.INTERSECT); 5897 } 5898 5899 // Take into account the window bounds. 5900 final View root = getRootView(); 5901 if (root != null) { 5902 region.op(dx, dy, root.getWidth() + dx, root.getHeight() + dy, Region.Op.INTERSECT); 5903 } 5904 5905 // If the view is completely covered, done. 5906 if (region.isEmpty()) { 5907 return false; 5908 } 5909 5910 // Try a shortcut here. 5911 if (region.isRect()) { 5912 Rect regionBounds = mAttachInfo.mTmpInvalRect; 5913 region.getBounds(regionBounds); 5914 outPoint.set(regionBounds.centerX(), regionBounds.centerY()); 5915 return true; 5916 } 5917 5918 // Get the a point on the region boundary path. 5919 Path path = region.getBoundaryPath(); 5920 PathMeasure pathMeasure = new PathMeasure(path, false); 5921 final float[] coordinates = mAttachInfo.mTmpTransformLocation; 5922 5923 // Without loss of generality pick a point. 5924 final float point = pathMeasure.getLength() * 0.01f; 5925 if (!pathMeasure.getPosTan(point, coordinates, null)) { 5926 return false; 5927 } 5928 5929 outPoint.set(Math.round(coordinates[0]), Math.round(coordinates[1])); 5930 } 5931 5932 return true; 5933 } 5934 5935 /** 5936 * Adds the clickable rectangles withing the bounds of this view. They 5937 * may overlap. This method is intended for use only by the accessibility 5938 * layer. 5939 * 5940 * @param outRects List to which to add clickable areas. 5941 * 5942 * @hide 5943 */ 5944 public void addClickableRectsForAccessibility(List<RectF> outRects) { 5945 if (isClickable() || isLongClickable()) { 5946 RectF bounds = new RectF(); 5947 bounds.set(0, 0, getWidth(), getHeight()); 5948 outRects.add(bounds); 5949 } 5950 } 5951 5952 static void offsetRects(List<RectF> rects, float offsetX, float offsetY) { 5953 final int rectCount = rects.size(); 5954 for (int i = 0; i < rectCount; i++) { 5955 RectF intersection = rects.get(i); 5956 intersection.offset(offsetX, offsetY); 5957 } 5958 } 5959 5960 /** 5961 * Returns the delegate for implementing accessibility support via 5962 * composition. For more details see {@link AccessibilityDelegate}. 5963 * 5964 * @return The delegate, or null if none set. 5965 * 5966 * @hide 5967 */ 5968 public AccessibilityDelegate getAccessibilityDelegate() { 5969 return mAccessibilityDelegate; 5970 } 5971 5972 /** 5973 * Sets a delegate for implementing accessibility support via composition as 5974 * opposed to inheritance. The delegate's primary use is for implementing 5975 * backwards compatible widgets. For more details see {@link AccessibilityDelegate}. 5976 * 5977 * @param delegate The delegate instance. 5978 * 5979 * @see AccessibilityDelegate 5980 */ 5981 public void setAccessibilityDelegate(AccessibilityDelegate delegate) { 5982 mAccessibilityDelegate = delegate; 5983 } 5984 5985 /** 5986 * Gets the provider for managing a virtual view hierarchy rooted at this View 5987 * and reported to {@link android.accessibilityservice.AccessibilityService}s 5988 * that explore the window content. 5989 * <p> 5990 * If this method returns an instance, this instance is responsible for managing 5991 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this 5992 * View including the one representing the View itself. Similarly the returned 5993 * instance is responsible for performing accessibility actions on any virtual 5994 * view or the root view itself. 5995 * </p> 5996 * <p> 5997 * If an {@link AccessibilityDelegate} has been specified via calling 5998 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5999 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)} 6000 * is responsible for handling this call. 6001 * </p> 6002 * 6003 * @return The provider. 6004 * 6005 * @see AccessibilityNodeProvider 6006 */ 6007 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 6008 if (mAccessibilityDelegate != null) { 6009 return mAccessibilityDelegate.getAccessibilityNodeProvider(this); 6010 } else { 6011 return null; 6012 } 6013 } 6014 6015 /** 6016 * Gets the unique identifier of this view on the screen for accessibility purposes. 6017 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 6018 * 6019 * @return The view accessibility id. 6020 * 6021 * @hide 6022 */ 6023 public int getAccessibilityViewId() { 6024 if (mAccessibilityViewId == NO_ID) { 6025 mAccessibilityViewId = sNextAccessibilityViewId++; 6026 } 6027 return mAccessibilityViewId; 6028 } 6029 6030 /** 6031 * Gets the unique identifier of the window in which this View reseides. 6032 * 6033 * @return The window accessibility id. 6034 * 6035 * @hide 6036 */ 6037 public int getAccessibilityWindowId() { 6038 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId 6039 : AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 6040 } 6041 6042 /** 6043 * Gets the {@link View} description. It briefly describes the view and is 6044 * primarily used for accessibility support. Set this property to enable 6045 * better accessibility support for your application. This is especially 6046 * true for views that do not have textual representation (For example, 6047 * ImageButton). 6048 * 6049 * @return The content description. 6050 * 6051 * @attr ref android.R.styleable#View_contentDescription 6052 */ 6053 @ViewDebug.ExportedProperty(category = "accessibility") 6054 public CharSequence getContentDescription() { 6055 return mContentDescription; 6056 } 6057 6058 /** 6059 * Sets the {@link View} description. It briefly describes the view and is 6060 * primarily used for accessibility support. Set this property to enable 6061 * better accessibility support for your application. This is especially 6062 * true for views that do not have textual representation (For example, 6063 * ImageButton). 6064 * 6065 * @param contentDescription The content description. 6066 * 6067 * @attr ref android.R.styleable#View_contentDescription 6068 */ 6069 @RemotableViewMethod 6070 public void setContentDescription(CharSequence contentDescription) { 6071 if (mContentDescription == null) { 6072 if (contentDescription == null) { 6073 return; 6074 } 6075 } else if (mContentDescription.equals(contentDescription)) { 6076 return; 6077 } 6078 mContentDescription = contentDescription; 6079 final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0; 6080 if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 6081 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); 6082 notifySubtreeAccessibilityStateChangedIfNeeded(); 6083 } else { 6084 notifyViewAccessibilityStateChangedIfNeeded( 6085 AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION); 6086 } 6087 } 6088 6089 /** 6090 * Sets the id of a view before which this one is visited in accessibility traversal. 6091 * A screen-reader must visit the content of this view before the content of the one 6092 * it precedes. For example, if view B is set to be before view A, then a screen-reader 6093 * will traverse the entire content of B before traversing the entire content of A, 6094 * regardles of what traversal strategy it is using. 6095 * <p> 6096 * Views that do not have specified before/after relationships are traversed in order 6097 * determined by the screen-reader. 6098 * </p> 6099 * <p> 6100 * Setting that this view is before a view that is not important for accessibility 6101 * or if this view is not important for accessibility will have no effect as the 6102 * screen-reader is not aware of unimportant views. 6103 * </p> 6104 * 6105 * @param beforeId The id of a view this one precedes in accessibility traversal. 6106 * 6107 * @attr ref android.R.styleable#View_accessibilityTraversalBefore 6108 * 6109 * @see #setImportantForAccessibility(int) 6110 */ 6111 @RemotableViewMethod 6112 public void setAccessibilityTraversalBefore(int beforeId) { 6113 if (mAccessibilityTraversalBeforeId == beforeId) { 6114 return; 6115 } 6116 mAccessibilityTraversalBeforeId = beforeId; 6117 notifyViewAccessibilityStateChangedIfNeeded( 6118 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 6119 } 6120 6121 /** 6122 * Gets the id of a view before which this one is visited in accessibility traversal. 6123 * 6124 * @return The id of a view this one precedes in accessibility traversal if 6125 * specified, otherwise {@link #NO_ID}. 6126 * 6127 * @see #setAccessibilityTraversalBefore(int) 6128 */ 6129 public int getAccessibilityTraversalBefore() { 6130 return mAccessibilityTraversalBeforeId; 6131 } 6132 6133 /** 6134 * Sets the id of a view after which this one is visited in accessibility traversal. 6135 * A screen-reader must visit the content of the other view before the content of this 6136 * one. For example, if view B is set to be after view A, then a screen-reader 6137 * will traverse the entire content of A before traversing the entire content of B, 6138 * regardles of what traversal strategy it is using. 6139 * <p> 6140 * Views that do not have specified before/after relationships are traversed in order 6141 * determined by the screen-reader. 6142 * </p> 6143 * <p> 6144 * Setting that this view is after a view that is not important for accessibility 6145 * or if this view is not important for accessibility will have no effect as the 6146 * screen-reader is not aware of unimportant views. 6147 * </p> 6148 * 6149 * @param afterId The id of a view this one succedees in accessibility traversal. 6150 * 6151 * @attr ref android.R.styleable#View_accessibilityTraversalAfter 6152 * 6153 * @see #setImportantForAccessibility(int) 6154 */ 6155 @RemotableViewMethod 6156 public void setAccessibilityTraversalAfter(int afterId) { 6157 if (mAccessibilityTraversalAfterId == afterId) { 6158 return; 6159 } 6160 mAccessibilityTraversalAfterId = afterId; 6161 notifyViewAccessibilityStateChangedIfNeeded( 6162 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 6163 } 6164 6165 /** 6166 * Gets the id of a view after which this one is visited in accessibility traversal. 6167 * 6168 * @return The id of a view this one succeedes in accessibility traversal if 6169 * specified, otherwise {@link #NO_ID}. 6170 * 6171 * @see #setAccessibilityTraversalAfter(int) 6172 */ 6173 public int getAccessibilityTraversalAfter() { 6174 return mAccessibilityTraversalAfterId; 6175 } 6176 6177 /** 6178 * Gets the id of a view for which this view serves as a label for 6179 * accessibility purposes. 6180 * 6181 * @return The labeled view id. 6182 */ 6183 @ViewDebug.ExportedProperty(category = "accessibility") 6184 public int getLabelFor() { 6185 return mLabelForId; 6186 } 6187 6188 /** 6189 * Sets the id of a view for which this view serves as a label for 6190 * accessibility purposes. 6191 * 6192 * @param id The labeled view id. 6193 */ 6194 @RemotableViewMethod 6195 public void setLabelFor(int id) { 6196 if (mLabelForId == id) { 6197 return; 6198 } 6199 mLabelForId = id; 6200 if (mLabelForId != View.NO_ID 6201 && mID == View.NO_ID) { 6202 mID = generateViewId(); 6203 } 6204 notifyViewAccessibilityStateChangedIfNeeded( 6205 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 6206 } 6207 6208 /** 6209 * Invoked whenever this view loses focus, either by losing window focus or by losing 6210 * focus within its window. This method can be used to clear any state tied to the 6211 * focus. For instance, if a button is held pressed with the trackball and the window 6212 * loses focus, this method can be used to cancel the press. 6213 * 6214 * Subclasses of View overriding this method should always call super.onFocusLost(). 6215 * 6216 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 6217 * @see #onWindowFocusChanged(boolean) 6218 * 6219 * @hide pending API council approval 6220 */ 6221 protected void onFocusLost() { 6222 resetPressedState(); 6223 } 6224 6225 private void resetPressedState() { 6226 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 6227 return; 6228 } 6229 6230 if (isPressed()) { 6231 setPressed(false); 6232 6233 if (!mHasPerformedLongPress) { 6234 removeLongPressCallback(); 6235 } 6236 } 6237 } 6238 6239 /** 6240 * Returns true if this view has focus 6241 * 6242 * @return True if this view has focus, false otherwise. 6243 */ 6244 @ViewDebug.ExportedProperty(category = "focus") 6245 public boolean isFocused() { 6246 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 6247 } 6248 6249 /** 6250 * Find the view in the hierarchy rooted at this view that currently has 6251 * focus. 6252 * 6253 * @return The view that currently has focus, or null if no focused view can 6254 * be found. 6255 */ 6256 public View findFocus() { 6257 return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null; 6258 } 6259 6260 /** 6261 * Indicates whether this view is one of the set of scrollable containers in 6262 * its window. 6263 * 6264 * @return whether this view is one of the set of scrollable containers in 6265 * its window 6266 * 6267 * @attr ref android.R.styleable#View_isScrollContainer 6268 */ 6269 public boolean isScrollContainer() { 6270 return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0; 6271 } 6272 6273 /** 6274 * Change whether this view is one of the set of scrollable containers in 6275 * its window. This will be used to determine whether the window can 6276 * resize or must pan when a soft input area is open -- scrollable 6277 * containers allow the window to use resize mode since the container 6278 * will appropriately shrink. 6279 * 6280 * @attr ref android.R.styleable#View_isScrollContainer 6281 */ 6282 public void setScrollContainer(boolean isScrollContainer) { 6283 if (isScrollContainer) { 6284 if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) { 6285 mAttachInfo.mScrollContainers.add(this); 6286 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 6287 } 6288 mPrivateFlags |= PFLAG_SCROLL_CONTAINER; 6289 } else { 6290 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 6291 mAttachInfo.mScrollContainers.remove(this); 6292 } 6293 mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED); 6294 } 6295 } 6296 6297 /** 6298 * Returns the quality of the drawing cache. 6299 * 6300 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 6301 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 6302 * 6303 * @see #setDrawingCacheQuality(int) 6304 * @see #setDrawingCacheEnabled(boolean) 6305 * @see #isDrawingCacheEnabled() 6306 * 6307 * @attr ref android.R.styleable#View_drawingCacheQuality 6308 */ 6309 @DrawingCacheQuality 6310 public int getDrawingCacheQuality() { 6311 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 6312 } 6313 6314 /** 6315 * Set the drawing cache quality of this view. This value is used only when the 6316 * drawing cache is enabled 6317 * 6318 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 6319 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 6320 * 6321 * @see #getDrawingCacheQuality() 6322 * @see #setDrawingCacheEnabled(boolean) 6323 * @see #isDrawingCacheEnabled() 6324 * 6325 * @attr ref android.R.styleable#View_drawingCacheQuality 6326 */ 6327 public void setDrawingCacheQuality(@DrawingCacheQuality int quality) { 6328 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 6329 } 6330 6331 /** 6332 * Returns whether the screen should remain on, corresponding to the current 6333 * value of {@link #KEEP_SCREEN_ON}. 6334 * 6335 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 6336 * 6337 * @see #setKeepScreenOn(boolean) 6338 * 6339 * @attr ref android.R.styleable#View_keepScreenOn 6340 */ 6341 public boolean getKeepScreenOn() { 6342 return (mViewFlags & KEEP_SCREEN_ON) != 0; 6343 } 6344 6345 /** 6346 * Controls whether the screen should remain on, modifying the 6347 * value of {@link #KEEP_SCREEN_ON}. 6348 * 6349 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 6350 * 6351 * @see #getKeepScreenOn() 6352 * 6353 * @attr ref android.R.styleable#View_keepScreenOn 6354 */ 6355 public void setKeepScreenOn(boolean keepScreenOn) { 6356 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 6357 } 6358 6359 /** 6360 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 6361 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6362 * 6363 * @attr ref android.R.styleable#View_nextFocusLeft 6364 */ 6365 public int getNextFocusLeftId() { 6366 return mNextFocusLeftId; 6367 } 6368 6369 /** 6370 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 6371 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 6372 * decide automatically. 6373 * 6374 * @attr ref android.R.styleable#View_nextFocusLeft 6375 */ 6376 public void setNextFocusLeftId(int nextFocusLeftId) { 6377 mNextFocusLeftId = nextFocusLeftId; 6378 } 6379 6380 /** 6381 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 6382 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6383 * 6384 * @attr ref android.R.styleable#View_nextFocusRight 6385 */ 6386 public int getNextFocusRightId() { 6387 return mNextFocusRightId; 6388 } 6389 6390 /** 6391 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 6392 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 6393 * decide automatically. 6394 * 6395 * @attr ref android.R.styleable#View_nextFocusRight 6396 */ 6397 public void setNextFocusRightId(int nextFocusRightId) { 6398 mNextFocusRightId = nextFocusRightId; 6399 } 6400 6401 /** 6402 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 6403 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6404 * 6405 * @attr ref android.R.styleable#View_nextFocusUp 6406 */ 6407 public int getNextFocusUpId() { 6408 return mNextFocusUpId; 6409 } 6410 6411 /** 6412 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 6413 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 6414 * decide automatically. 6415 * 6416 * @attr ref android.R.styleable#View_nextFocusUp 6417 */ 6418 public void setNextFocusUpId(int nextFocusUpId) { 6419 mNextFocusUpId = nextFocusUpId; 6420 } 6421 6422 /** 6423 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 6424 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6425 * 6426 * @attr ref android.R.styleable#View_nextFocusDown 6427 */ 6428 public int getNextFocusDownId() { 6429 return mNextFocusDownId; 6430 } 6431 6432 /** 6433 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 6434 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 6435 * decide automatically. 6436 * 6437 * @attr ref android.R.styleable#View_nextFocusDown 6438 */ 6439 public void setNextFocusDownId(int nextFocusDownId) { 6440 mNextFocusDownId = nextFocusDownId; 6441 } 6442 6443 /** 6444 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 6445 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6446 * 6447 * @attr ref android.R.styleable#View_nextFocusForward 6448 */ 6449 public int getNextFocusForwardId() { 6450 return mNextFocusForwardId; 6451 } 6452 6453 /** 6454 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 6455 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 6456 * decide automatically. 6457 * 6458 * @attr ref android.R.styleable#View_nextFocusForward 6459 */ 6460 public void setNextFocusForwardId(int nextFocusForwardId) { 6461 mNextFocusForwardId = nextFocusForwardId; 6462 } 6463 6464 /** 6465 * Returns the visibility of this view and all of its ancestors 6466 * 6467 * @return True if this view and all of its ancestors are {@link #VISIBLE} 6468 */ 6469 public boolean isShown() { 6470 View current = this; 6471 //noinspection ConstantConditions 6472 do { 6473 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 6474 return false; 6475 } 6476 ViewParent parent = current.mParent; 6477 if (parent == null) { 6478 return false; // We are not attached to the view root 6479 } 6480 if (!(parent instanceof View)) { 6481 return true; 6482 } 6483 current = (View) parent; 6484 } while (current != null); 6485 6486 return false; 6487 } 6488 6489 /** 6490 * Called by the view hierarchy when the content insets for a window have 6491 * changed, to allow it to adjust its content to fit within those windows. 6492 * The content insets tell you the space that the status bar, input method, 6493 * and other system windows infringe on the application's window. 6494 * 6495 * <p>You do not normally need to deal with this function, since the default 6496 * window decoration given to applications takes care of applying it to the 6497 * content of the window. If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 6498 * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case, 6499 * and your content can be placed under those system elements. You can then 6500 * use this method within your view hierarchy if you have parts of your UI 6501 * which you would like to ensure are not being covered. 6502 * 6503 * <p>The default implementation of this method simply applies the content 6504 * insets to the view's padding, consuming that content (modifying the 6505 * insets to be 0), and returning true. This behavior is off by default, but can 6506 * be enabled through {@link #setFitsSystemWindows(boolean)}. 6507 * 6508 * <p>This function's traversal down the hierarchy is depth-first. The same content 6509 * insets object is propagated down the hierarchy, so any changes made to it will 6510 * be seen by all following views (including potentially ones above in 6511 * the hierarchy since this is a depth-first traversal). The first view 6512 * that returns true will abort the entire traversal. 6513 * 6514 * <p>The default implementation works well for a situation where it is 6515 * used with a container that covers the entire window, allowing it to 6516 * apply the appropriate insets to its content on all edges. If you need 6517 * a more complicated layout (such as two different views fitting system 6518 * windows, one on the top of the window, and one on the bottom), 6519 * you can override the method and handle the insets however you would like. 6520 * Note that the insets provided by the framework are always relative to the 6521 * far edges of the window, not accounting for the location of the called view 6522 * within that window. (In fact when this method is called you do not yet know 6523 * where the layout will place the view, as it is done before layout happens.) 6524 * 6525 * <p>Note: unlike many View methods, there is no dispatch phase to this 6526 * call. If you are overriding it in a ViewGroup and want to allow the 6527 * call to continue to your children, you must be sure to call the super 6528 * implementation. 6529 * 6530 * <p>Here is a sample layout that makes use of fitting system windows 6531 * to have controls for a video view placed inside of the window decorations 6532 * that it hides and shows. This can be used with code like the second 6533 * sample (video player) shown in {@link #setSystemUiVisibility(int)}. 6534 * 6535 * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete} 6536 * 6537 * @param insets Current content insets of the window. Prior to 6538 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify 6539 * the insets or else you and Android will be unhappy. 6540 * 6541 * @return {@code true} if this view applied the insets and it should not 6542 * continue propagating further down the hierarchy, {@code false} otherwise. 6543 * @see #getFitsSystemWindows() 6544 * @see #setFitsSystemWindows(boolean) 6545 * @see #setSystemUiVisibility(int) 6546 * 6547 * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply 6548 * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use 6549 * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)} 6550 * to implement handling their own insets. 6551 */ 6552 protected boolean fitSystemWindows(Rect insets) { 6553 if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) { 6554 if (insets == null) { 6555 // Null insets by definition have already been consumed. 6556 // This call cannot apply insets since there are none to apply, 6557 // so return false. 6558 return false; 6559 } 6560 // If we're not in the process of dispatching the newer apply insets call, 6561 // that means we're not in the compatibility path. Dispatch into the newer 6562 // apply insets path and take things from there. 6563 try { 6564 mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS; 6565 return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed(); 6566 } finally { 6567 mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS; 6568 } 6569 } else { 6570 // We're being called from the newer apply insets path. 6571 // Perform the standard fallback behavior. 6572 return fitSystemWindowsInt(insets); 6573 } 6574 } 6575 6576 private boolean fitSystemWindowsInt(Rect insets) { 6577 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 6578 mUserPaddingStart = UNDEFINED_PADDING; 6579 mUserPaddingEnd = UNDEFINED_PADDING; 6580 Rect localInsets = sThreadLocal.get(); 6581 if (localInsets == null) { 6582 localInsets = new Rect(); 6583 sThreadLocal.set(localInsets); 6584 } 6585 boolean res = computeFitSystemWindows(insets, localInsets); 6586 mUserPaddingLeftInitial = localInsets.left; 6587 mUserPaddingRightInitial = localInsets.right; 6588 internalSetPadding(localInsets.left, localInsets.top, 6589 localInsets.right, localInsets.bottom); 6590 return res; 6591 } 6592 return false; 6593 } 6594 6595 /** 6596 * Called when the view should apply {@link WindowInsets} according to its internal policy. 6597 * 6598 * <p>This method should be overridden by views that wish to apply a policy different from or 6599 * in addition to the default behavior. Clients that wish to force a view subtree 6600 * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p> 6601 * 6602 * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set 6603 * it will be called during dispatch instead of this method. The listener may optionally 6604 * call this method from its own implementation if it wishes to apply the view's default 6605 * insets policy in addition to its own.</p> 6606 * 6607 * <p>Implementations of this method should either return the insets parameter unchanged 6608 * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed 6609 * that this view applied itself. This allows new inset types added in future platform 6610 * versions to pass through existing implementations unchanged without being erroneously 6611 * consumed.</p> 6612 * 6613 * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows} 6614 * property is set then the view will consume the system window insets and apply them 6615 * as padding for the view.</p> 6616 * 6617 * @param insets Insets to apply 6618 * @return The supplied insets with any applied insets consumed 6619 */ 6620 public WindowInsets onApplyWindowInsets(WindowInsets insets) { 6621 if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) { 6622 // We weren't called from within a direct call to fitSystemWindows, 6623 // call into it as a fallback in case we're in a class that overrides it 6624 // and has logic to perform. 6625 if (fitSystemWindows(insets.getSystemWindowInsets())) { 6626 return insets.consumeSystemWindowInsets(); 6627 } 6628 } else { 6629 // We were called from within a direct call to fitSystemWindows. 6630 if (fitSystemWindowsInt(insets.getSystemWindowInsets())) { 6631 return insets.consumeSystemWindowInsets(); 6632 } 6633 } 6634 return insets; 6635 } 6636 6637 /** 6638 * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying 6639 * window insets to this view. The listener's 6640 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 6641 * method will be called instead of the view's 6642 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 6643 * 6644 * @param listener Listener to set 6645 * 6646 * @see #onApplyWindowInsets(WindowInsets) 6647 */ 6648 public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) { 6649 getListenerInfo().mOnApplyWindowInsetsListener = listener; 6650 } 6651 6652 /** 6653 * Request to apply the given window insets to this view or another view in its subtree. 6654 * 6655 * <p>This method should be called by clients wishing to apply insets corresponding to areas 6656 * obscured by window decorations or overlays. This can include the status and navigation bars, 6657 * action bars, input methods and more. New inset categories may be added in the future. 6658 * The method returns the insets provided minus any that were applied by this view or its 6659 * children.</p> 6660 * 6661 * <p>Clients wishing to provide custom behavior should override the 6662 * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a 6663 * {@link OnApplyWindowInsetsListener} via the 6664 * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener} 6665 * method.</p> 6666 * 6667 * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method. 6668 * </p> 6669 * 6670 * @param insets Insets to apply 6671 * @return The provided insets minus the insets that were consumed 6672 */ 6673 public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) { 6674 try { 6675 mPrivateFlags3 |= PFLAG3_APPLYING_INSETS; 6676 if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) { 6677 return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets); 6678 } else { 6679 return onApplyWindowInsets(insets); 6680 } 6681 } finally { 6682 mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS; 6683 } 6684 } 6685 6686 /** 6687 * @hide Compute the insets that should be consumed by this view and the ones 6688 * that should propagate to those under it. 6689 */ 6690 protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) { 6691 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 6692 || mAttachInfo == null 6693 || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0 6694 && !mAttachInfo.mOverscanRequested)) { 6695 outLocalInsets.set(inoutInsets); 6696 inoutInsets.set(0, 0, 0, 0); 6697 return true; 6698 } else { 6699 // The application wants to take care of fitting system window for 6700 // the content... however we still need to take care of any overscan here. 6701 final Rect overscan = mAttachInfo.mOverscanInsets; 6702 outLocalInsets.set(overscan); 6703 inoutInsets.left -= overscan.left; 6704 inoutInsets.top -= overscan.top; 6705 inoutInsets.right -= overscan.right; 6706 inoutInsets.bottom -= overscan.bottom; 6707 return false; 6708 } 6709 } 6710 6711 /** 6712 * Compute insets that should be consumed by this view and the ones that should propagate 6713 * to those under it. 6714 * 6715 * @param in Insets currently being processed by this View, likely received as a parameter 6716 * to {@link #onApplyWindowInsets(WindowInsets)}. 6717 * @param outLocalInsets A Rect that will receive the insets that should be consumed 6718 * by this view 6719 * @return Insets that should be passed along to views under this one 6720 */ 6721 public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) { 6722 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 6723 || mAttachInfo == null 6724 || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) { 6725 outLocalInsets.set(in.getSystemWindowInsets()); 6726 return in.consumeSystemWindowInsets(); 6727 } else { 6728 outLocalInsets.set(0, 0, 0, 0); 6729 return in; 6730 } 6731 } 6732 6733 /** 6734 * Sets whether or not this view should account for system screen decorations 6735 * such as the status bar and inset its content; that is, controlling whether 6736 * the default implementation of {@link #fitSystemWindows(Rect)} will be 6737 * executed. See that method for more details. 6738 * 6739 * <p>Note that if you are providing your own implementation of 6740 * {@link #fitSystemWindows(Rect)}, then there is no need to set this 6741 * flag to true -- your implementation will be overriding the default 6742 * implementation that checks this flag. 6743 * 6744 * @param fitSystemWindows If true, then the default implementation of 6745 * {@link #fitSystemWindows(Rect)} will be executed. 6746 * 6747 * @attr ref android.R.styleable#View_fitsSystemWindows 6748 * @see #getFitsSystemWindows() 6749 * @see #fitSystemWindows(Rect) 6750 * @see #setSystemUiVisibility(int) 6751 */ 6752 public void setFitsSystemWindows(boolean fitSystemWindows) { 6753 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 6754 } 6755 6756 /** 6757 * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method 6758 * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)} 6759 * will be executed. 6760 * 6761 * @return {@code true} if the default implementation of 6762 * {@link #fitSystemWindows(Rect)} will be executed. 6763 * 6764 * @attr ref android.R.styleable#View_fitsSystemWindows 6765 * @see #setFitsSystemWindows(boolean) 6766 * @see #fitSystemWindows(Rect) 6767 * @see #setSystemUiVisibility(int) 6768 */ 6769 @ViewDebug.ExportedProperty 6770 public boolean getFitsSystemWindows() { 6771 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 6772 } 6773 6774 /** @hide */ 6775 public boolean fitsSystemWindows() { 6776 return getFitsSystemWindows(); 6777 } 6778 6779 /** 6780 * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed. 6781 * @deprecated Use {@link #requestApplyInsets()} for newer platform versions. 6782 */ 6783 public void requestFitSystemWindows() { 6784 if (mParent != null) { 6785 mParent.requestFitSystemWindows(); 6786 } 6787 } 6788 6789 /** 6790 * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed. 6791 */ 6792 public void requestApplyInsets() { 6793 requestFitSystemWindows(); 6794 } 6795 6796 /** 6797 * For use by PhoneWindow to make its own system window fitting optional. 6798 * @hide 6799 */ 6800 public void makeOptionalFitsSystemWindows() { 6801 setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS); 6802 } 6803 6804 /** 6805 * Returns the visibility status for this view. 6806 * 6807 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 6808 * @attr ref android.R.styleable#View_visibility 6809 */ 6810 @ViewDebug.ExportedProperty(mapping = { 6811 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 6812 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 6813 @ViewDebug.IntToString(from = GONE, to = "GONE") 6814 }) 6815 @Visibility 6816 public int getVisibility() { 6817 return mViewFlags & VISIBILITY_MASK; 6818 } 6819 6820 /** 6821 * Set the enabled state of this view. 6822 * 6823 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 6824 * @attr ref android.R.styleable#View_visibility 6825 */ 6826 @RemotableViewMethod 6827 public void setVisibility(@Visibility int visibility) { 6828 setFlags(visibility, VISIBILITY_MASK); 6829 if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false); 6830 } 6831 6832 /** 6833 * Returns the enabled status for this view. The interpretation of the 6834 * enabled state varies by subclass. 6835 * 6836 * @return True if this view is enabled, false otherwise. 6837 */ 6838 @ViewDebug.ExportedProperty 6839 public boolean isEnabled() { 6840 return (mViewFlags & ENABLED_MASK) == ENABLED; 6841 } 6842 6843 /** 6844 * Set the enabled state of this view. The interpretation of the enabled 6845 * state varies by subclass. 6846 * 6847 * @param enabled True if this view is enabled, false otherwise. 6848 */ 6849 @RemotableViewMethod 6850 public void setEnabled(boolean enabled) { 6851 if (enabled == isEnabled()) return; 6852 6853 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 6854 6855 /* 6856 * The View most likely has to change its appearance, so refresh 6857 * the drawable state. 6858 */ 6859 refreshDrawableState(); 6860 6861 // Invalidate too, since the default behavior for views is to be 6862 // be drawn at 50% alpha rather than to change the drawable. 6863 invalidate(true); 6864 6865 if (!enabled) { 6866 cancelPendingInputEvents(); 6867 } 6868 } 6869 6870 /** 6871 * Set whether this view can receive the focus. 6872 * 6873 * Setting this to false will also ensure that this view is not focusable 6874 * in touch mode. 6875 * 6876 * @param focusable If true, this view can receive the focus. 6877 * 6878 * @see #setFocusableInTouchMode(boolean) 6879 * @attr ref android.R.styleable#View_focusable 6880 */ 6881 public void setFocusable(boolean focusable) { 6882 if (!focusable) { 6883 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 6884 } 6885 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 6886 } 6887 6888 /** 6889 * Set whether this view can receive focus while in touch mode. 6890 * 6891 * Setting this to true will also ensure that this view is focusable. 6892 * 6893 * @param focusableInTouchMode If true, this view can receive the focus while 6894 * in touch mode. 6895 * 6896 * @see #setFocusable(boolean) 6897 * @attr ref android.R.styleable#View_focusableInTouchMode 6898 */ 6899 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 6900 // Focusable in touch mode should always be set before the focusable flag 6901 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 6902 // which, in touch mode, will not successfully request focus on this view 6903 // because the focusable in touch mode flag is not set 6904 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 6905 if (focusableInTouchMode) { 6906 setFlags(FOCUSABLE, FOCUSABLE_MASK); 6907 } 6908 } 6909 6910 /** 6911 * Set whether this view should have sound effects enabled for events such as 6912 * clicking and touching. 6913 * 6914 * <p>You may wish to disable sound effects for a view if you already play sounds, 6915 * for instance, a dial key that plays dtmf tones. 6916 * 6917 * @param soundEffectsEnabled whether sound effects are enabled for this view. 6918 * @see #isSoundEffectsEnabled() 6919 * @see #playSoundEffect(int) 6920 * @attr ref android.R.styleable#View_soundEffectsEnabled 6921 */ 6922 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 6923 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 6924 } 6925 6926 /** 6927 * @return whether this view should have sound effects enabled for events such as 6928 * clicking and touching. 6929 * 6930 * @see #setSoundEffectsEnabled(boolean) 6931 * @see #playSoundEffect(int) 6932 * @attr ref android.R.styleable#View_soundEffectsEnabled 6933 */ 6934 @ViewDebug.ExportedProperty 6935 public boolean isSoundEffectsEnabled() { 6936 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 6937 } 6938 6939 /** 6940 * Set whether this view should have haptic feedback for events such as 6941 * long presses. 6942 * 6943 * <p>You may wish to disable haptic feedback if your view already controls 6944 * its own haptic feedback. 6945 * 6946 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 6947 * @see #isHapticFeedbackEnabled() 6948 * @see #performHapticFeedback(int) 6949 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6950 */ 6951 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 6952 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 6953 } 6954 6955 /** 6956 * @return whether this view should have haptic feedback enabled for events 6957 * long presses. 6958 * 6959 * @see #setHapticFeedbackEnabled(boolean) 6960 * @see #performHapticFeedback(int) 6961 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6962 */ 6963 @ViewDebug.ExportedProperty 6964 public boolean isHapticFeedbackEnabled() { 6965 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 6966 } 6967 6968 /** 6969 * Returns the layout direction for this view. 6970 * 6971 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 6972 * {@link #LAYOUT_DIRECTION_RTL}, 6973 * {@link #LAYOUT_DIRECTION_INHERIT} or 6974 * {@link #LAYOUT_DIRECTION_LOCALE}. 6975 * 6976 * @attr ref android.R.styleable#View_layoutDirection 6977 * 6978 * @hide 6979 */ 6980 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6981 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 6982 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 6983 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 6984 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 6985 }) 6986 @LayoutDir 6987 public int getRawLayoutDirection() { 6988 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 6989 } 6990 6991 /** 6992 * Set the layout direction for this view. This will propagate a reset of layout direction 6993 * resolution to the view's children and resolve layout direction for this view. 6994 * 6995 * @param layoutDirection the layout direction to set. Should be one of: 6996 * 6997 * {@link #LAYOUT_DIRECTION_LTR}, 6998 * {@link #LAYOUT_DIRECTION_RTL}, 6999 * {@link #LAYOUT_DIRECTION_INHERIT}, 7000 * {@link #LAYOUT_DIRECTION_LOCALE}. 7001 * 7002 * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution 7003 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 7004 * will return the default {@link #LAYOUT_DIRECTION_LTR}. 7005 * 7006 * @attr ref android.R.styleable#View_layoutDirection 7007 */ 7008 @RemotableViewMethod 7009 public void setLayoutDirection(@LayoutDir int layoutDirection) { 7010 if (getRawLayoutDirection() != layoutDirection) { 7011 // Reset the current layout direction and the resolved one 7012 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK; 7013 resetRtlProperties(); 7014 // Set the new layout direction (filtered) 7015 mPrivateFlags2 |= 7016 ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK); 7017 // We need to resolve all RTL properties as they all depend on layout direction 7018 resolveRtlPropertiesIfNeeded(); 7019 requestLayout(); 7020 invalidate(true); 7021 } 7022 } 7023 7024 /** 7025 * Returns the resolved layout direction for this view. 7026 * 7027 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 7028 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL. 7029 * 7030 * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version 7031 * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}. 7032 * 7033 * @attr ref android.R.styleable#View_layoutDirection 7034 */ 7035 @ViewDebug.ExportedProperty(category = "layout", mapping = { 7036 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 7037 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 7038 }) 7039 @ResolvedLayoutDir 7040 public int getLayoutDirection() { 7041 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 7042 if (targetSdkVersion < JELLY_BEAN_MR1) { 7043 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 7044 return LAYOUT_DIRECTION_RESOLVED_DEFAULT; 7045 } 7046 return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) == 7047 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 7048 } 7049 7050 /** 7051 * Indicates whether or not this view's layout is right-to-left. This is resolved from 7052 * layout attribute and/or the inherited value from the parent 7053 * 7054 * @return true if the layout is right-to-left. 7055 * 7056 * @hide 7057 */ 7058 @ViewDebug.ExportedProperty(category = "layout") 7059 public boolean isLayoutRtl() { 7060 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL); 7061 } 7062 7063 /** 7064 * Indicates whether the view is currently tracking transient state that the 7065 * app should not need to concern itself with saving and restoring, but that 7066 * the framework should take special note to preserve when possible. 7067 * 7068 * <p>A view with transient state cannot be trivially rebound from an external 7069 * data source, such as an adapter binding item views in a list. This may be 7070 * because the view is performing an animation, tracking user selection 7071 * of content, or similar.</p> 7072 * 7073 * @return true if the view has transient state 7074 */ 7075 @ViewDebug.ExportedProperty(category = "layout") 7076 public boolean hasTransientState() { 7077 return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE; 7078 } 7079 7080 /** 7081 * Set whether this view is currently tracking transient state that the 7082 * framework should attempt to preserve when possible. This flag is reference counted, 7083 * so every call to setHasTransientState(true) should be paired with a later call 7084 * to setHasTransientState(false). 7085 * 7086 * <p>A view with transient state cannot be trivially rebound from an external 7087 * data source, such as an adapter binding item views in a list. This may be 7088 * because the view is performing an animation, tracking user selection 7089 * of content, or similar.</p> 7090 * 7091 * @param hasTransientState true if this view has transient state 7092 */ 7093 public void setHasTransientState(boolean hasTransientState) { 7094 mTransientStateCount = hasTransientState ? mTransientStateCount + 1 : 7095 mTransientStateCount - 1; 7096 if (mTransientStateCount < 0) { 7097 mTransientStateCount = 0; 7098 Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " + 7099 "unmatched pair of setHasTransientState calls"); 7100 } else if ((hasTransientState && mTransientStateCount == 1) || 7101 (!hasTransientState && mTransientStateCount == 0)) { 7102 // update flag if we've just incremented up from 0 or decremented down to 0 7103 mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) | 7104 (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0); 7105 if (mParent != null) { 7106 try { 7107 mParent.childHasTransientStateChanged(this, hasTransientState); 7108 } catch (AbstractMethodError e) { 7109 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 7110 " does not fully implement ViewParent", e); 7111 } 7112 } 7113 } 7114 } 7115 7116 /** 7117 * Returns true if this view is currently attached to a window. 7118 */ 7119 public boolean isAttachedToWindow() { 7120 return mAttachInfo != null; 7121 } 7122 7123 /** 7124 * Returns true if this view has been through at least one layout since it 7125 * was last attached to or detached from a window. 7126 */ 7127 public boolean isLaidOut() { 7128 return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT; 7129 } 7130 7131 /** 7132 * If this view doesn't do any drawing on its own, set this flag to 7133 * allow further optimizations. By default, this flag is not set on 7134 * View, but could be set on some View subclasses such as ViewGroup. 7135 * 7136 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 7137 * you should clear this flag. 7138 * 7139 * @param willNotDraw whether or not this View draw on its own 7140 */ 7141 public void setWillNotDraw(boolean willNotDraw) { 7142 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 7143 } 7144 7145 /** 7146 * Returns whether or not this View draws on its own. 7147 * 7148 * @return true if this view has nothing to draw, false otherwise 7149 */ 7150 @ViewDebug.ExportedProperty(category = "drawing") 7151 public boolean willNotDraw() { 7152 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 7153 } 7154 7155 /** 7156 * When a View's drawing cache is enabled, drawing is redirected to an 7157 * offscreen bitmap. Some views, like an ImageView, must be able to 7158 * bypass this mechanism if they already draw a single bitmap, to avoid 7159 * unnecessary usage of the memory. 7160 * 7161 * @param willNotCacheDrawing true if this view does not cache its 7162 * drawing, false otherwise 7163 */ 7164 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 7165 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 7166 } 7167 7168 /** 7169 * Returns whether or not this View can cache its drawing or not. 7170 * 7171 * @return true if this view does not cache its drawing, false otherwise 7172 */ 7173 @ViewDebug.ExportedProperty(category = "drawing") 7174 public boolean willNotCacheDrawing() { 7175 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 7176 } 7177 7178 /** 7179 * Indicates whether this view reacts to click events or not. 7180 * 7181 * @return true if the view is clickable, false otherwise 7182 * 7183 * @see #setClickable(boolean) 7184 * @attr ref android.R.styleable#View_clickable 7185 */ 7186 @ViewDebug.ExportedProperty 7187 public boolean isClickable() { 7188 return (mViewFlags & CLICKABLE) == CLICKABLE; 7189 } 7190 7191 /** 7192 * Enables or disables click events for this view. When a view 7193 * is clickable it will change its state to "pressed" on every click. 7194 * Subclasses should set the view clickable to visually react to 7195 * user's clicks. 7196 * 7197 * @param clickable true to make the view clickable, false otherwise 7198 * 7199 * @see #isClickable() 7200 * @attr ref android.R.styleable#View_clickable 7201 */ 7202 public void setClickable(boolean clickable) { 7203 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 7204 } 7205 7206 /** 7207 * Indicates whether this view reacts to long click events or not. 7208 * 7209 * @return true if the view is long clickable, false otherwise 7210 * 7211 * @see #setLongClickable(boolean) 7212 * @attr ref android.R.styleable#View_longClickable 7213 */ 7214 public boolean isLongClickable() { 7215 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 7216 } 7217 7218 /** 7219 * Enables or disables long click events for this view. When a view is long 7220 * clickable it reacts to the user holding down the button for a longer 7221 * duration than a tap. This event can either launch the listener or a 7222 * context menu. 7223 * 7224 * @param longClickable true to make the view long clickable, false otherwise 7225 * @see #isLongClickable() 7226 * @attr ref android.R.styleable#View_longClickable 7227 */ 7228 public void setLongClickable(boolean longClickable) { 7229 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 7230 } 7231 7232 /** 7233 * Sets the pressed state for this view and provides a touch coordinate for 7234 * animation hinting. 7235 * 7236 * @param pressed Pass true to set the View's internal state to "pressed", 7237 * or false to reverts the View's internal state from a 7238 * previously set "pressed" state. 7239 * @param x The x coordinate of the touch that caused the press 7240 * @param y The y coordinate of the touch that caused the press 7241 */ 7242 private void setPressed(boolean pressed, float x, float y) { 7243 if (pressed) { 7244 drawableHotspotChanged(x, y); 7245 } 7246 7247 setPressed(pressed); 7248 } 7249 7250 /** 7251 * Sets the pressed state for this view. 7252 * 7253 * @see #isClickable() 7254 * @see #setClickable(boolean) 7255 * 7256 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 7257 * the View's internal state from a previously set "pressed" state. 7258 */ 7259 public void setPressed(boolean pressed) { 7260 final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED); 7261 7262 if (pressed) { 7263 mPrivateFlags |= PFLAG_PRESSED; 7264 } else { 7265 mPrivateFlags &= ~PFLAG_PRESSED; 7266 } 7267 7268 if (needsRefresh) { 7269 refreshDrawableState(); 7270 } 7271 dispatchSetPressed(pressed); 7272 } 7273 7274 /** 7275 * Dispatch setPressed to all of this View's children. 7276 * 7277 * @see #setPressed(boolean) 7278 * 7279 * @param pressed The new pressed state 7280 */ 7281 protected void dispatchSetPressed(boolean pressed) { 7282 } 7283 7284 /** 7285 * Indicates whether the view is currently in pressed state. Unless 7286 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 7287 * the pressed state. 7288 * 7289 * @see #setPressed(boolean) 7290 * @see #isClickable() 7291 * @see #setClickable(boolean) 7292 * 7293 * @return true if the view is currently pressed, false otherwise 7294 */ 7295 @ViewDebug.ExportedProperty 7296 public boolean isPressed() { 7297 return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED; 7298 } 7299 7300 /** 7301 * Indicates whether this view will save its state (that is, 7302 * whether its {@link #onSaveInstanceState} method will be called). 7303 * 7304 * @return Returns true if the view state saving is enabled, else false. 7305 * 7306 * @see #setSaveEnabled(boolean) 7307 * @attr ref android.R.styleable#View_saveEnabled 7308 */ 7309 public boolean isSaveEnabled() { 7310 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 7311 } 7312 7313 /** 7314 * Controls whether the saving of this view's state is 7315 * enabled (that is, whether its {@link #onSaveInstanceState} method 7316 * will be called). Note that even if freezing is enabled, the 7317 * view still must have an id assigned to it (via {@link #setId(int)}) 7318 * for its state to be saved. This flag can only disable the 7319 * saving of this view; any child views may still have their state saved. 7320 * 7321 * @param enabled Set to false to <em>disable</em> state saving, or true 7322 * (the default) to allow it. 7323 * 7324 * @see #isSaveEnabled() 7325 * @see #setId(int) 7326 * @see #onSaveInstanceState() 7327 * @attr ref android.R.styleable#View_saveEnabled 7328 */ 7329 public void setSaveEnabled(boolean enabled) { 7330 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 7331 } 7332 7333 /** 7334 * Gets whether the framework should discard touches when the view's 7335 * window is obscured by another visible window. 7336 * Refer to the {@link View} security documentation for more details. 7337 * 7338 * @return True if touch filtering is enabled. 7339 * 7340 * @see #setFilterTouchesWhenObscured(boolean) 7341 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 7342 */ 7343 @ViewDebug.ExportedProperty 7344 public boolean getFilterTouchesWhenObscured() { 7345 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 7346 } 7347 7348 /** 7349 * Sets whether the framework should discard touches when the view's 7350 * window is obscured by another visible window. 7351 * Refer to the {@link View} security documentation for more details. 7352 * 7353 * @param enabled True if touch filtering should be enabled. 7354 * 7355 * @see #getFilterTouchesWhenObscured 7356 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 7357 */ 7358 public void setFilterTouchesWhenObscured(boolean enabled) { 7359 setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0, 7360 FILTER_TOUCHES_WHEN_OBSCURED); 7361 } 7362 7363 /** 7364 * Indicates whether the entire hierarchy under this view will save its 7365 * state when a state saving traversal occurs from its parent. The default 7366 * is true; if false, these views will not be saved unless 7367 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 7368 * 7369 * @return Returns true if the view state saving from parent is enabled, else false. 7370 * 7371 * @see #setSaveFromParentEnabled(boolean) 7372 */ 7373 public boolean isSaveFromParentEnabled() { 7374 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 7375 } 7376 7377 /** 7378 * Controls whether the entire hierarchy under this view will save its 7379 * state when a state saving traversal occurs from its parent. The default 7380 * is true; if false, these views will not be saved unless 7381 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 7382 * 7383 * @param enabled Set to false to <em>disable</em> state saving, or true 7384 * (the default) to allow it. 7385 * 7386 * @see #isSaveFromParentEnabled() 7387 * @see #setId(int) 7388 * @see #onSaveInstanceState() 7389 */ 7390 public void setSaveFromParentEnabled(boolean enabled) { 7391 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 7392 } 7393 7394 7395 /** 7396 * Returns whether this View is able to take focus. 7397 * 7398 * @return True if this view can take focus, or false otherwise. 7399 * @attr ref android.R.styleable#View_focusable 7400 */ 7401 @ViewDebug.ExportedProperty(category = "focus") 7402 public final boolean isFocusable() { 7403 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 7404 } 7405 7406 /** 7407 * When a view is focusable, it may not want to take focus when in touch mode. 7408 * For example, a button would like focus when the user is navigating via a D-pad 7409 * so that the user can click on it, but once the user starts touching the screen, 7410 * the button shouldn't take focus 7411 * @return Whether the view is focusable in touch mode. 7412 * @attr ref android.R.styleable#View_focusableInTouchMode 7413 */ 7414 @ViewDebug.ExportedProperty 7415 public final boolean isFocusableInTouchMode() { 7416 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 7417 } 7418 7419 /** 7420 * Find the nearest view in the specified direction that can take focus. 7421 * This does not actually give focus to that view. 7422 * 7423 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7424 * 7425 * @return The nearest focusable in the specified direction, or null if none 7426 * can be found. 7427 */ 7428 public View focusSearch(@FocusRealDirection int direction) { 7429 if (mParent != null) { 7430 return mParent.focusSearch(this, direction); 7431 } else { 7432 return null; 7433 } 7434 } 7435 7436 /** 7437 * This method is the last chance for the focused view and its ancestors to 7438 * respond to an arrow key. This is called when the focused view did not 7439 * consume the key internally, nor could the view system find a new view in 7440 * the requested direction to give focus to. 7441 * 7442 * @param focused The currently focused view. 7443 * @param direction The direction focus wants to move. One of FOCUS_UP, 7444 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 7445 * @return True if the this view consumed this unhandled move. 7446 */ 7447 public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) { 7448 return false; 7449 } 7450 7451 /** 7452 * If a user manually specified the next view id for a particular direction, 7453 * use the root to look up the view. 7454 * @param root The root view of the hierarchy containing this view. 7455 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 7456 * or FOCUS_BACKWARD. 7457 * @return The user specified next view, or null if there is none. 7458 */ 7459 View findUserSetNextFocus(View root, @FocusDirection int direction) { 7460 switch (direction) { 7461 case FOCUS_LEFT: 7462 if (mNextFocusLeftId == View.NO_ID) return null; 7463 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 7464 case FOCUS_RIGHT: 7465 if (mNextFocusRightId == View.NO_ID) return null; 7466 return findViewInsideOutShouldExist(root, mNextFocusRightId); 7467 case FOCUS_UP: 7468 if (mNextFocusUpId == View.NO_ID) return null; 7469 return findViewInsideOutShouldExist(root, mNextFocusUpId); 7470 case FOCUS_DOWN: 7471 if (mNextFocusDownId == View.NO_ID) return null; 7472 return findViewInsideOutShouldExist(root, mNextFocusDownId); 7473 case FOCUS_FORWARD: 7474 if (mNextFocusForwardId == View.NO_ID) return null; 7475 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 7476 case FOCUS_BACKWARD: { 7477 if (mID == View.NO_ID) return null; 7478 final int id = mID; 7479 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 7480 @Override 7481 public boolean apply(View t) { 7482 return t.mNextFocusForwardId == id; 7483 } 7484 }); 7485 } 7486 } 7487 return null; 7488 } 7489 7490 private View findViewInsideOutShouldExist(View root, int id) { 7491 if (mMatchIdPredicate == null) { 7492 mMatchIdPredicate = new MatchIdPredicate(); 7493 } 7494 mMatchIdPredicate.mId = id; 7495 View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate); 7496 if (result == null) { 7497 Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id); 7498 } 7499 return result; 7500 } 7501 7502 /** 7503 * Find and return all focusable views that are descendants of this view, 7504 * possibly including this view if it is focusable itself. 7505 * 7506 * @param direction The direction of the focus 7507 * @return A list of focusable views 7508 */ 7509 public ArrayList<View> getFocusables(@FocusDirection int direction) { 7510 ArrayList<View> result = new ArrayList<View>(24); 7511 addFocusables(result, direction); 7512 return result; 7513 } 7514 7515 /** 7516 * Add any focusable views that are descendants of this view (possibly 7517 * including this view if it is focusable itself) to views. If we are in touch mode, 7518 * only add views that are also focusable in touch mode. 7519 * 7520 * @param views Focusable views found so far 7521 * @param direction The direction of the focus 7522 */ 7523 public void addFocusables(ArrayList<View> views, @FocusDirection int direction) { 7524 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 7525 } 7526 7527 /** 7528 * Adds any focusable views that are descendants of this view (possibly 7529 * including this view if it is focusable itself) to views. This method 7530 * adds all focusable views regardless if we are in touch mode or 7531 * only views focusable in touch mode if we are in touch mode or 7532 * only views that can take accessibility focus if accessibility is enabeld 7533 * depending on the focusable mode paramater. 7534 * 7535 * @param views Focusable views found so far or null if all we are interested is 7536 * the number of focusables. 7537 * @param direction The direction of the focus. 7538 * @param focusableMode The type of focusables to be added. 7539 * 7540 * @see #FOCUSABLES_ALL 7541 * @see #FOCUSABLES_TOUCH_MODE 7542 */ 7543 public void addFocusables(ArrayList<View> views, @FocusDirection int direction, 7544 @FocusableMode int focusableMode) { 7545 if (views == null) { 7546 return; 7547 } 7548 if (!isFocusable()) { 7549 return; 7550 } 7551 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE 7552 && isInTouchMode() && !isFocusableInTouchMode()) { 7553 return; 7554 } 7555 views.add(this); 7556 } 7557 7558 /** 7559 * Finds the Views that contain given text. The containment is case insensitive. 7560 * The search is performed by either the text that the View renders or the content 7561 * description that describes the view for accessibility purposes and the view does 7562 * not render or both. Clients can specify how the search is to be performed via 7563 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 7564 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 7565 * 7566 * @param outViews The output list of matching Views. 7567 * @param searched The text to match against. 7568 * 7569 * @see #FIND_VIEWS_WITH_TEXT 7570 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 7571 * @see #setContentDescription(CharSequence) 7572 */ 7573 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, 7574 @FindViewFlags int flags) { 7575 if (getAccessibilityNodeProvider() != null) { 7576 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 7577 outViews.add(this); 7578 } 7579 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 7580 && (searched != null && searched.length() > 0) 7581 && (mContentDescription != null && mContentDescription.length() > 0)) { 7582 String searchedLowerCase = searched.toString().toLowerCase(); 7583 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 7584 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 7585 outViews.add(this); 7586 } 7587 } 7588 } 7589 7590 /** 7591 * Find and return all touchable views that are descendants of this view, 7592 * possibly including this view if it is touchable itself. 7593 * 7594 * @return A list of touchable views 7595 */ 7596 public ArrayList<View> getTouchables() { 7597 ArrayList<View> result = new ArrayList<View>(); 7598 addTouchables(result); 7599 return result; 7600 } 7601 7602 /** 7603 * Add any touchable views that are descendants of this view (possibly 7604 * including this view if it is touchable itself) to views. 7605 * 7606 * @param views Touchable views found so far 7607 */ 7608 public void addTouchables(ArrayList<View> views) { 7609 final int viewFlags = mViewFlags; 7610 7611 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 7612 && (viewFlags & ENABLED_MASK) == ENABLED) { 7613 views.add(this); 7614 } 7615 } 7616 7617 /** 7618 * Returns whether this View is accessibility focused. 7619 * 7620 * @return True if this View is accessibility focused. 7621 */ 7622 public boolean isAccessibilityFocused() { 7623 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0; 7624 } 7625 7626 /** 7627 * Call this to try to give accessibility focus to this view. 7628 * 7629 * A view will not actually take focus if {@link AccessibilityManager#isEnabled()} 7630 * returns false or the view is no visible or the view already has accessibility 7631 * focus. 7632 * 7633 * See also {@link #focusSearch(int)}, which is what you call to say that you 7634 * have focus, and you want your parent to look for the next one. 7635 * 7636 * @return Whether this view actually took accessibility focus. 7637 * 7638 * @hide 7639 */ 7640 public boolean requestAccessibilityFocus() { 7641 AccessibilityManager manager = AccessibilityManager.getInstance(mContext); 7642 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 7643 return false; 7644 } 7645 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7646 return false; 7647 } 7648 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) { 7649 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED; 7650 ViewRootImpl viewRootImpl = getViewRootImpl(); 7651 if (viewRootImpl != null) { 7652 viewRootImpl.setAccessibilityFocus(this, null); 7653 } 7654 invalidate(); 7655 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); 7656 return true; 7657 } 7658 return false; 7659 } 7660 7661 /** 7662 * Call this to try to clear accessibility focus of this view. 7663 * 7664 * See also {@link #focusSearch(int)}, which is what you call to say that you 7665 * have focus, and you want your parent to look for the next one. 7666 * 7667 * @hide 7668 */ 7669 public void clearAccessibilityFocus() { 7670 clearAccessibilityFocusNoCallbacks(); 7671 // Clear the global reference of accessibility focus if this 7672 // view or any of its descendants had accessibility focus. 7673 ViewRootImpl viewRootImpl = getViewRootImpl(); 7674 if (viewRootImpl != null) { 7675 View focusHost = viewRootImpl.getAccessibilityFocusedHost(); 7676 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 7677 viewRootImpl.setAccessibilityFocus(null, null); 7678 } 7679 } 7680 } 7681 7682 private void sendAccessibilityHoverEvent(int eventType) { 7683 // Since we are not delivering to a client accessibility events from not 7684 // important views (unless the clinet request that) we need to fire the 7685 // event from the deepest view exposed to the client. As a consequence if 7686 // the user crosses a not exposed view the client will see enter and exit 7687 // of the exposed predecessor followed by and enter and exit of that same 7688 // predecessor when entering and exiting the not exposed descendant. This 7689 // is fine since the client has a clear idea which view is hovered at the 7690 // price of a couple more events being sent. This is a simple and 7691 // working solution. 7692 View source = this; 7693 while (true) { 7694 if (source.includeForAccessibility()) { 7695 source.sendAccessibilityEvent(eventType); 7696 return; 7697 } 7698 ViewParent parent = source.getParent(); 7699 if (parent instanceof View) { 7700 source = (View) parent; 7701 } else { 7702 return; 7703 } 7704 } 7705 } 7706 7707 /** 7708 * Clears accessibility focus without calling any callback methods 7709 * normally invoked in {@link #clearAccessibilityFocus()}. This method 7710 * is used for clearing accessibility focus when giving this focus to 7711 * another view. 7712 */ 7713 void clearAccessibilityFocusNoCallbacks() { 7714 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 7715 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 7716 invalidate(); 7717 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); 7718 } 7719 } 7720 7721 /** 7722 * Call this to try to give focus to a specific view or to one of its 7723 * descendants. 7724 * 7725 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7726 * false), or if it is focusable and it is not focusable in touch mode 7727 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7728 * 7729 * See also {@link #focusSearch(int)}, which is what you call to say that you 7730 * have focus, and you want your parent to look for the next one. 7731 * 7732 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 7733 * {@link #FOCUS_DOWN} and <code>null</code>. 7734 * 7735 * @return Whether this view or one of its descendants actually took focus. 7736 */ 7737 public final boolean requestFocus() { 7738 return requestFocus(View.FOCUS_DOWN); 7739 } 7740 7741 /** 7742 * Call this to try to give focus to a specific view or to one of its 7743 * descendants and give it a hint about what direction focus is heading. 7744 * 7745 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7746 * false), or if it is focusable and it is not focusable in touch mode 7747 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7748 * 7749 * See also {@link #focusSearch(int)}, which is what you call to say that you 7750 * have focus, and you want your parent to look for the next one. 7751 * 7752 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 7753 * <code>null</code> set for the previously focused rectangle. 7754 * 7755 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7756 * @return Whether this view or one of its descendants actually took focus. 7757 */ 7758 public final boolean requestFocus(int direction) { 7759 return requestFocus(direction, null); 7760 } 7761 7762 /** 7763 * Call this to try to give focus to a specific view or to one of its descendants 7764 * and give it hints about the direction and a specific rectangle that the focus 7765 * is coming from. The rectangle can help give larger views a finer grained hint 7766 * about where focus is coming from, and therefore, where to show selection, or 7767 * forward focus change internally. 7768 * 7769 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7770 * false), or if it is focusable and it is not focusable in touch mode 7771 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7772 * 7773 * A View will not take focus if it is not visible. 7774 * 7775 * A View will not take focus if one of its parents has 7776 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 7777 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 7778 * 7779 * See also {@link #focusSearch(int)}, which is what you call to say that you 7780 * have focus, and you want your parent to look for the next one. 7781 * 7782 * You may wish to override this method if your custom {@link View} has an internal 7783 * {@link View} that it wishes to forward the request to. 7784 * 7785 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7786 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 7787 * to give a finer grained hint about where focus is coming from. May be null 7788 * if there is no hint. 7789 * @return Whether this view or one of its descendants actually took focus. 7790 */ 7791 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 7792 return requestFocusNoSearch(direction, previouslyFocusedRect); 7793 } 7794 7795 private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) { 7796 // need to be focusable 7797 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 7798 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7799 return false; 7800 } 7801 7802 // need to be focusable in touch mode if in touch mode 7803 if (isInTouchMode() && 7804 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 7805 return false; 7806 } 7807 7808 // need to not have any parents blocking us 7809 if (hasAncestorThatBlocksDescendantFocus()) { 7810 return false; 7811 } 7812 7813 handleFocusGainInternal(direction, previouslyFocusedRect); 7814 return true; 7815 } 7816 7817 /** 7818 * Call this to try to give focus to a specific view or to one of its descendants. This is a 7819 * special variant of {@link #requestFocus() } that will allow views that are not focuable in 7820 * touch mode to request focus when they are touched. 7821 * 7822 * @return Whether this view or one of its descendants actually took focus. 7823 * 7824 * @see #isInTouchMode() 7825 * 7826 */ 7827 public final boolean requestFocusFromTouch() { 7828 // Leave touch mode if we need to 7829 if (isInTouchMode()) { 7830 ViewRootImpl viewRoot = getViewRootImpl(); 7831 if (viewRoot != null) { 7832 viewRoot.ensureTouchMode(false); 7833 } 7834 } 7835 return requestFocus(View.FOCUS_DOWN); 7836 } 7837 7838 /** 7839 * @return Whether any ancestor of this view blocks descendant focus. 7840 */ 7841 private boolean hasAncestorThatBlocksDescendantFocus() { 7842 final boolean focusableInTouchMode = isFocusableInTouchMode(); 7843 ViewParent ancestor = mParent; 7844 while (ancestor instanceof ViewGroup) { 7845 final ViewGroup vgAncestor = (ViewGroup) ancestor; 7846 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS 7847 || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) { 7848 return true; 7849 } else { 7850 ancestor = vgAncestor.getParent(); 7851 } 7852 } 7853 return false; 7854 } 7855 7856 /** 7857 * Gets the mode for determining whether this View is important for accessibility 7858 * which is if it fires accessibility events and if it is reported to 7859 * accessibility services that query the screen. 7860 * 7861 * @return The mode for determining whether a View is important for accessibility. 7862 * 7863 * @attr ref android.R.styleable#View_importantForAccessibility 7864 * 7865 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 7866 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 7867 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 7868 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 7869 */ 7870 @ViewDebug.ExportedProperty(category = "accessibility", mapping = { 7871 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"), 7872 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"), 7873 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"), 7874 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS, 7875 to = "noHideDescendants") 7876 }) 7877 public int getImportantForAccessibility() { 7878 return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 7879 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 7880 } 7881 7882 /** 7883 * Sets the live region mode for this view. This indicates to accessibility 7884 * services whether they should automatically notify the user about changes 7885 * to the view's content description or text, or to the content descriptions 7886 * or text of the view's children (where applicable). 7887 * <p> 7888 * For example, in a login screen with a TextView that displays an "incorrect 7889 * password" notification, that view should be marked as a live region with 7890 * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 7891 * <p> 7892 * To disable change notifications for this view, use 7893 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region 7894 * mode for most views. 7895 * <p> 7896 * To indicate that the user should be notified of changes, use 7897 * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 7898 * <p> 7899 * If the view's changes should interrupt ongoing speech and notify the user 7900 * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}. 7901 * 7902 * @param mode The live region mode for this view, one of: 7903 * <ul> 7904 * <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE} 7905 * <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE} 7906 * <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE} 7907 * </ul> 7908 * @attr ref android.R.styleable#View_accessibilityLiveRegion 7909 */ 7910 public void setAccessibilityLiveRegion(int mode) { 7911 if (mode != getAccessibilityLiveRegion()) { 7912 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 7913 mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT) 7914 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 7915 notifyViewAccessibilityStateChangedIfNeeded( 7916 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7917 } 7918 } 7919 7920 /** 7921 * Gets the live region mode for this View. 7922 * 7923 * @return The live region mode for the view. 7924 * 7925 * @attr ref android.R.styleable#View_accessibilityLiveRegion 7926 * 7927 * @see #setAccessibilityLiveRegion(int) 7928 */ 7929 public int getAccessibilityLiveRegion() { 7930 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK) 7931 >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 7932 } 7933 7934 /** 7935 * Sets how to determine whether this view is important for accessibility 7936 * which is if it fires accessibility events and if it is reported to 7937 * accessibility services that query the screen. 7938 * 7939 * @param mode How to determine whether this view is important for accessibility. 7940 * 7941 * @attr ref android.R.styleable#View_importantForAccessibility 7942 * 7943 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 7944 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 7945 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 7946 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 7947 */ 7948 public void setImportantForAccessibility(int mode) { 7949 final int oldMode = getImportantForAccessibility(); 7950 if (mode != oldMode) { 7951 // If we're moving between AUTO and another state, we might not need 7952 // to send a subtree changed notification. We'll store the computed 7953 // importance, since we'll need to check it later to make sure. 7954 final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO 7955 || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO; 7956 final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility(); 7957 mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 7958 mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT) 7959 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 7960 if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) { 7961 notifySubtreeAccessibilityStateChangedIfNeeded(); 7962 } else { 7963 notifyViewAccessibilityStateChangedIfNeeded( 7964 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7965 } 7966 } 7967 } 7968 7969 /** 7970 * Computes whether this view should be exposed for accessibility. In 7971 * general, views that are interactive or provide information are exposed 7972 * while views that serve only as containers are hidden. 7973 * <p> 7974 * If an ancestor of this view has importance 7975 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method 7976 * returns <code>false</code>. 7977 * <p> 7978 * Otherwise, the value is computed according to the view's 7979 * {@link #getImportantForAccessibility()} value: 7980 * <ol> 7981 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or 7982 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false 7983 * </code> 7984 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code> 7985 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if 7986 * view satisfies any of the following: 7987 * <ul> 7988 * <li>Is actionable, e.g. {@link #isClickable()}, 7989 * {@link #isLongClickable()}, or {@link #isFocusable()} 7990 * <li>Has an {@link AccessibilityDelegate} 7991 * <li>Has an interaction listener, e.g. {@link OnTouchListener}, 7992 * {@link OnKeyListener}, etc. 7993 * <li>Is an accessibility live region, e.g. 7994 * {@link #getAccessibilityLiveRegion()} is not 7995 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. 7996 * </ul> 7997 * </ol> 7998 * 7999 * @return Whether the view is exposed for accessibility. 8000 * @see #setImportantForAccessibility(int) 8001 * @see #getImportantForAccessibility() 8002 */ 8003 public boolean isImportantForAccessibility() { 8004 final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 8005 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 8006 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO 8007 || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 8008 return false; 8009 } 8010 8011 // Check parent mode to ensure we're not hidden. 8012 ViewParent parent = mParent; 8013 while (parent instanceof View) { 8014 if (((View) parent).getImportantForAccessibility() 8015 == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 8016 return false; 8017 } 8018 parent = parent.getParent(); 8019 } 8020 8021 return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility() 8022 || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null 8023 || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE; 8024 } 8025 8026 /** 8027 * Gets the parent for accessibility purposes. Note that the parent for 8028 * accessibility is not necessary the immediate parent. It is the first 8029 * predecessor that is important for accessibility. 8030 * 8031 * @return The parent for accessibility purposes. 8032 */ 8033 public ViewParent getParentForAccessibility() { 8034 if (mParent instanceof View) { 8035 View parentView = (View) mParent; 8036 if (parentView.includeForAccessibility()) { 8037 return mParent; 8038 } else { 8039 return mParent.getParentForAccessibility(); 8040 } 8041 } 8042 return null; 8043 } 8044 8045 /** 8046 * Adds the children of a given View for accessibility. Since some Views are 8047 * not important for accessibility the children for accessibility are not 8048 * necessarily direct children of the view, rather they are the first level of 8049 * descendants important for accessibility. 8050 * 8051 * @param children The list of children for accessibility. 8052 */ 8053 public void addChildrenForAccessibility(ArrayList<View> children) { 8054 8055 } 8056 8057 /** 8058 * Whether to regard this view for accessibility. A view is regarded for 8059 * accessibility if it is important for accessibility or the querying 8060 * accessibility service has explicitly requested that view not 8061 * important for accessibility are regarded. 8062 * 8063 * @return Whether to regard the view for accessibility. 8064 * 8065 * @hide 8066 */ 8067 public boolean includeForAccessibility() { 8068 if (mAttachInfo != null) { 8069 return (mAttachInfo.mAccessibilityFetchFlags 8070 & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0 8071 || isImportantForAccessibility(); 8072 } 8073 return false; 8074 } 8075 8076 /** 8077 * Returns whether the View is considered actionable from 8078 * accessibility perspective. Such view are important for 8079 * accessibility. 8080 * 8081 * @return True if the view is actionable for accessibility. 8082 * 8083 * @hide 8084 */ 8085 public boolean isActionableForAccessibility() { 8086 return (isClickable() || isLongClickable() || isFocusable()); 8087 } 8088 8089 /** 8090 * Returns whether the View has registered callbacks which makes it 8091 * important for accessibility. 8092 * 8093 * @return True if the view is actionable for accessibility. 8094 */ 8095 private boolean hasListenersForAccessibility() { 8096 ListenerInfo info = getListenerInfo(); 8097 return mTouchDelegate != null || info.mOnKeyListener != null 8098 || info.mOnTouchListener != null || info.mOnGenericMotionListener != null 8099 || info.mOnHoverListener != null || info.mOnDragListener != null; 8100 } 8101 8102 /** 8103 * Notifies that the accessibility state of this view changed. The change 8104 * is local to this view and does not represent structural changes such 8105 * as children and parent. For example, the view became focusable. The 8106 * notification is at at most once every 8107 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 8108 * to avoid unnecessary load to the system. Also once a view has a pending 8109 * notification this method is a NOP until the notification has been sent. 8110 * 8111 * @hide 8112 */ 8113 public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) { 8114 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 8115 return; 8116 } 8117 if (mSendViewStateChangedAccessibilityEvent == null) { 8118 mSendViewStateChangedAccessibilityEvent = 8119 new SendViewStateChangedAccessibilityEvent(); 8120 } 8121 mSendViewStateChangedAccessibilityEvent.runOrPost(changeType); 8122 } 8123 8124 /** 8125 * Notifies that the accessibility state of this view changed. The change 8126 * is *not* local to this view and does represent structural changes such 8127 * as children and parent. For example, the view size changed. The 8128 * notification is at at most once every 8129 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 8130 * to avoid unnecessary load to the system. Also once a view has a pending 8131 * notification this method is a NOP until the notification has been sent. 8132 * 8133 * @hide 8134 */ 8135 public void notifySubtreeAccessibilityStateChangedIfNeeded() { 8136 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 8137 return; 8138 } 8139 if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) { 8140 mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 8141 if (mParent != null) { 8142 try { 8143 mParent.notifySubtreeAccessibilityStateChanged( 8144 this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE); 8145 } catch (AbstractMethodError e) { 8146 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 8147 " does not fully implement ViewParent", e); 8148 } 8149 } 8150 } 8151 } 8152 8153 /** 8154 * Reset the flag indicating the accessibility state of the subtree rooted 8155 * at this view changed. 8156 */ 8157 void resetSubtreeAccessibilityStateChanged() { 8158 mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 8159 } 8160 8161 /** 8162 * Report an accessibility action to this view's parents for delegated processing. 8163 * 8164 * <p>Implementations of {@link #performAccessibilityAction(int, Bundle)} may internally 8165 * call this method to delegate an accessibility action to a supporting parent. If the parent 8166 * returns true from its 8167 * {@link ViewParent#onNestedPrePerformAccessibilityAction(View, int, android.os.Bundle)} 8168 * method this method will return true to signify that the action was consumed.</p> 8169 * 8170 * <p>This method is useful for implementing nested scrolling child views. If 8171 * {@link #isNestedScrollingEnabled()} returns true and the action is a scrolling action 8172 * a custom view implementation may invoke this method to allow a parent to consume the 8173 * scroll first. If this method returns true the custom view should skip its own scrolling 8174 * behavior.</p> 8175 * 8176 * @param action Accessibility action to delegate 8177 * @param arguments Optional action arguments 8178 * @return true if the action was consumed by a parent 8179 */ 8180 public boolean dispatchNestedPrePerformAccessibilityAction(int action, Bundle arguments) { 8181 for (ViewParent p = getParent(); p != null; p = p.getParent()) { 8182 if (p.onNestedPrePerformAccessibilityAction(this, action, arguments)) { 8183 return true; 8184 } 8185 } 8186 return false; 8187 } 8188 8189 /** 8190 * Performs the specified accessibility action on the view. For 8191 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 8192 * <p> 8193 * If an {@link AccessibilityDelegate} has been specified via calling 8194 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 8195 * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)} 8196 * is responsible for handling this call. 8197 * </p> 8198 * 8199 * <p>The default implementation will delegate 8200 * {@link AccessibilityNodeInfo#ACTION_SCROLL_BACKWARD} and 8201 * {@link AccessibilityNodeInfo#ACTION_SCROLL_FORWARD} to nested scrolling parents if 8202 * {@link #isNestedScrollingEnabled() nested scrolling is enabled} on this view.</p> 8203 * 8204 * @param action The action to perform. 8205 * @param arguments Optional action arguments. 8206 * @return Whether the action was performed. 8207 */ 8208 public boolean performAccessibilityAction(int action, Bundle arguments) { 8209 if (mAccessibilityDelegate != null) { 8210 return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments); 8211 } else { 8212 return performAccessibilityActionInternal(action, arguments); 8213 } 8214 } 8215 8216 /** 8217 * @see #performAccessibilityAction(int, Bundle) 8218 * 8219 * Note: Called from the default {@link AccessibilityDelegate}. 8220 * 8221 * @hide Until we've refactored all accessibility delegation methods. 8222 */ 8223 public boolean performAccessibilityActionInternal(int action, Bundle arguments) { 8224 if (isNestedScrollingEnabled() 8225 && (action == AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD 8226 || action == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD)) { 8227 if (dispatchNestedPrePerformAccessibilityAction(action, arguments)) { 8228 return true; 8229 } 8230 } 8231 8232 switch (action) { 8233 case AccessibilityNodeInfo.ACTION_CLICK: { 8234 if (isClickable()) { 8235 performClick(); 8236 return true; 8237 } 8238 } break; 8239 case AccessibilityNodeInfo.ACTION_LONG_CLICK: { 8240 if (isLongClickable()) { 8241 performLongClick(); 8242 return true; 8243 } 8244 } break; 8245 case AccessibilityNodeInfo.ACTION_FOCUS: { 8246 if (!hasFocus()) { 8247 // Get out of touch mode since accessibility 8248 // wants to move focus around. 8249 getViewRootImpl().ensureTouchMode(false); 8250 return requestFocus(); 8251 } 8252 } break; 8253 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 8254 if (hasFocus()) { 8255 clearFocus(); 8256 return !isFocused(); 8257 } 8258 } break; 8259 case AccessibilityNodeInfo.ACTION_SELECT: { 8260 if (!isSelected()) { 8261 setSelected(true); 8262 return isSelected(); 8263 } 8264 } break; 8265 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: { 8266 if (isSelected()) { 8267 setSelected(false); 8268 return !isSelected(); 8269 } 8270 } break; 8271 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 8272 if (!isAccessibilityFocused()) { 8273 return requestAccessibilityFocus(); 8274 } 8275 } break; 8276 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 8277 if (isAccessibilityFocused()) { 8278 clearAccessibilityFocus(); 8279 return true; 8280 } 8281 } break; 8282 case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { 8283 if (arguments != null) { 8284 final int granularity = arguments.getInt( 8285 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 8286 final boolean extendSelection = arguments.getBoolean( 8287 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 8288 return traverseAtGranularity(granularity, true, extendSelection); 8289 } 8290 } break; 8291 case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { 8292 if (arguments != null) { 8293 final int granularity = arguments.getInt( 8294 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 8295 final boolean extendSelection = arguments.getBoolean( 8296 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 8297 return traverseAtGranularity(granularity, false, extendSelection); 8298 } 8299 } break; 8300 case AccessibilityNodeInfo.ACTION_SET_SELECTION: { 8301 CharSequence text = getIterableTextForAccessibility(); 8302 if (text == null) { 8303 return false; 8304 } 8305 final int start = (arguments != null) ? arguments.getInt( 8306 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1; 8307 final int end = (arguments != null) ? arguments.getInt( 8308 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1; 8309 // Only cursor position can be specified (selection length == 0) 8310 if ((getAccessibilitySelectionStart() != start 8311 || getAccessibilitySelectionEnd() != end) 8312 && (start == end)) { 8313 setAccessibilitySelection(start, end); 8314 notifyViewAccessibilityStateChangedIfNeeded( 8315 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 8316 return true; 8317 } 8318 } break; 8319 } 8320 return false; 8321 } 8322 8323 private boolean traverseAtGranularity(int granularity, boolean forward, 8324 boolean extendSelection) { 8325 CharSequence text = getIterableTextForAccessibility(); 8326 if (text == null || text.length() == 0) { 8327 return false; 8328 } 8329 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 8330 if (iterator == null) { 8331 return false; 8332 } 8333 int current = getAccessibilitySelectionEnd(); 8334 if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 8335 current = forward ? 0 : text.length(); 8336 } 8337 final int[] range = forward ? iterator.following(current) : iterator.preceding(current); 8338 if (range == null) { 8339 return false; 8340 } 8341 final int segmentStart = range[0]; 8342 final int segmentEnd = range[1]; 8343 int selectionStart; 8344 int selectionEnd; 8345 if (extendSelection && isAccessibilitySelectionExtendable()) { 8346 selectionStart = getAccessibilitySelectionStart(); 8347 if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 8348 selectionStart = forward ? segmentStart : segmentEnd; 8349 } 8350 selectionEnd = forward ? segmentEnd : segmentStart; 8351 } else { 8352 selectionStart = selectionEnd= forward ? segmentEnd : segmentStart; 8353 } 8354 setAccessibilitySelection(selectionStart, selectionEnd); 8355 final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY 8356 : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY; 8357 sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd); 8358 return true; 8359 } 8360 8361 /** 8362 * Gets the text reported for accessibility purposes. 8363 * 8364 * @return The accessibility text. 8365 * 8366 * @hide 8367 */ 8368 public CharSequence getIterableTextForAccessibility() { 8369 return getContentDescription(); 8370 } 8371 8372 /** 8373 * Gets whether accessibility selection can be extended. 8374 * 8375 * @return If selection is extensible. 8376 * 8377 * @hide 8378 */ 8379 public boolean isAccessibilitySelectionExtendable() { 8380 return false; 8381 } 8382 8383 /** 8384 * @hide 8385 */ 8386 public int getAccessibilitySelectionStart() { 8387 return mAccessibilityCursorPosition; 8388 } 8389 8390 /** 8391 * @hide 8392 */ 8393 public int getAccessibilitySelectionEnd() { 8394 return getAccessibilitySelectionStart(); 8395 } 8396 8397 /** 8398 * @hide 8399 */ 8400 public void setAccessibilitySelection(int start, int end) { 8401 if (start == end && end == mAccessibilityCursorPosition) { 8402 return; 8403 } 8404 if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) { 8405 mAccessibilityCursorPosition = start; 8406 } else { 8407 mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 8408 } 8409 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); 8410 } 8411 8412 private void sendViewTextTraversedAtGranularityEvent(int action, int granularity, 8413 int fromIndex, int toIndex) { 8414 if (mParent == null) { 8415 return; 8416 } 8417 AccessibilityEvent event = AccessibilityEvent.obtain( 8418 AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY); 8419 onInitializeAccessibilityEvent(event); 8420 onPopulateAccessibilityEvent(event); 8421 event.setFromIndex(fromIndex); 8422 event.setToIndex(toIndex); 8423 event.setAction(action); 8424 event.setMovementGranularity(granularity); 8425 mParent.requestSendAccessibilityEvent(this, event); 8426 } 8427 8428 /** 8429 * @hide 8430 */ 8431 public TextSegmentIterator getIteratorForGranularity(int granularity) { 8432 switch (granularity) { 8433 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { 8434 CharSequence text = getIterableTextForAccessibility(); 8435 if (text != null && text.length() > 0) { 8436 CharacterTextSegmentIterator iterator = 8437 CharacterTextSegmentIterator.getInstance( 8438 mContext.getResources().getConfiguration().locale); 8439 iterator.initialize(text.toString()); 8440 return iterator; 8441 } 8442 } break; 8443 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: { 8444 CharSequence text = getIterableTextForAccessibility(); 8445 if (text != null && text.length() > 0) { 8446 WordTextSegmentIterator iterator = 8447 WordTextSegmentIterator.getInstance( 8448 mContext.getResources().getConfiguration().locale); 8449 iterator.initialize(text.toString()); 8450 return iterator; 8451 } 8452 } break; 8453 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: { 8454 CharSequence text = getIterableTextForAccessibility(); 8455 if (text != null && text.length() > 0) { 8456 ParagraphTextSegmentIterator iterator = 8457 ParagraphTextSegmentIterator.getInstance(); 8458 iterator.initialize(text.toString()); 8459 return iterator; 8460 } 8461 } break; 8462 } 8463 return null; 8464 } 8465 8466 /** 8467 * @hide 8468 */ 8469 public void dispatchStartTemporaryDetach() { 8470 onStartTemporaryDetach(); 8471 } 8472 8473 /** 8474 * This is called when a container is going to temporarily detach a child, with 8475 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 8476 * It will either be followed by {@link #onFinishTemporaryDetach()} or 8477 * {@link #onDetachedFromWindow()} when the container is done. 8478 */ 8479 public void onStartTemporaryDetach() { 8480 removeUnsetPressCallback(); 8481 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 8482 } 8483 8484 /** 8485 * @hide 8486 */ 8487 public void dispatchFinishTemporaryDetach() { 8488 onFinishTemporaryDetach(); 8489 } 8490 8491 /** 8492 * Called after {@link #onStartTemporaryDetach} when the container is done 8493 * changing the view. 8494 */ 8495 public void onFinishTemporaryDetach() { 8496 } 8497 8498 /** 8499 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 8500 * for this view's window. Returns null if the view is not currently attached 8501 * to the window. Normally you will not need to use this directly, but 8502 * just use the standard high-level event callbacks like 8503 * {@link #onKeyDown(int, KeyEvent)}. 8504 */ 8505 public KeyEvent.DispatcherState getKeyDispatcherState() { 8506 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 8507 } 8508 8509 /** 8510 * Dispatch a key event before it is processed by any input method 8511 * associated with the view hierarchy. This can be used to intercept 8512 * key events in special situations before the IME consumes them; a 8513 * typical example would be handling the BACK key to update the application's 8514 * UI instead of allowing the IME to see it and close itself. 8515 * 8516 * @param event The key event to be dispatched. 8517 * @return True if the event was handled, false otherwise. 8518 */ 8519 public boolean dispatchKeyEventPreIme(KeyEvent event) { 8520 return onKeyPreIme(event.getKeyCode(), event); 8521 } 8522 8523 /** 8524 * Dispatch a key event to the next view on the focus path. This path runs 8525 * from the top of the view tree down to the currently focused view. If this 8526 * view has focus, it will dispatch to itself. Otherwise it will dispatch 8527 * the next node down the focus path. This method also fires any key 8528 * listeners. 8529 * 8530 * @param event The key event to be dispatched. 8531 * @return True if the event was handled, false otherwise. 8532 */ 8533 public boolean dispatchKeyEvent(KeyEvent event) { 8534 if (mInputEventConsistencyVerifier != null) { 8535 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 8536 } 8537 8538 // Give any attached key listener a first crack at the event. 8539 //noinspection SimplifiableIfStatement 8540 ListenerInfo li = mListenerInfo; 8541 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 8542 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 8543 return true; 8544 } 8545 8546 if (event.dispatch(this, mAttachInfo != null 8547 ? mAttachInfo.mKeyDispatchState : null, this)) { 8548 return true; 8549 } 8550 8551 if (mInputEventConsistencyVerifier != null) { 8552 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8553 } 8554 return false; 8555 } 8556 8557 /** 8558 * Dispatches a key shortcut event. 8559 * 8560 * @param event The key event to be dispatched. 8561 * @return True if the event was handled by the view, false otherwise. 8562 */ 8563 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 8564 return onKeyShortcut(event.getKeyCode(), event); 8565 } 8566 8567 /** 8568 * Pass the touch screen motion event down to the target view, or this 8569 * view if it is the target. 8570 * 8571 * @param event The motion event to be dispatched. 8572 * @return True if the event was handled by the view, false otherwise. 8573 */ 8574 public boolean dispatchTouchEvent(MotionEvent event) { 8575 boolean result = false; 8576 8577 if (mInputEventConsistencyVerifier != null) { 8578 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 8579 } 8580 8581 final int actionMasked = event.getActionMasked(); 8582 if (actionMasked == MotionEvent.ACTION_DOWN) { 8583 // Defensive cleanup for new gesture 8584 stopNestedScroll(); 8585 } 8586 8587 if (onFilterTouchEventForSecurity(event)) { 8588 //noinspection SimplifiableIfStatement 8589 ListenerInfo li = mListenerInfo; 8590 if (li != null && li.mOnTouchListener != null 8591 && (mViewFlags & ENABLED_MASK) == ENABLED 8592 && li.mOnTouchListener.onTouch(this, event)) { 8593 result = true; 8594 } 8595 8596 if (!result && onTouchEvent(event)) { 8597 result = true; 8598 } 8599 } 8600 8601 if (!result && mInputEventConsistencyVerifier != null) { 8602 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8603 } 8604 8605 // Clean up after nested scrolls if this is the end of a gesture; 8606 // also cancel it if we tried an ACTION_DOWN but we didn't want the rest 8607 // of the gesture. 8608 if (actionMasked == MotionEvent.ACTION_UP || 8609 actionMasked == MotionEvent.ACTION_CANCEL || 8610 (actionMasked == MotionEvent.ACTION_DOWN && !result)) { 8611 stopNestedScroll(); 8612 } 8613 8614 return result; 8615 } 8616 8617 /** 8618 * Filter the touch event to apply security policies. 8619 * 8620 * @param event The motion event to be filtered. 8621 * @return True if the event should be dispatched, false if the event should be dropped. 8622 * 8623 * @see #getFilterTouchesWhenObscured 8624 */ 8625 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 8626 //noinspection RedundantIfStatement 8627 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 8628 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 8629 // Window is obscured, drop this touch. 8630 return false; 8631 } 8632 return true; 8633 } 8634 8635 /** 8636 * Pass a trackball motion event down to the focused view. 8637 * 8638 * @param event The motion event to be dispatched. 8639 * @return True if the event was handled by the view, false otherwise. 8640 */ 8641 public boolean dispatchTrackballEvent(MotionEvent event) { 8642 if (mInputEventConsistencyVerifier != null) { 8643 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 8644 } 8645 8646 return onTrackballEvent(event); 8647 } 8648 8649 /** 8650 * Dispatch a generic motion event. 8651 * <p> 8652 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 8653 * are delivered to the view under the pointer. All other generic motion events are 8654 * delivered to the focused view. Hover events are handled specially and are delivered 8655 * to {@link #onHoverEvent(MotionEvent)}. 8656 * </p> 8657 * 8658 * @param event The motion event to be dispatched. 8659 * @return True if the event was handled by the view, false otherwise. 8660 */ 8661 public boolean dispatchGenericMotionEvent(MotionEvent event) { 8662 if (mInputEventConsistencyVerifier != null) { 8663 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 8664 } 8665 8666 final int source = event.getSource(); 8667 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 8668 final int action = event.getAction(); 8669 if (action == MotionEvent.ACTION_HOVER_ENTER 8670 || action == MotionEvent.ACTION_HOVER_MOVE 8671 || action == MotionEvent.ACTION_HOVER_EXIT) { 8672 if (dispatchHoverEvent(event)) { 8673 return true; 8674 } 8675 } else if (dispatchGenericPointerEvent(event)) { 8676 return true; 8677 } 8678 } else if (dispatchGenericFocusedEvent(event)) { 8679 return true; 8680 } 8681 8682 if (dispatchGenericMotionEventInternal(event)) { 8683 return true; 8684 } 8685 8686 if (mInputEventConsistencyVerifier != null) { 8687 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8688 } 8689 return false; 8690 } 8691 8692 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 8693 //noinspection SimplifiableIfStatement 8694 ListenerInfo li = mListenerInfo; 8695 if (li != null && li.mOnGenericMotionListener != null 8696 && (mViewFlags & ENABLED_MASK) == ENABLED 8697 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 8698 return true; 8699 } 8700 8701 if (onGenericMotionEvent(event)) { 8702 return true; 8703 } 8704 8705 if (mInputEventConsistencyVerifier != null) { 8706 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8707 } 8708 return false; 8709 } 8710 8711 /** 8712 * Dispatch a hover event. 8713 * <p> 8714 * Do not call this method directly. 8715 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8716 * </p> 8717 * 8718 * @param event The motion event to be dispatched. 8719 * @return True if the event was handled by the view, false otherwise. 8720 */ 8721 protected boolean dispatchHoverEvent(MotionEvent event) { 8722 ListenerInfo li = mListenerInfo; 8723 //noinspection SimplifiableIfStatement 8724 if (li != null && li.mOnHoverListener != null 8725 && (mViewFlags & ENABLED_MASK) == ENABLED 8726 && li.mOnHoverListener.onHover(this, event)) { 8727 return true; 8728 } 8729 8730 return onHoverEvent(event); 8731 } 8732 8733 /** 8734 * Returns true if the view has a child to which it has recently sent 8735 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 8736 * it does not have a hovered child, then it must be the innermost hovered view. 8737 * @hide 8738 */ 8739 protected boolean hasHoveredChild() { 8740 return false; 8741 } 8742 8743 /** 8744 * Dispatch a generic motion event to the view under the first pointer. 8745 * <p> 8746 * Do not call this method directly. 8747 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8748 * </p> 8749 * 8750 * @param event The motion event to be dispatched. 8751 * @return True if the event was handled by the view, false otherwise. 8752 */ 8753 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 8754 return false; 8755 } 8756 8757 /** 8758 * Dispatch a generic motion event to the currently focused view. 8759 * <p> 8760 * Do not call this method directly. 8761 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8762 * </p> 8763 * 8764 * @param event The motion event to be dispatched. 8765 * @return True if the event was handled by the view, false otherwise. 8766 */ 8767 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 8768 return false; 8769 } 8770 8771 /** 8772 * Dispatch a pointer event. 8773 * <p> 8774 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 8775 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 8776 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 8777 * and should not be expected to handle other pointing device features. 8778 * </p> 8779 * 8780 * @param event The motion event to be dispatched. 8781 * @return True if the event was handled by the view, false otherwise. 8782 * @hide 8783 */ 8784 public final boolean dispatchPointerEvent(MotionEvent event) { 8785 if (event.isTouchEvent()) { 8786 return dispatchTouchEvent(event); 8787 } else { 8788 return dispatchGenericMotionEvent(event); 8789 } 8790 } 8791 8792 /** 8793 * Called when the window containing this view gains or loses window focus. 8794 * ViewGroups should override to route to their children. 8795 * 8796 * @param hasFocus True if the window containing this view now has focus, 8797 * false otherwise. 8798 */ 8799 public void dispatchWindowFocusChanged(boolean hasFocus) { 8800 onWindowFocusChanged(hasFocus); 8801 } 8802 8803 /** 8804 * Called when the window containing this view gains or loses focus. Note 8805 * that this is separate from view focus: to receive key events, both 8806 * your view and its window must have focus. If a window is displayed 8807 * on top of yours that takes input focus, then your own window will lose 8808 * focus but the view focus will remain unchanged. 8809 * 8810 * @param hasWindowFocus True if the window containing this view now has 8811 * focus, false otherwise. 8812 */ 8813 public void onWindowFocusChanged(boolean hasWindowFocus) { 8814 InputMethodManager imm = InputMethodManager.peekInstance(); 8815 if (!hasWindowFocus) { 8816 if (isPressed()) { 8817 setPressed(false); 8818 } 8819 if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 8820 imm.focusOut(this); 8821 } 8822 removeLongPressCallback(); 8823 removeTapCallback(); 8824 onFocusLost(); 8825 } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 8826 imm.focusIn(this); 8827 } 8828 refreshDrawableState(); 8829 } 8830 8831 /** 8832 * Returns true if this view is in a window that currently has window focus. 8833 * Note that this is not the same as the view itself having focus. 8834 * 8835 * @return True if this view is in a window that currently has window focus. 8836 */ 8837 public boolean hasWindowFocus() { 8838 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 8839 } 8840 8841 /** 8842 * Dispatch a view visibility change down the view hierarchy. 8843 * ViewGroups should override to route to their children. 8844 * @param changedView The view whose visibility changed. Could be 'this' or 8845 * an ancestor view. 8846 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 8847 * {@link #INVISIBLE} or {@link #GONE}. 8848 */ 8849 protected void dispatchVisibilityChanged(@NonNull View changedView, 8850 @Visibility int visibility) { 8851 onVisibilityChanged(changedView, visibility); 8852 } 8853 8854 /** 8855 * Called when the visibility of the view or an ancestor of the view is changed. 8856 * @param changedView The view whose visibility changed. Could be 'this' or 8857 * an ancestor view. 8858 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 8859 * {@link #INVISIBLE} or {@link #GONE}. 8860 */ 8861 protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) { 8862 if (visibility == VISIBLE) { 8863 if (mAttachInfo != null) { 8864 initialAwakenScrollBars(); 8865 } else { 8866 mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 8867 } 8868 } 8869 } 8870 8871 /** 8872 * Dispatch a hint about whether this view is displayed. For instance, when 8873 * a View moves out of the screen, it might receives a display hint indicating 8874 * the view is not displayed. Applications should not <em>rely</em> on this hint 8875 * as there is no guarantee that they will receive one. 8876 * 8877 * @param hint A hint about whether or not this view is displayed: 8878 * {@link #VISIBLE} or {@link #INVISIBLE}. 8879 */ 8880 public void dispatchDisplayHint(@Visibility int hint) { 8881 onDisplayHint(hint); 8882 } 8883 8884 /** 8885 * Gives this view a hint about whether is displayed or not. For instance, when 8886 * a View moves out of the screen, it might receives a display hint indicating 8887 * the view is not displayed. Applications should not <em>rely</em> on this hint 8888 * as there is no guarantee that they will receive one. 8889 * 8890 * @param hint A hint about whether or not this view is displayed: 8891 * {@link #VISIBLE} or {@link #INVISIBLE}. 8892 */ 8893 protected void onDisplayHint(@Visibility int hint) { 8894 } 8895 8896 /** 8897 * Dispatch a window visibility change down the view hierarchy. 8898 * ViewGroups should override to route to their children. 8899 * 8900 * @param visibility The new visibility of the window. 8901 * 8902 * @see #onWindowVisibilityChanged(int) 8903 */ 8904 public void dispatchWindowVisibilityChanged(@Visibility int visibility) { 8905 onWindowVisibilityChanged(visibility); 8906 } 8907 8908 /** 8909 * Called when the window containing has change its visibility 8910 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 8911 * that this tells you whether or not your window is being made visible 8912 * to the window manager; this does <em>not</em> tell you whether or not 8913 * your window is obscured by other windows on the screen, even if it 8914 * is itself visible. 8915 * 8916 * @param visibility The new visibility of the window. 8917 */ 8918 protected void onWindowVisibilityChanged(@Visibility int visibility) { 8919 if (visibility == VISIBLE) { 8920 initialAwakenScrollBars(); 8921 } 8922 } 8923 8924 /** 8925 * Returns the current visibility of the window this view is attached to 8926 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 8927 * 8928 * @return Returns the current visibility of the view's window. 8929 */ 8930 @Visibility 8931 public int getWindowVisibility() { 8932 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 8933 } 8934 8935 /** 8936 * Retrieve the overall visible display size in which the window this view is 8937 * attached to has been positioned in. This takes into account screen 8938 * decorations above the window, for both cases where the window itself 8939 * is being position inside of them or the window is being placed under 8940 * then and covered insets are used for the window to position its content 8941 * inside. In effect, this tells you the available area where content can 8942 * be placed and remain visible to users. 8943 * 8944 * <p>This function requires an IPC back to the window manager to retrieve 8945 * the requested information, so should not be used in performance critical 8946 * code like drawing. 8947 * 8948 * @param outRect Filled in with the visible display frame. If the view 8949 * is not attached to a window, this is simply the raw display size. 8950 */ 8951 public void getWindowVisibleDisplayFrame(Rect outRect) { 8952 if (mAttachInfo != null) { 8953 try { 8954 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 8955 } catch (RemoteException e) { 8956 return; 8957 } 8958 // XXX This is really broken, and probably all needs to be done 8959 // in the window manager, and we need to know more about whether 8960 // we want the area behind or in front of the IME. 8961 final Rect insets = mAttachInfo.mVisibleInsets; 8962 outRect.left += insets.left; 8963 outRect.top += insets.top; 8964 outRect.right -= insets.right; 8965 outRect.bottom -= insets.bottom; 8966 return; 8967 } 8968 // The view is not attached to a display so we don't have a context. 8969 // Make a best guess about the display size. 8970 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 8971 d.getRectSize(outRect); 8972 } 8973 8974 /** 8975 * Dispatch a notification about a resource configuration change down 8976 * the view hierarchy. 8977 * ViewGroups should override to route to their children. 8978 * 8979 * @param newConfig The new resource configuration. 8980 * 8981 * @see #onConfigurationChanged(android.content.res.Configuration) 8982 */ 8983 public void dispatchConfigurationChanged(Configuration newConfig) { 8984 onConfigurationChanged(newConfig); 8985 } 8986 8987 /** 8988 * Called when the current configuration of the resources being used 8989 * by the application have changed. You can use this to decide when 8990 * to reload resources that can changed based on orientation and other 8991 * configuration characterstics. You only need to use this if you are 8992 * not relying on the normal {@link android.app.Activity} mechanism of 8993 * recreating the activity instance upon a configuration change. 8994 * 8995 * @param newConfig The new resource configuration. 8996 */ 8997 protected void onConfigurationChanged(Configuration newConfig) { 8998 } 8999 9000 /** 9001 * Private function to aggregate all per-view attributes in to the view 9002 * root. 9003 */ 9004 void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) { 9005 performCollectViewAttributes(attachInfo, visibility); 9006 } 9007 9008 void performCollectViewAttributes(AttachInfo attachInfo, int visibility) { 9009 if ((visibility & VISIBILITY_MASK) == VISIBLE) { 9010 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 9011 attachInfo.mKeepScreenOn = true; 9012 } 9013 attachInfo.mSystemUiVisibility |= mSystemUiVisibility; 9014 ListenerInfo li = mListenerInfo; 9015 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 9016 attachInfo.mHasSystemUiListeners = true; 9017 } 9018 } 9019 } 9020 9021 void needGlobalAttributesUpdate(boolean force) { 9022 final AttachInfo ai = mAttachInfo; 9023 if (ai != null && !ai.mRecomputeGlobalAttributes) { 9024 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 9025 || ai.mHasSystemUiListeners) { 9026 ai.mRecomputeGlobalAttributes = true; 9027 } 9028 } 9029 } 9030 9031 /** 9032 * Returns whether the device is currently in touch mode. Touch mode is entered 9033 * once the user begins interacting with the device by touch, and affects various 9034 * things like whether focus is always visible to the user. 9035 * 9036 * @return Whether the device is in touch mode. 9037 */ 9038 @ViewDebug.ExportedProperty 9039 public boolean isInTouchMode() { 9040 if (mAttachInfo != null) { 9041 return mAttachInfo.mInTouchMode; 9042 } else { 9043 return ViewRootImpl.isInTouchMode(); 9044 } 9045 } 9046 9047 /** 9048 * Returns the context the view is running in, through which it can 9049 * access the current theme, resources, etc. 9050 * 9051 * @return The view's Context. 9052 */ 9053 @ViewDebug.CapturedViewProperty 9054 public final Context getContext() { 9055 return mContext; 9056 } 9057 9058 /** 9059 * Handle a key event before it is processed by any input method 9060 * associated with the view hierarchy. This can be used to intercept 9061 * key events in special situations before the IME consumes them; a 9062 * typical example would be handling the BACK key to update the application's 9063 * UI instead of allowing the IME to see it and close itself. 9064 * 9065 * @param keyCode The value in event.getKeyCode(). 9066 * @param event Description of the key event. 9067 * @return If you handled the event, return true. If you want to allow the 9068 * event to be handled by the next receiver, return false. 9069 */ 9070 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 9071 return false; 9072 } 9073 9074 /** 9075 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 9076 * KeyEvent.Callback.onKeyDown()}: perform press of the view 9077 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 9078 * is released, if the view is enabled and clickable. 9079 * 9080 * <p>Key presses in software keyboards will generally NOT trigger this listener, 9081 * although some may elect to do so in some situations. Do not rely on this to 9082 * catch software key presses. 9083 * 9084 * @param keyCode A key code that represents the button pressed, from 9085 * {@link android.view.KeyEvent}. 9086 * @param event The KeyEvent object that defines the button action. 9087 */ 9088 public boolean onKeyDown(int keyCode, KeyEvent event) { 9089 boolean result = false; 9090 9091 if (KeyEvent.isConfirmKey(keyCode)) { 9092 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 9093 return true; 9094 } 9095 // Long clickable items don't necessarily have to be clickable 9096 if (((mViewFlags & CLICKABLE) == CLICKABLE || 9097 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 9098 (event.getRepeatCount() == 0)) { 9099 setPressed(true); 9100 checkForLongClick(0); 9101 return true; 9102 } 9103 } 9104 return result; 9105 } 9106 9107 /** 9108 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 9109 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 9110 * the event). 9111 * <p>Key presses in software keyboards will generally NOT trigger this listener, 9112 * although some may elect to do so in some situations. Do not rely on this to 9113 * catch software key presses. 9114 */ 9115 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 9116 return false; 9117 } 9118 9119 /** 9120 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 9121 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 9122 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 9123 * {@link KeyEvent#KEYCODE_ENTER} is released. 9124 * <p>Key presses in software keyboards will generally NOT trigger this listener, 9125 * although some may elect to do so in some situations. Do not rely on this to 9126 * catch software key presses. 9127 * 9128 * @param keyCode A key code that represents the button pressed, from 9129 * {@link android.view.KeyEvent}. 9130 * @param event The KeyEvent object that defines the button action. 9131 */ 9132 public boolean onKeyUp(int keyCode, KeyEvent event) { 9133 if (KeyEvent.isConfirmKey(keyCode)) { 9134 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 9135 return true; 9136 } 9137 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 9138 setPressed(false); 9139 9140 if (!mHasPerformedLongPress) { 9141 // This is a tap, so remove the longpress check 9142 removeLongPressCallback(); 9143 return performClick(); 9144 } 9145 } 9146 } 9147 return false; 9148 } 9149 9150 /** 9151 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 9152 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 9153 * the event). 9154 * <p>Key presses in software keyboards will generally NOT trigger this listener, 9155 * although some may elect to do so in some situations. Do not rely on this to 9156 * catch software key presses. 9157 * 9158 * @param keyCode A key code that represents the button pressed, from 9159 * {@link android.view.KeyEvent}. 9160 * @param repeatCount The number of times the action was made. 9161 * @param event The KeyEvent object that defines the button action. 9162 */ 9163 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 9164 return false; 9165 } 9166 9167 /** 9168 * Called on the focused view when a key shortcut event is not handled. 9169 * Override this method to implement local key shortcuts for the View. 9170 * Key shortcuts can also be implemented by setting the 9171 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 9172 * 9173 * @param keyCode The value in event.getKeyCode(). 9174 * @param event Description of the key event. 9175 * @return If you handled the event, return true. If you want to allow the 9176 * event to be handled by the next receiver, return false. 9177 */ 9178 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 9179 return false; 9180 } 9181 9182 /** 9183 * Check whether the called view is a text editor, in which case it 9184 * would make sense to automatically display a soft input window for 9185 * it. Subclasses should override this if they implement 9186 * {@link #onCreateInputConnection(EditorInfo)} to return true if 9187 * a call on that method would return a non-null InputConnection, and 9188 * they are really a first-class editor that the user would normally 9189 * start typing on when the go into a window containing your view. 9190 * 9191 * <p>The default implementation always returns false. This does 9192 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 9193 * will not be called or the user can not otherwise perform edits on your 9194 * view; it is just a hint to the system that this is not the primary 9195 * purpose of this view. 9196 * 9197 * @return Returns true if this view is a text editor, else false. 9198 */ 9199 public boolean onCheckIsTextEditor() { 9200 return false; 9201 } 9202 9203 /** 9204 * Create a new InputConnection for an InputMethod to interact 9205 * with the view. The default implementation returns null, since it doesn't 9206 * support input methods. You can override this to implement such support. 9207 * This is only needed for views that take focus and text input. 9208 * 9209 * <p>When implementing this, you probably also want to implement 9210 * {@link #onCheckIsTextEditor()} to indicate you will return a 9211 * non-null InputConnection.</p> 9212 * 9213 * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo} 9214 * object correctly and in its entirety, so that the connected IME can rely 9215 * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart} 9216 * and {@link android.view.inputmethod.EditorInfo#initialSelEnd} members 9217 * must be filled in with the correct cursor position for IMEs to work correctly 9218 * with your application.</p> 9219 * 9220 * @param outAttrs Fill in with attribute information about the connection. 9221 */ 9222 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 9223 return null; 9224 } 9225 9226 /** 9227 * Called by the {@link android.view.inputmethod.InputMethodManager} 9228 * when a view who is not the current 9229 * input connection target is trying to make a call on the manager. The 9230 * default implementation returns false; you can override this to return 9231 * true for certain views if you are performing InputConnection proxying 9232 * to them. 9233 * @param view The View that is making the InputMethodManager call. 9234 * @return Return true to allow the call, false to reject. 9235 */ 9236 public boolean checkInputConnectionProxy(View view) { 9237 return false; 9238 } 9239 9240 /** 9241 * Show the context menu for this view. It is not safe to hold on to the 9242 * menu after returning from this method. 9243 * 9244 * You should normally not overload this method. Overload 9245 * {@link #onCreateContextMenu(ContextMenu)} or define an 9246 * {@link OnCreateContextMenuListener} to add items to the context menu. 9247 * 9248 * @param menu The context menu to populate 9249 */ 9250 public void createContextMenu(ContextMenu menu) { 9251 ContextMenuInfo menuInfo = getContextMenuInfo(); 9252 9253 // Sets the current menu info so all items added to menu will have 9254 // my extra info set. 9255 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 9256 9257 onCreateContextMenu(menu); 9258 ListenerInfo li = mListenerInfo; 9259 if (li != null && li.mOnCreateContextMenuListener != null) { 9260 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 9261 } 9262 9263 // Clear the extra information so subsequent items that aren't mine don't 9264 // have my extra info. 9265 ((MenuBuilder)menu).setCurrentMenuInfo(null); 9266 9267 if (mParent != null) { 9268 mParent.createContextMenu(menu); 9269 } 9270 } 9271 9272 /** 9273 * Views should implement this if they have extra information to associate 9274 * with the context menu. The return result is supplied as a parameter to 9275 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 9276 * callback. 9277 * 9278 * @return Extra information about the item for which the context menu 9279 * should be shown. This information will vary across different 9280 * subclasses of View. 9281 */ 9282 protected ContextMenuInfo getContextMenuInfo() { 9283 return null; 9284 } 9285 9286 /** 9287 * Views should implement this if the view itself is going to add items to 9288 * the context menu. 9289 * 9290 * @param menu the context menu to populate 9291 */ 9292 protected void onCreateContextMenu(ContextMenu menu) { 9293 } 9294 9295 /** 9296 * Implement this method to handle trackball motion events. The 9297 * <em>relative</em> movement of the trackball since the last event 9298 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 9299 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 9300 * that a movement of 1 corresponds to the user pressing one DPAD key (so 9301 * they will often be fractional values, representing the more fine-grained 9302 * movement information available from a trackball). 9303 * 9304 * @param event The motion event. 9305 * @return True if the event was handled, false otherwise. 9306 */ 9307 public boolean onTrackballEvent(MotionEvent event) { 9308 return false; 9309 } 9310 9311 /** 9312 * Implement this method to handle generic motion events. 9313 * <p> 9314 * Generic motion events describe joystick movements, mouse hovers, track pad 9315 * touches, scroll wheel movements and other input events. The 9316 * {@link MotionEvent#getSource() source} of the motion event specifies 9317 * the class of input that was received. Implementations of this method 9318 * must examine the bits in the source before processing the event. 9319 * The following code example shows how this is done. 9320 * </p><p> 9321 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 9322 * are delivered to the view under the pointer. All other generic motion events are 9323 * delivered to the focused view. 9324 * </p> 9325 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 9326 * if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) { 9327 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 9328 * // process the joystick movement... 9329 * return true; 9330 * } 9331 * } 9332 * if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) { 9333 * switch (event.getAction()) { 9334 * case MotionEvent.ACTION_HOVER_MOVE: 9335 * // process the mouse hover movement... 9336 * return true; 9337 * case MotionEvent.ACTION_SCROLL: 9338 * // process the scroll wheel movement... 9339 * return true; 9340 * } 9341 * } 9342 * return super.onGenericMotionEvent(event); 9343 * }</pre> 9344 * 9345 * @param event The generic motion event being processed. 9346 * @return True if the event was handled, false otherwise. 9347 */ 9348 public boolean onGenericMotionEvent(MotionEvent event) { 9349 return false; 9350 } 9351 9352 /** 9353 * Implement this method to handle hover events. 9354 * <p> 9355 * This method is called whenever a pointer is hovering into, over, or out of the 9356 * bounds of a view and the view is not currently being touched. 9357 * Hover events are represented as pointer events with action 9358 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 9359 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 9360 * </p> 9361 * <ul> 9362 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 9363 * when the pointer enters the bounds of the view.</li> 9364 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 9365 * when the pointer has already entered the bounds of the view and has moved.</li> 9366 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 9367 * when the pointer has exited the bounds of the view or when the pointer is 9368 * about to go down due to a button click, tap, or similar user action that 9369 * causes the view to be touched.</li> 9370 * </ul> 9371 * <p> 9372 * The view should implement this method to return true to indicate that it is 9373 * handling the hover event, such as by changing its drawable state. 9374 * </p><p> 9375 * The default implementation calls {@link #setHovered} to update the hovered state 9376 * of the view when a hover enter or hover exit event is received, if the view 9377 * is enabled and is clickable. The default implementation also sends hover 9378 * accessibility events. 9379 * </p> 9380 * 9381 * @param event The motion event that describes the hover. 9382 * @return True if the view handled the hover event. 9383 * 9384 * @see #isHovered 9385 * @see #setHovered 9386 * @see #onHoverChanged 9387 */ 9388 public boolean onHoverEvent(MotionEvent event) { 9389 // The root view may receive hover (or touch) events that are outside the bounds of 9390 // the window. This code ensures that we only send accessibility events for 9391 // hovers that are actually within the bounds of the root view. 9392 final int action = event.getActionMasked(); 9393 if (!mSendingHoverAccessibilityEvents) { 9394 if ((action == MotionEvent.ACTION_HOVER_ENTER 9395 || action == MotionEvent.ACTION_HOVER_MOVE) 9396 && !hasHoveredChild() 9397 && pointInView(event.getX(), event.getY())) { 9398 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 9399 mSendingHoverAccessibilityEvents = true; 9400 } 9401 } else { 9402 if (action == MotionEvent.ACTION_HOVER_EXIT 9403 || (action == MotionEvent.ACTION_MOVE 9404 && !pointInView(event.getX(), event.getY()))) { 9405 mSendingHoverAccessibilityEvents = false; 9406 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 9407 } 9408 } 9409 9410 if (isHoverable()) { 9411 switch (action) { 9412 case MotionEvent.ACTION_HOVER_ENTER: 9413 setHovered(true); 9414 break; 9415 case MotionEvent.ACTION_HOVER_EXIT: 9416 setHovered(false); 9417 break; 9418 } 9419 9420 // Dispatch the event to onGenericMotionEvent before returning true. 9421 // This is to provide compatibility with existing applications that 9422 // handled HOVER_MOVE events in onGenericMotionEvent and that would 9423 // break because of the new default handling for hoverable views 9424 // in onHoverEvent. 9425 // Note that onGenericMotionEvent will be called by default when 9426 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 9427 dispatchGenericMotionEventInternal(event); 9428 // The event was already handled by calling setHovered(), so always 9429 // return true. 9430 return true; 9431 } 9432 9433 return false; 9434 } 9435 9436 /** 9437 * Returns true if the view should handle {@link #onHoverEvent} 9438 * by calling {@link #setHovered} to change its hovered state. 9439 * 9440 * @return True if the view is hoverable. 9441 */ 9442 private boolean isHoverable() { 9443 final int viewFlags = mViewFlags; 9444 if ((viewFlags & ENABLED_MASK) == DISABLED) { 9445 return false; 9446 } 9447 9448 return (viewFlags & CLICKABLE) == CLICKABLE 9449 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 9450 } 9451 9452 /** 9453 * Returns true if the view is currently hovered. 9454 * 9455 * @return True if the view is currently hovered. 9456 * 9457 * @see #setHovered 9458 * @see #onHoverChanged 9459 */ 9460 @ViewDebug.ExportedProperty 9461 public boolean isHovered() { 9462 return (mPrivateFlags & PFLAG_HOVERED) != 0; 9463 } 9464 9465 /** 9466 * Sets whether the view is currently hovered. 9467 * <p> 9468 * Calling this method also changes the drawable state of the view. This 9469 * enables the view to react to hover by using different drawable resources 9470 * to change its appearance. 9471 * </p><p> 9472 * The {@link #onHoverChanged} method is called when the hovered state changes. 9473 * </p> 9474 * 9475 * @param hovered True if the view is hovered. 9476 * 9477 * @see #isHovered 9478 * @see #onHoverChanged 9479 */ 9480 public void setHovered(boolean hovered) { 9481 if (hovered) { 9482 if ((mPrivateFlags & PFLAG_HOVERED) == 0) { 9483 mPrivateFlags |= PFLAG_HOVERED; 9484 refreshDrawableState(); 9485 onHoverChanged(true); 9486 } 9487 } else { 9488 if ((mPrivateFlags & PFLAG_HOVERED) != 0) { 9489 mPrivateFlags &= ~PFLAG_HOVERED; 9490 refreshDrawableState(); 9491 onHoverChanged(false); 9492 } 9493 } 9494 } 9495 9496 /** 9497 * Implement this method to handle hover state changes. 9498 * <p> 9499 * This method is called whenever the hover state changes as a result of a 9500 * call to {@link #setHovered}. 9501 * </p> 9502 * 9503 * @param hovered The current hover state, as returned by {@link #isHovered}. 9504 * 9505 * @see #isHovered 9506 * @see #setHovered 9507 */ 9508 public void onHoverChanged(boolean hovered) { 9509 } 9510 9511 /** 9512 * Implement this method to handle touch screen motion events. 9513 * <p> 9514 * If this method is used to detect click actions, it is recommended that 9515 * the actions be performed by implementing and calling 9516 * {@link #performClick()}. This will ensure consistent system behavior, 9517 * including: 9518 * <ul> 9519 * <li>obeying click sound preferences 9520 * <li>dispatching OnClickListener calls 9521 * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when 9522 * accessibility features are enabled 9523 * </ul> 9524 * 9525 * @param event The motion event. 9526 * @return True if the event was handled, false otherwise. 9527 */ 9528 public boolean onTouchEvent(MotionEvent event) { 9529 final float x = event.getX(); 9530 final float y = event.getY(); 9531 final int viewFlags = mViewFlags; 9532 9533 if ((viewFlags & ENABLED_MASK) == DISABLED) { 9534 if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { 9535 setPressed(false); 9536 } 9537 // A disabled view that is clickable still consumes the touch 9538 // events, it just doesn't respond to them. 9539 return (((viewFlags & CLICKABLE) == CLICKABLE || 9540 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); 9541 } 9542 9543 if (mTouchDelegate != null) { 9544 if (mTouchDelegate.onTouchEvent(event)) { 9545 return true; 9546 } 9547 } 9548 9549 if (((viewFlags & CLICKABLE) == CLICKABLE || 9550 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { 9551 switch (event.getAction()) { 9552 case MotionEvent.ACTION_UP: 9553 boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; 9554 if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { 9555 // take focus if we don't have it already and we should in 9556 // touch mode. 9557 boolean focusTaken = false; 9558 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 9559 focusTaken = requestFocus(); 9560 } 9561 9562 if (prepressed) { 9563 // The button is being released before we actually 9564 // showed it as pressed. Make it show the pressed 9565 // state now (before scheduling the click) to ensure 9566 // the user sees it. 9567 setPressed(true, x, y); 9568 } 9569 9570 if (!mHasPerformedLongPress) { 9571 // This is a tap, so remove the longpress check 9572 removeLongPressCallback(); 9573 9574 // Only perform take click actions if we were in the pressed state 9575 if (!focusTaken) { 9576 // Use a Runnable and post this rather than calling 9577 // performClick directly. This lets other visual state 9578 // of the view update before click actions start. 9579 if (mPerformClick == null) { 9580 mPerformClick = new PerformClick(); 9581 } 9582 if (!post(mPerformClick)) { 9583 performClick(); 9584 } 9585 } 9586 } 9587 9588 if (mUnsetPressedState == null) { 9589 mUnsetPressedState = new UnsetPressedState(); 9590 } 9591 9592 if (prepressed) { 9593 postDelayed(mUnsetPressedState, 9594 ViewConfiguration.getPressedStateDuration()); 9595 } else if (!post(mUnsetPressedState)) { 9596 // If the post failed, unpress right now 9597 mUnsetPressedState.run(); 9598 } 9599 9600 removeTapCallback(); 9601 } 9602 break; 9603 9604 case MotionEvent.ACTION_DOWN: 9605 mHasPerformedLongPress = false; 9606 9607 if (performButtonActionOnTouchDown(event)) { 9608 break; 9609 } 9610 9611 // Walk up the hierarchy to determine if we're inside a scrolling container. 9612 boolean isInScrollingContainer = isInScrollingContainer(); 9613 9614 // For views inside a scrolling container, delay the pressed feedback for 9615 // a short period in case this is a scroll. 9616 if (isInScrollingContainer) { 9617 mPrivateFlags |= PFLAG_PREPRESSED; 9618 if (mPendingCheckForTap == null) { 9619 mPendingCheckForTap = new CheckForTap(); 9620 } 9621 mPendingCheckForTap.x = event.getX(); 9622 mPendingCheckForTap.y = event.getY(); 9623 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 9624 } else { 9625 // Not inside a scrolling container, so show the feedback right away 9626 setPressed(true, x, y); 9627 checkForLongClick(0); 9628 } 9629 break; 9630 9631 case MotionEvent.ACTION_CANCEL: 9632 setPressed(false); 9633 removeTapCallback(); 9634 removeLongPressCallback(); 9635 break; 9636 9637 case MotionEvent.ACTION_MOVE: 9638 drawableHotspotChanged(x, y); 9639 9640 // Be lenient about moving outside of buttons 9641 if (!pointInView(x, y, mTouchSlop)) { 9642 // Outside button 9643 removeTapCallback(); 9644 if ((mPrivateFlags & PFLAG_PRESSED) != 0) { 9645 // Remove any future long press/tap checks 9646 removeLongPressCallback(); 9647 9648 setPressed(false); 9649 } 9650 } 9651 break; 9652 } 9653 9654 return true; 9655 } 9656 9657 return false; 9658 } 9659 9660 /** 9661 * @hide 9662 */ 9663 public boolean isInScrollingContainer() { 9664 ViewParent p = getParent(); 9665 while (p != null && p instanceof ViewGroup) { 9666 if (((ViewGroup) p).shouldDelayChildPressedState()) { 9667 return true; 9668 } 9669 p = p.getParent(); 9670 } 9671 return false; 9672 } 9673 9674 /** 9675 * Remove the longpress detection timer. 9676 */ 9677 private void removeLongPressCallback() { 9678 if (mPendingCheckForLongPress != null) { 9679 removeCallbacks(mPendingCheckForLongPress); 9680 } 9681 } 9682 9683 /** 9684 * Remove the pending click action 9685 */ 9686 private void removePerformClickCallback() { 9687 if (mPerformClick != null) { 9688 removeCallbacks(mPerformClick); 9689 } 9690 } 9691 9692 /** 9693 * Remove the prepress detection timer. 9694 */ 9695 private void removeUnsetPressCallback() { 9696 if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) { 9697 setPressed(false); 9698 removeCallbacks(mUnsetPressedState); 9699 } 9700 } 9701 9702 /** 9703 * Remove the tap detection timer. 9704 */ 9705 private void removeTapCallback() { 9706 if (mPendingCheckForTap != null) { 9707 mPrivateFlags &= ~PFLAG_PREPRESSED; 9708 removeCallbacks(mPendingCheckForTap); 9709 } 9710 } 9711 9712 /** 9713 * Cancels a pending long press. Your subclass can use this if you 9714 * want the context menu to come up if the user presses and holds 9715 * at the same place, but you don't want it to come up if they press 9716 * and then move around enough to cause scrolling. 9717 */ 9718 public void cancelLongPress() { 9719 removeLongPressCallback(); 9720 9721 /* 9722 * The prepressed state handled by the tap callback is a display 9723 * construct, but the tap callback will post a long press callback 9724 * less its own timeout. Remove it here. 9725 */ 9726 removeTapCallback(); 9727 } 9728 9729 /** 9730 * Remove the pending callback for sending a 9731 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 9732 */ 9733 private void removeSendViewScrolledAccessibilityEventCallback() { 9734 if (mSendViewScrolledAccessibilityEvent != null) { 9735 removeCallbacks(mSendViewScrolledAccessibilityEvent); 9736 mSendViewScrolledAccessibilityEvent.mIsPending = false; 9737 } 9738 } 9739 9740 /** 9741 * Sets the TouchDelegate for this View. 9742 */ 9743 public void setTouchDelegate(TouchDelegate delegate) { 9744 mTouchDelegate = delegate; 9745 } 9746 9747 /** 9748 * Gets the TouchDelegate for this View. 9749 */ 9750 public TouchDelegate getTouchDelegate() { 9751 return mTouchDelegate; 9752 } 9753 9754 /** 9755 * Request unbuffered dispatch of the given stream of MotionEvents to this View. 9756 * 9757 * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input 9758 * system not batch {@link MotionEvent}s but instead deliver them as soon as they're 9759 * available. This method should only be called for touch events. 9760 * 9761 * <p class="note">This api is not intended for most applications. Buffered dispatch 9762 * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent 9763 * streams will not improve your input latency. Side effects include: increased latency, 9764 * jittery scrolls and inability to take advantage of system resampling. Talk to your input 9765 * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for 9766 * you.</p> 9767 */ 9768 public final void requestUnbufferedDispatch(MotionEvent event) { 9769 final int action = event.getAction(); 9770 if (mAttachInfo == null 9771 || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE 9772 || !event.isTouchEvent()) { 9773 return; 9774 } 9775 mAttachInfo.mUnbufferedDispatchRequested = true; 9776 } 9777 9778 /** 9779 * Set flags controlling behavior of this view. 9780 * 9781 * @param flags Constant indicating the value which should be set 9782 * @param mask Constant indicating the bit range that should be changed 9783 */ 9784 void setFlags(int flags, int mask) { 9785 final boolean accessibilityEnabled = 9786 AccessibilityManager.getInstance(mContext).isEnabled(); 9787 final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility(); 9788 9789 int old = mViewFlags; 9790 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 9791 9792 int changed = mViewFlags ^ old; 9793 if (changed == 0) { 9794 return; 9795 } 9796 int privateFlags = mPrivateFlags; 9797 9798 /* Check if the FOCUSABLE bit has changed */ 9799 if (((changed & FOCUSABLE_MASK) != 0) && 9800 ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) { 9801 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 9802 && ((privateFlags & PFLAG_FOCUSED) != 0)) { 9803 /* Give up focus if we are no longer focusable */ 9804 clearFocus(); 9805 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 9806 && ((privateFlags & PFLAG_FOCUSED) == 0)) { 9807 /* 9808 * Tell the view system that we are now available to take focus 9809 * if no one else already has it. 9810 */ 9811 if (mParent != null) mParent.focusableViewAvailable(this); 9812 } 9813 } 9814 9815 final int newVisibility = flags & VISIBILITY_MASK; 9816 if (newVisibility == VISIBLE) { 9817 if ((changed & VISIBILITY_MASK) != 0) { 9818 /* 9819 * If this view is becoming visible, invalidate it in case it changed while 9820 * it was not visible. Marking it drawn ensures that the invalidation will 9821 * go through. 9822 */ 9823 mPrivateFlags |= PFLAG_DRAWN; 9824 invalidate(true); 9825 9826 needGlobalAttributesUpdate(true); 9827 9828 // a view becoming visible is worth notifying the parent 9829 // about in case nothing has focus. even if this specific view 9830 // isn't focusable, it may contain something that is, so let 9831 // the root view try to give this focus if nothing else does. 9832 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 9833 mParent.focusableViewAvailable(this); 9834 } 9835 } 9836 } 9837 9838 /* Check if the GONE bit has changed */ 9839 if ((changed & GONE) != 0) { 9840 needGlobalAttributesUpdate(false); 9841 requestLayout(); 9842 9843 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 9844 if (hasFocus()) clearFocus(); 9845 clearAccessibilityFocus(); 9846 destroyDrawingCache(); 9847 if (mParent instanceof View) { 9848 // GONE views noop invalidation, so invalidate the parent 9849 ((View) mParent).invalidate(true); 9850 } 9851 // Mark the view drawn to ensure that it gets invalidated properly the next 9852 // time it is visible and gets invalidated 9853 mPrivateFlags |= PFLAG_DRAWN; 9854 } 9855 if (mAttachInfo != null) { 9856 mAttachInfo.mViewVisibilityChanged = true; 9857 } 9858 } 9859 9860 /* Check if the VISIBLE bit has changed */ 9861 if ((changed & INVISIBLE) != 0) { 9862 needGlobalAttributesUpdate(false); 9863 /* 9864 * If this view is becoming invisible, set the DRAWN flag so that 9865 * the next invalidate() will not be skipped. 9866 */ 9867 mPrivateFlags |= PFLAG_DRAWN; 9868 9869 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) { 9870 // root view becoming invisible shouldn't clear focus and accessibility focus 9871 if (getRootView() != this) { 9872 if (hasFocus()) clearFocus(); 9873 clearAccessibilityFocus(); 9874 } 9875 } 9876 if (mAttachInfo != null) { 9877 mAttachInfo.mViewVisibilityChanged = true; 9878 } 9879 } 9880 9881 if ((changed & VISIBILITY_MASK) != 0) { 9882 // If the view is invisible, cleanup its display list to free up resources 9883 if (newVisibility != VISIBLE && mAttachInfo != null) { 9884 cleanupDraw(); 9885 } 9886 9887 if (mParent instanceof ViewGroup) { 9888 ((ViewGroup) mParent).onChildVisibilityChanged(this, 9889 (changed & VISIBILITY_MASK), newVisibility); 9890 ((View) mParent).invalidate(true); 9891 } else if (mParent != null) { 9892 mParent.invalidateChild(this, null); 9893 } 9894 dispatchVisibilityChanged(this, newVisibility); 9895 9896 notifySubtreeAccessibilityStateChangedIfNeeded(); 9897 } 9898 9899 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 9900 destroyDrawingCache(); 9901 } 9902 9903 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 9904 destroyDrawingCache(); 9905 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 9906 invalidateParentCaches(); 9907 } 9908 9909 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 9910 destroyDrawingCache(); 9911 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 9912 } 9913 9914 if ((changed & DRAW_MASK) != 0) { 9915 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 9916 if (mBackground != null) { 9917 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 9918 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 9919 } else { 9920 mPrivateFlags |= PFLAG_SKIP_DRAW; 9921 } 9922 } else { 9923 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 9924 } 9925 requestLayout(); 9926 invalidate(true); 9927 } 9928 9929 if ((changed & KEEP_SCREEN_ON) != 0) { 9930 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 9931 mParent.recomputeViewAttributes(this); 9932 } 9933 } 9934 9935 if (accessibilityEnabled) { 9936 if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0 9937 || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) { 9938 if (oldIncludeForAccessibility != includeForAccessibility()) { 9939 notifySubtreeAccessibilityStateChangedIfNeeded(); 9940 } else { 9941 notifyViewAccessibilityStateChangedIfNeeded( 9942 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9943 } 9944 } else if ((changed & ENABLED_MASK) != 0) { 9945 notifyViewAccessibilityStateChangedIfNeeded( 9946 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9947 } 9948 } 9949 } 9950 9951 /** 9952 * Change the view's z order in the tree, so it's on top of other sibling 9953 * views. This ordering change may affect layout, if the parent container 9954 * uses an order-dependent layout scheme (e.g., LinearLayout). Prior 9955 * to {@link android.os.Build.VERSION_CODES#KITKAT} this 9956 * method should be followed by calls to {@link #requestLayout()} and 9957 * {@link View#invalidate()} on the view's parent to force the parent to redraw 9958 * with the new child ordering. 9959 * 9960 * @see ViewGroup#bringChildToFront(View) 9961 */ 9962 public void bringToFront() { 9963 if (mParent != null) { 9964 mParent.bringChildToFront(this); 9965 } 9966 } 9967 9968 /** 9969 * This is called in response to an internal scroll in this view (i.e., the 9970 * view scrolled its own contents). This is typically as a result of 9971 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 9972 * called. 9973 * 9974 * @param l Current horizontal scroll origin. 9975 * @param t Current vertical scroll origin. 9976 * @param oldl Previous horizontal scroll origin. 9977 * @param oldt Previous vertical scroll origin. 9978 */ 9979 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 9980 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 9981 postSendViewScrolledAccessibilityEventCallback(); 9982 } 9983 9984 mBackgroundSizeChanged = true; 9985 9986 final AttachInfo ai = mAttachInfo; 9987 if (ai != null) { 9988 ai.mViewScrollChanged = true; 9989 } 9990 9991 if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) { 9992 mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt); 9993 } 9994 } 9995 9996 /** 9997 * Interface definition for a callback to be invoked when the scroll 9998 * position of a view changes. 9999 * 10000 * @hide Only used internally. 10001 */ 10002 public interface OnScrollChangeListener { 10003 /** 10004 * Called when the scroll position of a view changes. 10005 * 10006 * @param v The view whose scroll position has changed. 10007 * @param scrollX Current horizontal scroll origin. 10008 * @param scrollY Current vertical scroll origin. 10009 * @param oldScrollX Previous horizontal scroll origin. 10010 * @param oldScrollY Previous vertical scroll origin. 10011 */ 10012 void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY); 10013 } 10014 10015 /** 10016 * Interface definition for a callback to be invoked when the layout bounds of a view 10017 * changes due to layout processing. 10018 */ 10019 public interface OnLayoutChangeListener { 10020 /** 10021 * Called when the layout bounds of a view changes due to layout processing. 10022 * 10023 * @param v The view whose bounds have changed. 10024 * @param left The new value of the view's left property. 10025 * @param top The new value of the view's top property. 10026 * @param right The new value of the view's right property. 10027 * @param bottom The new value of the view's bottom property. 10028 * @param oldLeft The previous value of the view's left property. 10029 * @param oldTop The previous value of the view's top property. 10030 * @param oldRight The previous value of the view's right property. 10031 * @param oldBottom The previous value of the view's bottom property. 10032 */ 10033 void onLayoutChange(View v, int left, int top, int right, int bottom, 10034 int oldLeft, int oldTop, int oldRight, int oldBottom); 10035 } 10036 10037 /** 10038 * This is called during layout when the size of this view has changed. If 10039 * you were just added to the view hierarchy, you're called with the old 10040 * values of 0. 10041 * 10042 * @param w Current width of this view. 10043 * @param h Current height of this view. 10044 * @param oldw Old width of this view. 10045 * @param oldh Old height of this view. 10046 */ 10047 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 10048 } 10049 10050 /** 10051 * Called by draw to draw the child views. This may be overridden 10052 * by derived classes to gain control just before its children are drawn 10053 * (but after its own view has been drawn). 10054 * @param canvas the canvas on which to draw the view 10055 */ 10056 protected void dispatchDraw(Canvas canvas) { 10057 10058 } 10059 10060 /** 10061 * Gets the parent of this view. Note that the parent is a 10062 * ViewParent and not necessarily a View. 10063 * 10064 * @return Parent of this view. 10065 */ 10066 public final ViewParent getParent() { 10067 return mParent; 10068 } 10069 10070 /** 10071 * Set the horizontal scrolled position of your view. This will cause a call to 10072 * {@link #onScrollChanged(int, int, int, int)} and the view will be 10073 * invalidated. 10074 * @param value the x position to scroll to 10075 */ 10076 public void setScrollX(int value) { 10077 scrollTo(value, mScrollY); 10078 } 10079 10080 /** 10081 * Set the vertical scrolled position of your view. This will cause a call to 10082 * {@link #onScrollChanged(int, int, int, int)} and the view will be 10083 * invalidated. 10084 * @param value the y position to scroll to 10085 */ 10086 public void setScrollY(int value) { 10087 scrollTo(mScrollX, value); 10088 } 10089 10090 /** 10091 * Return the scrolled left position of this view. This is the left edge of 10092 * the displayed part of your view. You do not need to draw any pixels 10093 * farther left, since those are outside of the frame of your view on 10094 * screen. 10095 * 10096 * @return The left edge of the displayed part of your view, in pixels. 10097 */ 10098 public final int getScrollX() { 10099 return mScrollX; 10100 } 10101 10102 /** 10103 * Return the scrolled top position of this view. This is the top edge of 10104 * the displayed part of your view. You do not need to draw any pixels above 10105 * it, since those are outside of the frame of your view on screen. 10106 * 10107 * @return The top edge of the displayed part of your view, in pixels. 10108 */ 10109 public final int getScrollY() { 10110 return mScrollY; 10111 } 10112 10113 /** 10114 * Return the width of the your view. 10115 * 10116 * @return The width of your view, in pixels. 10117 */ 10118 @ViewDebug.ExportedProperty(category = "layout") 10119 public final int getWidth() { 10120 return mRight - mLeft; 10121 } 10122 10123 /** 10124 * Return the height of your view. 10125 * 10126 * @return The height of your view, in pixels. 10127 */ 10128 @ViewDebug.ExportedProperty(category = "layout") 10129 public final int getHeight() { 10130 return mBottom - mTop; 10131 } 10132 10133 /** 10134 * Return the visible drawing bounds of your view. Fills in the output 10135 * rectangle with the values from getScrollX(), getScrollY(), 10136 * getWidth(), and getHeight(). These bounds do not account for any 10137 * transformation properties currently set on the view, such as 10138 * {@link #setScaleX(float)} or {@link #setRotation(float)}. 10139 * 10140 * @param outRect The (scrolled) drawing bounds of the view. 10141 */ 10142 public void getDrawingRect(Rect outRect) { 10143 outRect.left = mScrollX; 10144 outRect.top = mScrollY; 10145 outRect.right = mScrollX + (mRight - mLeft); 10146 outRect.bottom = mScrollY + (mBottom - mTop); 10147 } 10148 10149 /** 10150 * Like {@link #getMeasuredWidthAndState()}, but only returns the 10151 * raw width component (that is the result is masked by 10152 * {@link #MEASURED_SIZE_MASK}). 10153 * 10154 * @return The raw measured width of this view. 10155 */ 10156 public final int getMeasuredWidth() { 10157 return mMeasuredWidth & MEASURED_SIZE_MASK; 10158 } 10159 10160 /** 10161 * Return the full width measurement information for this view as computed 10162 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 10163 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 10164 * This should be used during measurement and layout calculations only. Use 10165 * {@link #getWidth()} to see how wide a view is after layout. 10166 * 10167 * @return The measured width of this view as a bit mask. 10168 */ 10169 public final int getMeasuredWidthAndState() { 10170 return mMeasuredWidth; 10171 } 10172 10173 /** 10174 * Like {@link #getMeasuredHeightAndState()}, but only returns the 10175 * raw width component (that is the result is masked by 10176 * {@link #MEASURED_SIZE_MASK}). 10177 * 10178 * @return The raw measured height of this view. 10179 */ 10180 public final int getMeasuredHeight() { 10181 return mMeasuredHeight & MEASURED_SIZE_MASK; 10182 } 10183 10184 /** 10185 * Return the full height measurement information for this view as computed 10186 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 10187 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 10188 * This should be used during measurement and layout calculations only. Use 10189 * {@link #getHeight()} to see how wide a view is after layout. 10190 * 10191 * @return The measured width of this view as a bit mask. 10192 */ 10193 public final int getMeasuredHeightAndState() { 10194 return mMeasuredHeight; 10195 } 10196 10197 /** 10198 * Return only the state bits of {@link #getMeasuredWidthAndState()} 10199 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 10200 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 10201 * and the height component is at the shifted bits 10202 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 10203 */ 10204 public final int getMeasuredState() { 10205 return (mMeasuredWidth&MEASURED_STATE_MASK) 10206 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 10207 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 10208 } 10209 10210 /** 10211 * The transform matrix of this view, which is calculated based on the current 10212 * rotation, scale, and pivot properties. 10213 * 10214 * @see #getRotation() 10215 * @see #getScaleX() 10216 * @see #getScaleY() 10217 * @see #getPivotX() 10218 * @see #getPivotY() 10219 * @return The current transform matrix for the view 10220 */ 10221 public Matrix getMatrix() { 10222 ensureTransformationInfo(); 10223 final Matrix matrix = mTransformationInfo.mMatrix; 10224 mRenderNode.getMatrix(matrix); 10225 return matrix; 10226 } 10227 10228 /** 10229 * Returns true if the transform matrix is the identity matrix. 10230 * Recomputes the matrix if necessary. 10231 * 10232 * @return True if the transform matrix is the identity matrix, false otherwise. 10233 */ 10234 final boolean hasIdentityMatrix() { 10235 return mRenderNode.hasIdentityMatrix(); 10236 } 10237 10238 void ensureTransformationInfo() { 10239 if (mTransformationInfo == null) { 10240 mTransformationInfo = new TransformationInfo(); 10241 } 10242 } 10243 10244 /** 10245 * Utility method to retrieve the inverse of the current mMatrix property. 10246 * We cache the matrix to avoid recalculating it when transform properties 10247 * have not changed. 10248 * 10249 * @return The inverse of the current matrix of this view. 10250 * @hide 10251 */ 10252 public final Matrix getInverseMatrix() { 10253 ensureTransformationInfo(); 10254 if (mTransformationInfo.mInverseMatrix == null) { 10255 mTransformationInfo.mInverseMatrix = new Matrix(); 10256 } 10257 final Matrix matrix = mTransformationInfo.mInverseMatrix; 10258 mRenderNode.getInverseMatrix(matrix); 10259 return matrix; 10260 } 10261 10262 /** 10263 * Gets the distance along the Z axis from the camera to this view. 10264 * 10265 * @see #setCameraDistance(float) 10266 * 10267 * @return The distance along the Z axis. 10268 */ 10269 public float getCameraDistance() { 10270 final float dpi = mResources.getDisplayMetrics().densityDpi; 10271 return -(mRenderNode.getCameraDistance() * dpi); 10272 } 10273 10274 /** 10275 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 10276 * views are drawn) from the camera to this view. The camera's distance 10277 * affects 3D transformations, for instance rotations around the X and Y 10278 * axis. If the rotationX or rotationY properties are changed and this view is 10279 * large (more than half the size of the screen), it is recommended to always 10280 * use a camera distance that's greater than the height (X axis rotation) or 10281 * the width (Y axis rotation) of this view.</p> 10282 * 10283 * <p>The distance of the camera from the view plane can have an affect on the 10284 * perspective distortion of the view when it is rotated around the x or y axis. 10285 * For example, a large distance will result in a large viewing angle, and there 10286 * will not be much perspective distortion of the view as it rotates. A short 10287 * distance may cause much more perspective distortion upon rotation, and can 10288 * also result in some drawing artifacts if the rotated view ends up partially 10289 * behind the camera (which is why the recommendation is to use a distance at 10290 * least as far as the size of the view, if the view is to be rotated.)</p> 10291 * 10292 * <p>The distance is expressed in "depth pixels." The default distance depends 10293 * on the screen density. For instance, on a medium density display, the 10294 * default distance is 1280. On a high density display, the default distance 10295 * is 1920.</p> 10296 * 10297 * <p>If you want to specify a distance that leads to visually consistent 10298 * results across various densities, use the following formula:</p> 10299 * <pre> 10300 * float scale = context.getResources().getDisplayMetrics().density; 10301 * view.setCameraDistance(distance * scale); 10302 * </pre> 10303 * 10304 * <p>The density scale factor of a high density display is 1.5, 10305 * and 1920 = 1280 * 1.5.</p> 10306 * 10307 * @param distance The distance in "depth pixels", if negative the opposite 10308 * value is used 10309 * 10310 * @see #setRotationX(float) 10311 * @see #setRotationY(float) 10312 */ 10313 public void setCameraDistance(float distance) { 10314 final float dpi = mResources.getDisplayMetrics().densityDpi; 10315 10316 invalidateViewProperty(true, false); 10317 mRenderNode.setCameraDistance(-Math.abs(distance) / dpi); 10318 invalidateViewProperty(false, false); 10319 10320 invalidateParentIfNeededAndWasQuickRejected(); 10321 } 10322 10323 /** 10324 * The degrees that the view is rotated around the pivot point. 10325 * 10326 * @see #setRotation(float) 10327 * @see #getPivotX() 10328 * @see #getPivotY() 10329 * 10330 * @return The degrees of rotation. 10331 */ 10332 @ViewDebug.ExportedProperty(category = "drawing") 10333 public float getRotation() { 10334 return mRenderNode.getRotation(); 10335 } 10336 10337 /** 10338 * Sets the degrees that the view is rotated around the pivot point. Increasing values 10339 * result in clockwise rotation. 10340 * 10341 * @param rotation The degrees of rotation. 10342 * 10343 * @see #getRotation() 10344 * @see #getPivotX() 10345 * @see #getPivotY() 10346 * @see #setRotationX(float) 10347 * @see #setRotationY(float) 10348 * 10349 * @attr ref android.R.styleable#View_rotation 10350 */ 10351 public void setRotation(float rotation) { 10352 if (rotation != getRotation()) { 10353 // Double-invalidation is necessary to capture view's old and new areas 10354 invalidateViewProperty(true, false); 10355 mRenderNode.setRotation(rotation); 10356 invalidateViewProperty(false, true); 10357 10358 invalidateParentIfNeededAndWasQuickRejected(); 10359 notifySubtreeAccessibilityStateChangedIfNeeded(); 10360 } 10361 } 10362 10363 /** 10364 * The degrees that the view is rotated around the vertical axis through the pivot point. 10365 * 10366 * @see #getPivotX() 10367 * @see #getPivotY() 10368 * @see #setRotationY(float) 10369 * 10370 * @return The degrees of Y rotation. 10371 */ 10372 @ViewDebug.ExportedProperty(category = "drawing") 10373 public float getRotationY() { 10374 return mRenderNode.getRotationY(); 10375 } 10376 10377 /** 10378 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 10379 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 10380 * down the y axis. 10381 * 10382 * When rotating large views, it is recommended to adjust the camera distance 10383 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 10384 * 10385 * @param rotationY The degrees of Y rotation. 10386 * 10387 * @see #getRotationY() 10388 * @see #getPivotX() 10389 * @see #getPivotY() 10390 * @see #setRotation(float) 10391 * @see #setRotationX(float) 10392 * @see #setCameraDistance(float) 10393 * 10394 * @attr ref android.R.styleable#View_rotationY 10395 */ 10396 public void setRotationY(float rotationY) { 10397 if (rotationY != getRotationY()) { 10398 invalidateViewProperty(true, false); 10399 mRenderNode.setRotationY(rotationY); 10400 invalidateViewProperty(false, true); 10401 10402 invalidateParentIfNeededAndWasQuickRejected(); 10403 notifySubtreeAccessibilityStateChangedIfNeeded(); 10404 } 10405 } 10406 10407 /** 10408 * The degrees that the view is rotated around the horizontal axis through the pivot point. 10409 * 10410 * @see #getPivotX() 10411 * @see #getPivotY() 10412 * @see #setRotationX(float) 10413 * 10414 * @return The degrees of X rotation. 10415 */ 10416 @ViewDebug.ExportedProperty(category = "drawing") 10417 public float getRotationX() { 10418 return mRenderNode.getRotationX(); 10419 } 10420 10421 /** 10422 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 10423 * Increasing values result in clockwise rotation from the viewpoint of looking down the 10424 * x axis. 10425 * 10426 * When rotating large views, it is recommended to adjust the camera distance 10427 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 10428 * 10429 * @param rotationX The degrees of X rotation. 10430 * 10431 * @see #getRotationX() 10432 * @see #getPivotX() 10433 * @see #getPivotY() 10434 * @see #setRotation(float) 10435 * @see #setRotationY(float) 10436 * @see #setCameraDistance(float) 10437 * 10438 * @attr ref android.R.styleable#View_rotationX 10439 */ 10440 public void setRotationX(float rotationX) { 10441 if (rotationX != getRotationX()) { 10442 invalidateViewProperty(true, false); 10443 mRenderNode.setRotationX(rotationX); 10444 invalidateViewProperty(false, true); 10445 10446 invalidateParentIfNeededAndWasQuickRejected(); 10447 notifySubtreeAccessibilityStateChangedIfNeeded(); 10448 } 10449 } 10450 10451 /** 10452 * The amount that the view is scaled in x around the pivot point, as a proportion of 10453 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 10454 * 10455 * <p>By default, this is 1.0f. 10456 * 10457 * @see #getPivotX() 10458 * @see #getPivotY() 10459 * @return The scaling factor. 10460 */ 10461 @ViewDebug.ExportedProperty(category = "drawing") 10462 public float getScaleX() { 10463 return mRenderNode.getScaleX(); 10464 } 10465 10466 /** 10467 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 10468 * the view's unscaled width. A value of 1 means that no scaling is applied. 10469 * 10470 * @param scaleX The scaling factor. 10471 * @see #getPivotX() 10472 * @see #getPivotY() 10473 * 10474 * @attr ref android.R.styleable#View_scaleX 10475 */ 10476 public void setScaleX(float scaleX) { 10477 if (scaleX != getScaleX()) { 10478 invalidateViewProperty(true, false); 10479 mRenderNode.setScaleX(scaleX); 10480 invalidateViewProperty(false, true); 10481 10482 invalidateParentIfNeededAndWasQuickRejected(); 10483 notifySubtreeAccessibilityStateChangedIfNeeded(); 10484 } 10485 } 10486 10487 /** 10488 * The amount that the view is scaled in y around the pivot point, as a proportion of 10489 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 10490 * 10491 * <p>By default, this is 1.0f. 10492 * 10493 * @see #getPivotX() 10494 * @see #getPivotY() 10495 * @return The scaling factor. 10496 */ 10497 @ViewDebug.ExportedProperty(category = "drawing") 10498 public float getScaleY() { 10499 return mRenderNode.getScaleY(); 10500 } 10501 10502 /** 10503 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 10504 * the view's unscaled width. A value of 1 means that no scaling is applied. 10505 * 10506 * @param scaleY The scaling factor. 10507 * @see #getPivotX() 10508 * @see #getPivotY() 10509 * 10510 * @attr ref android.R.styleable#View_scaleY 10511 */ 10512 public void setScaleY(float scaleY) { 10513 if (scaleY != getScaleY()) { 10514 invalidateViewProperty(true, false); 10515 mRenderNode.setScaleY(scaleY); 10516 invalidateViewProperty(false, true); 10517 10518 invalidateParentIfNeededAndWasQuickRejected(); 10519 notifySubtreeAccessibilityStateChangedIfNeeded(); 10520 } 10521 } 10522 10523 /** 10524 * The x location of the point around which the view is {@link #setRotation(float) rotated} 10525 * and {@link #setScaleX(float) scaled}. 10526 * 10527 * @see #getRotation() 10528 * @see #getScaleX() 10529 * @see #getScaleY() 10530 * @see #getPivotY() 10531 * @return The x location of the pivot point. 10532 * 10533 * @attr ref android.R.styleable#View_transformPivotX 10534 */ 10535 @ViewDebug.ExportedProperty(category = "drawing") 10536 public float getPivotX() { 10537 return mRenderNode.getPivotX(); 10538 } 10539 10540 /** 10541 * Sets the x location of the point around which the view is 10542 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 10543 * By default, the pivot point is centered on the object. 10544 * Setting this property disables this behavior and causes the view to use only the 10545 * explicitly set pivotX and pivotY values. 10546 * 10547 * @param pivotX The x location of the pivot point. 10548 * @see #getRotation() 10549 * @see #getScaleX() 10550 * @see #getScaleY() 10551 * @see #getPivotY() 10552 * 10553 * @attr ref android.R.styleable#View_transformPivotX 10554 */ 10555 public void setPivotX(float pivotX) { 10556 if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) { 10557 invalidateViewProperty(true, false); 10558 mRenderNode.setPivotX(pivotX); 10559 invalidateViewProperty(false, true); 10560 10561 invalidateParentIfNeededAndWasQuickRejected(); 10562 } 10563 } 10564 10565 /** 10566 * The y location of the point around which the view is {@link #setRotation(float) rotated} 10567 * and {@link #setScaleY(float) scaled}. 10568 * 10569 * @see #getRotation() 10570 * @see #getScaleX() 10571 * @see #getScaleY() 10572 * @see #getPivotY() 10573 * @return The y location of the pivot point. 10574 * 10575 * @attr ref android.R.styleable#View_transformPivotY 10576 */ 10577 @ViewDebug.ExportedProperty(category = "drawing") 10578 public float getPivotY() { 10579 return mRenderNode.getPivotY(); 10580 } 10581 10582 /** 10583 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 10584 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 10585 * Setting this property disables this behavior and causes the view to use only the 10586 * explicitly set pivotX and pivotY values. 10587 * 10588 * @param pivotY The y location of the pivot point. 10589 * @see #getRotation() 10590 * @see #getScaleX() 10591 * @see #getScaleY() 10592 * @see #getPivotY() 10593 * 10594 * @attr ref android.R.styleable#View_transformPivotY 10595 */ 10596 public void setPivotY(float pivotY) { 10597 if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) { 10598 invalidateViewProperty(true, false); 10599 mRenderNode.setPivotY(pivotY); 10600 invalidateViewProperty(false, true); 10601 10602 invalidateParentIfNeededAndWasQuickRejected(); 10603 } 10604 } 10605 10606 /** 10607 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 10608 * completely transparent and 1 means the view is completely opaque. 10609 * 10610 * <p>By default this is 1.0f. 10611 * @return The opacity of the view. 10612 */ 10613 @ViewDebug.ExportedProperty(category = "drawing") 10614 public float getAlpha() { 10615 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 10616 } 10617 10618 /** 10619 * Returns whether this View has content which overlaps. 10620 * 10621 * <p>This function, intended to be overridden by specific View types, is an optimization when 10622 * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to 10623 * an offscreen buffer and then composited into place, which can be expensive. If the view has 10624 * no overlapping rendering, the view can draw each primitive with the appropriate alpha value 10625 * directly. An example of overlapping rendering is a TextView with a background image, such as 10626 * a Button. An example of non-overlapping rendering is a TextView with no background, or an 10627 * ImageView with only the foreground image. The default implementation returns true; subclasses 10628 * should override if they have cases which can be optimized.</p> 10629 * 10630 * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas} 10631 * necessitates that a View return true if it uses the methods internally without passing the 10632 * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p> 10633 * 10634 * @return true if the content in this view might overlap, false otherwise. 10635 */ 10636 @ViewDebug.ExportedProperty(category = "drawing") 10637 public boolean hasOverlappingRendering() { 10638 return true; 10639 } 10640 10641 /** 10642 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is 10643 * completely transparent and 1 means the view is completely opaque.</p> 10644 * 10645 * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant 10646 * performance implications, especially for large views. It is best to use the alpha property 10647 * sparingly and transiently, as in the case of fading animations.</p> 10648 * 10649 * <p>For a view with a frequently changing alpha, such as during a fading animation, it is 10650 * strongly recommended for performance reasons to either override 10651 * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a 10652 * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p> 10653 * 10654 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 10655 * responsible for applying the opacity itself.</p> 10656 * 10657 * <p>Note that if the view is backed by a 10658 * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a 10659 * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than 10660 * 1.0 will supercede the alpha of the layer paint.</p> 10661 * 10662 * @param alpha The opacity of the view. 10663 * 10664 * @see #hasOverlappingRendering() 10665 * @see #setLayerType(int, android.graphics.Paint) 10666 * 10667 * @attr ref android.R.styleable#View_alpha 10668 */ 10669 public void setAlpha(float alpha) { 10670 ensureTransformationInfo(); 10671 if (mTransformationInfo.mAlpha != alpha) { 10672 mTransformationInfo.mAlpha = alpha; 10673 if (onSetAlpha((int) (alpha * 255))) { 10674 mPrivateFlags |= PFLAG_ALPHA_SET; 10675 // subclass is handling alpha - don't optimize rendering cache invalidation 10676 invalidateParentCaches(); 10677 invalidate(true); 10678 } else { 10679 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10680 invalidateViewProperty(true, false); 10681 mRenderNode.setAlpha(getFinalAlpha()); 10682 notifyViewAccessibilityStateChangedIfNeeded( 10683 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 10684 } 10685 } 10686 } 10687 10688 /** 10689 * Faster version of setAlpha() which performs the same steps except there are 10690 * no calls to invalidate(). The caller of this function should perform proper invalidation 10691 * on the parent and this object. The return value indicates whether the subclass handles 10692 * alpha (the return value for onSetAlpha()). 10693 * 10694 * @param alpha The new value for the alpha property 10695 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 10696 * the new value for the alpha property is different from the old value 10697 */ 10698 boolean setAlphaNoInvalidation(float alpha) { 10699 ensureTransformationInfo(); 10700 if (mTransformationInfo.mAlpha != alpha) { 10701 mTransformationInfo.mAlpha = alpha; 10702 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 10703 if (subclassHandlesAlpha) { 10704 mPrivateFlags |= PFLAG_ALPHA_SET; 10705 return true; 10706 } else { 10707 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10708 mRenderNode.setAlpha(getFinalAlpha()); 10709 } 10710 } 10711 return false; 10712 } 10713 10714 /** 10715 * This property is hidden and intended only for use by the Fade transition, which 10716 * animates it to produce a visual translucency that does not side-effect (or get 10717 * affected by) the real alpha property. This value is composited with the other 10718 * alpha value (and the AlphaAnimation value, when that is present) to produce 10719 * a final visual translucency result, which is what is passed into the DisplayList. 10720 * 10721 * @hide 10722 */ 10723 public void setTransitionAlpha(float alpha) { 10724 ensureTransformationInfo(); 10725 if (mTransformationInfo.mTransitionAlpha != alpha) { 10726 mTransformationInfo.mTransitionAlpha = alpha; 10727 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10728 invalidateViewProperty(true, false); 10729 mRenderNode.setAlpha(getFinalAlpha()); 10730 } 10731 } 10732 10733 /** 10734 * Calculates the visual alpha of this view, which is a combination of the actual 10735 * alpha value and the transitionAlpha value (if set). 10736 */ 10737 private float getFinalAlpha() { 10738 if (mTransformationInfo != null) { 10739 return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha; 10740 } 10741 return 1; 10742 } 10743 10744 /** 10745 * This property is hidden and intended only for use by the Fade transition, which 10746 * animates it to produce a visual translucency that does not side-effect (or get 10747 * affected by) the real alpha property. This value is composited with the other 10748 * alpha value (and the AlphaAnimation value, when that is present) to produce 10749 * a final visual translucency result, which is what is passed into the DisplayList. 10750 * 10751 * @hide 10752 */ 10753 @ViewDebug.ExportedProperty(category = "drawing") 10754 public float getTransitionAlpha() { 10755 return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1; 10756 } 10757 10758 /** 10759 * Top position of this view relative to its parent. 10760 * 10761 * @return The top of this view, in pixels. 10762 */ 10763 @ViewDebug.CapturedViewProperty 10764 public final int getTop() { 10765 return mTop; 10766 } 10767 10768 /** 10769 * Sets the top position of this view relative to its parent. This method is meant to be called 10770 * by the layout system and should not generally be called otherwise, because the property 10771 * may be changed at any time by the layout. 10772 * 10773 * @param top The top of this view, in pixels. 10774 */ 10775 public final void setTop(int top) { 10776 if (top != mTop) { 10777 final boolean matrixIsIdentity = hasIdentityMatrix(); 10778 if (matrixIsIdentity) { 10779 if (mAttachInfo != null) { 10780 int minTop; 10781 int yLoc; 10782 if (top < mTop) { 10783 minTop = top; 10784 yLoc = top - mTop; 10785 } else { 10786 minTop = mTop; 10787 yLoc = 0; 10788 } 10789 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 10790 } 10791 } else { 10792 // Double-invalidation is necessary to capture view's old and new areas 10793 invalidate(true); 10794 } 10795 10796 int width = mRight - mLeft; 10797 int oldHeight = mBottom - mTop; 10798 10799 mTop = top; 10800 mRenderNode.setTop(mTop); 10801 10802 sizeChange(width, mBottom - mTop, width, oldHeight); 10803 10804 if (!matrixIsIdentity) { 10805 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10806 invalidate(true); 10807 } 10808 mBackgroundSizeChanged = true; 10809 invalidateParentIfNeeded(); 10810 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10811 // View was rejected last time it was drawn by its parent; this may have changed 10812 invalidateParentIfNeeded(); 10813 } 10814 } 10815 } 10816 10817 /** 10818 * Bottom position of this view relative to its parent. 10819 * 10820 * @return The bottom of this view, in pixels. 10821 */ 10822 @ViewDebug.CapturedViewProperty 10823 public final int getBottom() { 10824 return mBottom; 10825 } 10826 10827 /** 10828 * True if this view has changed since the last time being drawn. 10829 * 10830 * @return The dirty state of this view. 10831 */ 10832 public boolean isDirty() { 10833 return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0; 10834 } 10835 10836 /** 10837 * Sets the bottom position of this view relative to its parent. This method is meant to be 10838 * called by the layout system and should not generally be called otherwise, because the 10839 * property may be changed at any time by the layout. 10840 * 10841 * @param bottom The bottom of this view, in pixels. 10842 */ 10843 public final void setBottom(int bottom) { 10844 if (bottom != mBottom) { 10845 final boolean matrixIsIdentity = hasIdentityMatrix(); 10846 if (matrixIsIdentity) { 10847 if (mAttachInfo != null) { 10848 int maxBottom; 10849 if (bottom < mBottom) { 10850 maxBottom = mBottom; 10851 } else { 10852 maxBottom = bottom; 10853 } 10854 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 10855 } 10856 } else { 10857 // Double-invalidation is necessary to capture view's old and new areas 10858 invalidate(true); 10859 } 10860 10861 int width = mRight - mLeft; 10862 int oldHeight = mBottom - mTop; 10863 10864 mBottom = bottom; 10865 mRenderNode.setBottom(mBottom); 10866 10867 sizeChange(width, mBottom - mTop, width, oldHeight); 10868 10869 if (!matrixIsIdentity) { 10870 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10871 invalidate(true); 10872 } 10873 mBackgroundSizeChanged = true; 10874 invalidateParentIfNeeded(); 10875 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10876 // View was rejected last time it was drawn by its parent; this may have changed 10877 invalidateParentIfNeeded(); 10878 } 10879 } 10880 } 10881 10882 /** 10883 * Left position of this view relative to its parent. 10884 * 10885 * @return The left edge of this view, in pixels. 10886 */ 10887 @ViewDebug.CapturedViewProperty 10888 public final int getLeft() { 10889 return mLeft; 10890 } 10891 10892 /** 10893 * Sets the left position of this view relative to its parent. This method is meant to be called 10894 * by the layout system and should not generally be called otherwise, because the property 10895 * may be changed at any time by the layout. 10896 * 10897 * @param left The left of this view, in pixels. 10898 */ 10899 public final void setLeft(int left) { 10900 if (left != mLeft) { 10901 final boolean matrixIsIdentity = hasIdentityMatrix(); 10902 if (matrixIsIdentity) { 10903 if (mAttachInfo != null) { 10904 int minLeft; 10905 int xLoc; 10906 if (left < mLeft) { 10907 minLeft = left; 10908 xLoc = left - mLeft; 10909 } else { 10910 minLeft = mLeft; 10911 xLoc = 0; 10912 } 10913 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 10914 } 10915 } else { 10916 // Double-invalidation is necessary to capture view's old and new areas 10917 invalidate(true); 10918 } 10919 10920 int oldWidth = mRight - mLeft; 10921 int height = mBottom - mTop; 10922 10923 mLeft = left; 10924 mRenderNode.setLeft(left); 10925 10926 sizeChange(mRight - mLeft, height, oldWidth, height); 10927 10928 if (!matrixIsIdentity) { 10929 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10930 invalidate(true); 10931 } 10932 mBackgroundSizeChanged = true; 10933 invalidateParentIfNeeded(); 10934 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10935 // View was rejected last time it was drawn by its parent; this may have changed 10936 invalidateParentIfNeeded(); 10937 } 10938 } 10939 } 10940 10941 /** 10942 * Right position of this view relative to its parent. 10943 * 10944 * @return The right edge of this view, in pixels. 10945 */ 10946 @ViewDebug.CapturedViewProperty 10947 public final int getRight() { 10948 return mRight; 10949 } 10950 10951 /** 10952 * Sets the right position of this view relative to its parent. This method is meant to be called 10953 * by the layout system and should not generally be called otherwise, because the property 10954 * may be changed at any time by the layout. 10955 * 10956 * @param right The right of this view, in pixels. 10957 */ 10958 public final void setRight(int right) { 10959 if (right != mRight) { 10960 final boolean matrixIsIdentity = hasIdentityMatrix(); 10961 if (matrixIsIdentity) { 10962 if (mAttachInfo != null) { 10963 int maxRight; 10964 if (right < mRight) { 10965 maxRight = mRight; 10966 } else { 10967 maxRight = right; 10968 } 10969 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 10970 } 10971 } else { 10972 // Double-invalidation is necessary to capture view's old and new areas 10973 invalidate(true); 10974 } 10975 10976 int oldWidth = mRight - mLeft; 10977 int height = mBottom - mTop; 10978 10979 mRight = right; 10980 mRenderNode.setRight(mRight); 10981 10982 sizeChange(mRight - mLeft, height, oldWidth, height); 10983 10984 if (!matrixIsIdentity) { 10985 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10986 invalidate(true); 10987 } 10988 mBackgroundSizeChanged = true; 10989 invalidateParentIfNeeded(); 10990 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10991 // View was rejected last time it was drawn by its parent; this may have changed 10992 invalidateParentIfNeeded(); 10993 } 10994 } 10995 } 10996 10997 /** 10998 * The visual x position of this view, in pixels. This is equivalent to the 10999 * {@link #setTranslationX(float) translationX} property plus the current 11000 * {@link #getLeft() left} property. 11001 * 11002 * @return The visual x position of this view, in pixels. 11003 */ 11004 @ViewDebug.ExportedProperty(category = "drawing") 11005 public float getX() { 11006 return mLeft + getTranslationX(); 11007 } 11008 11009 /** 11010 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 11011 * {@link #setTranslationX(float) translationX} property to be the difference between 11012 * the x value passed in and the current {@link #getLeft() left} property. 11013 * 11014 * @param x The visual x position of this view, in pixels. 11015 */ 11016 public void setX(float x) { 11017 setTranslationX(x - mLeft); 11018 } 11019 11020 /** 11021 * The visual y position of this view, in pixels. This is equivalent to the 11022 * {@link #setTranslationY(float) translationY} property plus the current 11023 * {@link #getTop() top} property. 11024 * 11025 * @return The visual y position of this view, in pixels. 11026 */ 11027 @ViewDebug.ExportedProperty(category = "drawing") 11028 public float getY() { 11029 return mTop + getTranslationY(); 11030 } 11031 11032 /** 11033 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 11034 * {@link #setTranslationY(float) translationY} property to be the difference between 11035 * the y value passed in and the current {@link #getTop() top} property. 11036 * 11037 * @param y The visual y position of this view, in pixels. 11038 */ 11039 public void setY(float y) { 11040 setTranslationY(y - mTop); 11041 } 11042 11043 /** 11044 * The visual z position of this view, in pixels. This is equivalent to the 11045 * {@link #setTranslationZ(float) translationZ} property plus the current 11046 * {@link #getElevation() elevation} property. 11047 * 11048 * @return The visual z position of this view, in pixels. 11049 */ 11050 @ViewDebug.ExportedProperty(category = "drawing") 11051 public float getZ() { 11052 return getElevation() + getTranslationZ(); 11053 } 11054 11055 /** 11056 * Sets the visual z position of this view, in pixels. This is equivalent to setting the 11057 * {@link #setTranslationZ(float) translationZ} property to be the difference between 11058 * the x value passed in and the current {@link #getElevation() elevation} property. 11059 * 11060 * @param z The visual z position of this view, in pixels. 11061 */ 11062 public void setZ(float z) { 11063 setTranslationZ(z - getElevation()); 11064 } 11065 11066 /** 11067 * The base elevation of this view relative to its parent, in pixels. 11068 * 11069 * @return The base depth position of the view, in pixels. 11070 */ 11071 @ViewDebug.ExportedProperty(category = "drawing") 11072 public float getElevation() { 11073 return mRenderNode.getElevation(); 11074 } 11075 11076 /** 11077 * Sets the base elevation of this view, in pixels. 11078 * 11079 * @attr ref android.R.styleable#View_elevation 11080 */ 11081 public void setElevation(float elevation) { 11082 if (elevation != getElevation()) { 11083 invalidateViewProperty(true, false); 11084 mRenderNode.setElevation(elevation); 11085 invalidateViewProperty(false, true); 11086 11087 invalidateParentIfNeededAndWasQuickRejected(); 11088 } 11089 } 11090 11091 /** 11092 * The horizontal location of this view relative to its {@link #getLeft() left} position. 11093 * This position is post-layout, in addition to wherever the object's 11094 * layout placed it. 11095 * 11096 * @return The horizontal position of this view relative to its left position, in pixels. 11097 */ 11098 @ViewDebug.ExportedProperty(category = "drawing") 11099 public float getTranslationX() { 11100 return mRenderNode.getTranslationX(); 11101 } 11102 11103 /** 11104 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 11105 * This effectively positions the object post-layout, in addition to wherever the object's 11106 * layout placed it. 11107 * 11108 * @param translationX The horizontal position of this view relative to its left position, 11109 * in pixels. 11110 * 11111 * @attr ref android.R.styleable#View_translationX 11112 */ 11113 public void setTranslationX(float translationX) { 11114 if (translationX != getTranslationX()) { 11115 invalidateViewProperty(true, false); 11116 mRenderNode.setTranslationX(translationX); 11117 invalidateViewProperty(false, true); 11118 11119 invalidateParentIfNeededAndWasQuickRejected(); 11120 notifySubtreeAccessibilityStateChangedIfNeeded(); 11121 } 11122 } 11123 11124 /** 11125 * The vertical location of this view relative to its {@link #getTop() top} position. 11126 * This position is post-layout, in addition to wherever the object's 11127 * layout placed it. 11128 * 11129 * @return The vertical position of this view relative to its top position, 11130 * in pixels. 11131 */ 11132 @ViewDebug.ExportedProperty(category = "drawing") 11133 public float getTranslationY() { 11134 return mRenderNode.getTranslationY(); 11135 } 11136 11137 /** 11138 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 11139 * This effectively positions the object post-layout, in addition to wherever the object's 11140 * layout placed it. 11141 * 11142 * @param translationY The vertical position of this view relative to its top position, 11143 * in pixels. 11144 * 11145 * @attr ref android.R.styleable#View_translationY 11146 */ 11147 public void setTranslationY(float translationY) { 11148 if (translationY != getTranslationY()) { 11149 invalidateViewProperty(true, false); 11150 mRenderNode.setTranslationY(translationY); 11151 invalidateViewProperty(false, true); 11152 11153 invalidateParentIfNeededAndWasQuickRejected(); 11154 } 11155 } 11156 11157 /** 11158 * The depth location of this view relative to its {@link #getElevation() elevation}. 11159 * 11160 * @return The depth of this view relative to its elevation. 11161 */ 11162 @ViewDebug.ExportedProperty(category = "drawing") 11163 public float getTranslationZ() { 11164 return mRenderNode.getTranslationZ(); 11165 } 11166 11167 /** 11168 * Sets the depth location of this view relative to its {@link #getElevation() elevation}. 11169 * 11170 * @attr ref android.R.styleable#View_translationZ 11171 */ 11172 public void setTranslationZ(float translationZ) { 11173 if (translationZ != getTranslationZ()) { 11174 invalidateViewProperty(true, false); 11175 mRenderNode.setTranslationZ(translationZ); 11176 invalidateViewProperty(false, true); 11177 11178 invalidateParentIfNeededAndWasQuickRejected(); 11179 } 11180 } 11181 11182 /** @hide */ 11183 public void setAnimationMatrix(Matrix matrix) { 11184 invalidateViewProperty(true, false); 11185 mRenderNode.setAnimationMatrix(matrix); 11186 invalidateViewProperty(false, true); 11187 11188 invalidateParentIfNeededAndWasQuickRejected(); 11189 } 11190 11191 /** 11192 * Returns the current StateListAnimator if exists. 11193 * 11194 * @return StateListAnimator or null if it does not exists 11195 * @see #setStateListAnimator(android.animation.StateListAnimator) 11196 */ 11197 public StateListAnimator getStateListAnimator() { 11198 return mStateListAnimator; 11199 } 11200 11201 /** 11202 * Attaches the provided StateListAnimator to this View. 11203 * <p> 11204 * Any previously attached StateListAnimator will be detached. 11205 * 11206 * @param stateListAnimator The StateListAnimator to update the view 11207 * @see {@link android.animation.StateListAnimator} 11208 */ 11209 public void setStateListAnimator(StateListAnimator stateListAnimator) { 11210 if (mStateListAnimator == stateListAnimator) { 11211 return; 11212 } 11213 if (mStateListAnimator != null) { 11214 mStateListAnimator.setTarget(null); 11215 } 11216 mStateListAnimator = stateListAnimator; 11217 if (stateListAnimator != null) { 11218 stateListAnimator.setTarget(this); 11219 if (isAttachedToWindow()) { 11220 stateListAnimator.setState(getDrawableState()); 11221 } 11222 } 11223 } 11224 11225 /** 11226 * Returns whether the Outline should be used to clip the contents of the View. 11227 * <p> 11228 * Note that this flag will only be respected if the View's Outline returns true from 11229 * {@link Outline#canClip()}. 11230 * 11231 * @see #setOutlineProvider(ViewOutlineProvider) 11232 * @see #setClipToOutline(boolean) 11233 */ 11234 public final boolean getClipToOutline() { 11235 return mRenderNode.getClipToOutline(); 11236 } 11237 11238 /** 11239 * Sets whether the View's Outline should be used to clip the contents of the View. 11240 * <p> 11241 * Only a single non-rectangular clip can be applied on a View at any time. 11242 * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float) 11243 * circular reveal} animation take priority over Outline clipping, and 11244 * child Outline clipping takes priority over Outline clipping done by a 11245 * parent. 11246 * <p> 11247 * Note that this flag will only be respected if the View's Outline returns true from 11248 * {@link Outline#canClip()}. 11249 * 11250 * @see #setOutlineProvider(ViewOutlineProvider) 11251 * @see #getClipToOutline() 11252 */ 11253 public void setClipToOutline(boolean clipToOutline) { 11254 damageInParent(); 11255 if (getClipToOutline() != clipToOutline) { 11256 mRenderNode.setClipToOutline(clipToOutline); 11257 } 11258 } 11259 11260 // correspond to the enum values of View_outlineProvider 11261 private static final int PROVIDER_BACKGROUND = 0; 11262 private static final int PROVIDER_NONE = 1; 11263 private static final int PROVIDER_BOUNDS = 2; 11264 private static final int PROVIDER_PADDED_BOUNDS = 3; 11265 private void setOutlineProviderFromAttribute(int providerInt) { 11266 switch (providerInt) { 11267 case PROVIDER_BACKGROUND: 11268 setOutlineProvider(ViewOutlineProvider.BACKGROUND); 11269 break; 11270 case PROVIDER_NONE: 11271 setOutlineProvider(null); 11272 break; 11273 case PROVIDER_BOUNDS: 11274 setOutlineProvider(ViewOutlineProvider.BOUNDS); 11275 break; 11276 case PROVIDER_PADDED_BOUNDS: 11277 setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS); 11278 break; 11279 } 11280 } 11281 11282 /** 11283 * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines 11284 * the shape of the shadow it casts, and enables outline clipping. 11285 * <p> 11286 * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline 11287 * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the 11288 * outline provider with this method allows this behavior to be overridden. 11289 * <p> 11290 * If the ViewOutlineProvider is null, if querying it for an outline returns false, 11291 * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast. 11292 * <p> 11293 * Only outlines that return true from {@link Outline#canClip()} may be used for clipping. 11294 * 11295 * @see #setClipToOutline(boolean) 11296 * @see #getClipToOutline() 11297 * @see #getOutlineProvider() 11298 */ 11299 public void setOutlineProvider(ViewOutlineProvider provider) { 11300 mOutlineProvider = provider; 11301 invalidateOutline(); 11302 } 11303 11304 /** 11305 * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline 11306 * that defines the shape of the shadow it casts, and enables outline clipping. 11307 * 11308 * @see #setOutlineProvider(ViewOutlineProvider) 11309 */ 11310 public ViewOutlineProvider getOutlineProvider() { 11311 return mOutlineProvider; 11312 } 11313 11314 /** 11315 * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider} 11316 * 11317 * @see #setOutlineProvider(ViewOutlineProvider) 11318 */ 11319 public void invalidateOutline() { 11320 rebuildOutline(); 11321 11322 notifySubtreeAccessibilityStateChangedIfNeeded(); 11323 invalidateViewProperty(false, false); 11324 } 11325 11326 /** 11327 * Internal version of {@link #invalidateOutline()} which invalidates the 11328 * outline without invalidating the view itself. This is intended to be called from 11329 * within methods in the View class itself which are the result of the view being 11330 * invalidated already. For example, when we are drawing the background of a View, 11331 * we invalidate the outline in case it changed in the meantime, but we do not 11332 * need to invalidate the view because we're already drawing the background as part 11333 * of drawing the view in response to an earlier invalidation of the view. 11334 */ 11335 private void rebuildOutline() { 11336 // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow() 11337 if (mAttachInfo == null) return; 11338 11339 if (mOutlineProvider == null) { 11340 // no provider, remove outline 11341 mRenderNode.setOutline(null); 11342 } else { 11343 final Outline outline = mAttachInfo.mTmpOutline; 11344 outline.setEmpty(); 11345 outline.setAlpha(1.0f); 11346 11347 mOutlineProvider.getOutline(this, outline); 11348 mRenderNode.setOutline(outline); 11349 } 11350 } 11351 11352 /** 11353 * HierarchyViewer only 11354 * 11355 * @hide 11356 */ 11357 @ViewDebug.ExportedProperty(category = "drawing") 11358 public boolean hasShadow() { 11359 return mRenderNode.hasShadow(); 11360 } 11361 11362 11363 /** @hide */ 11364 public void setRevealClip(boolean shouldClip, float x, float y, float radius) { 11365 mRenderNode.setRevealClip(shouldClip, x, y, radius); 11366 invalidateViewProperty(false, false); 11367 } 11368 11369 /** 11370 * Hit rectangle in parent's coordinates 11371 * 11372 * @param outRect The hit rectangle of the view. 11373 */ 11374 public void getHitRect(Rect outRect) { 11375 if (hasIdentityMatrix() || mAttachInfo == null) { 11376 outRect.set(mLeft, mTop, mRight, mBottom); 11377 } else { 11378 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 11379 tmpRect.set(0, 0, getWidth(), getHeight()); 11380 getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect) 11381 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 11382 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 11383 } 11384 } 11385 11386 /** 11387 * Determines whether the given point, in local coordinates is inside the view. 11388 */ 11389 /*package*/ final boolean pointInView(float localX, float localY) { 11390 return localX >= 0 && localX < (mRight - mLeft) 11391 && localY >= 0 && localY < (mBottom - mTop); 11392 } 11393 11394 /** 11395 * Utility method to determine whether the given point, in local coordinates, 11396 * is inside the view, where the area of the view is expanded by the slop factor. 11397 * This method is called while processing touch-move events to determine if the event 11398 * is still within the view. 11399 * 11400 * @hide 11401 */ 11402 public boolean pointInView(float localX, float localY, float slop) { 11403 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 11404 localY < ((mBottom - mTop) + slop); 11405 } 11406 11407 /** 11408 * When a view has focus and the user navigates away from it, the next view is searched for 11409 * starting from the rectangle filled in by this method. 11410 * 11411 * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)}) 11412 * of the view. However, if your view maintains some idea of internal selection, 11413 * such as a cursor, or a selected row or column, you should override this method and 11414 * fill in a more specific rectangle. 11415 * 11416 * @param r The rectangle to fill in, in this view's coordinates. 11417 */ 11418 public void getFocusedRect(Rect r) { 11419 getDrawingRect(r); 11420 } 11421 11422 /** 11423 * If some part of this view is not clipped by any of its parents, then 11424 * return that area in r in global (root) coordinates. To convert r to local 11425 * coordinates (without taking possible View rotations into account), offset 11426 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 11427 * If the view is completely clipped or translated out, return false. 11428 * 11429 * @param r If true is returned, r holds the global coordinates of the 11430 * visible portion of this view. 11431 * @param globalOffset If true is returned, globalOffset holds the dx,dy 11432 * between this view and its root. globalOffet may be null. 11433 * @return true if r is non-empty (i.e. part of the view is visible at the 11434 * root level. 11435 */ 11436 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 11437 int width = mRight - mLeft; 11438 int height = mBottom - mTop; 11439 if (width > 0 && height > 0) { 11440 r.set(0, 0, width, height); 11441 if (globalOffset != null) { 11442 globalOffset.set(-mScrollX, -mScrollY); 11443 } 11444 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 11445 } 11446 return false; 11447 } 11448 11449 public final boolean getGlobalVisibleRect(Rect r) { 11450 return getGlobalVisibleRect(r, null); 11451 } 11452 11453 public final boolean getLocalVisibleRect(Rect r) { 11454 final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point(); 11455 if (getGlobalVisibleRect(r, offset)) { 11456 r.offset(-offset.x, -offset.y); // make r local 11457 return true; 11458 } 11459 return false; 11460 } 11461 11462 /** 11463 * Offset this view's vertical location by the specified number of pixels. 11464 * 11465 * @param offset the number of pixels to offset the view by 11466 */ 11467 public void offsetTopAndBottom(int offset) { 11468 if (offset != 0) { 11469 final boolean matrixIsIdentity = hasIdentityMatrix(); 11470 if (matrixIsIdentity) { 11471 if (isHardwareAccelerated()) { 11472 invalidateViewProperty(false, false); 11473 } else { 11474 final ViewParent p = mParent; 11475 if (p != null && mAttachInfo != null) { 11476 final Rect r = mAttachInfo.mTmpInvalRect; 11477 int minTop; 11478 int maxBottom; 11479 int yLoc; 11480 if (offset < 0) { 11481 minTop = mTop + offset; 11482 maxBottom = mBottom; 11483 yLoc = offset; 11484 } else { 11485 minTop = mTop; 11486 maxBottom = mBottom + offset; 11487 yLoc = 0; 11488 } 11489 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 11490 p.invalidateChild(this, r); 11491 } 11492 } 11493 } else { 11494 invalidateViewProperty(false, false); 11495 } 11496 11497 mTop += offset; 11498 mBottom += offset; 11499 mRenderNode.offsetTopAndBottom(offset); 11500 if (isHardwareAccelerated()) { 11501 invalidateViewProperty(false, false); 11502 } else { 11503 if (!matrixIsIdentity) { 11504 invalidateViewProperty(false, true); 11505 } 11506 invalidateParentIfNeeded(); 11507 } 11508 notifySubtreeAccessibilityStateChangedIfNeeded(); 11509 } 11510 } 11511 11512 /** 11513 * Offset this view's horizontal location by the specified amount of pixels. 11514 * 11515 * @param offset the number of pixels to offset the view by 11516 */ 11517 public void offsetLeftAndRight(int offset) { 11518 if (offset != 0) { 11519 final boolean matrixIsIdentity = hasIdentityMatrix(); 11520 if (matrixIsIdentity) { 11521 if (isHardwareAccelerated()) { 11522 invalidateViewProperty(false, false); 11523 } else { 11524 final ViewParent p = mParent; 11525 if (p != null && mAttachInfo != null) { 11526 final Rect r = mAttachInfo.mTmpInvalRect; 11527 int minLeft; 11528 int maxRight; 11529 if (offset < 0) { 11530 minLeft = mLeft + offset; 11531 maxRight = mRight; 11532 } else { 11533 minLeft = mLeft; 11534 maxRight = mRight + offset; 11535 } 11536 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 11537 p.invalidateChild(this, r); 11538 } 11539 } 11540 } else { 11541 invalidateViewProperty(false, false); 11542 } 11543 11544 mLeft += offset; 11545 mRight += offset; 11546 mRenderNode.offsetLeftAndRight(offset); 11547 if (isHardwareAccelerated()) { 11548 invalidateViewProperty(false, false); 11549 } else { 11550 if (!matrixIsIdentity) { 11551 invalidateViewProperty(false, true); 11552 } 11553 invalidateParentIfNeeded(); 11554 } 11555 notifySubtreeAccessibilityStateChangedIfNeeded(); 11556 } 11557 } 11558 11559 /** 11560 * Get the LayoutParams associated with this view. All views should have 11561 * layout parameters. These supply parameters to the <i>parent</i> of this 11562 * view specifying how it should be arranged. There are many subclasses of 11563 * ViewGroup.LayoutParams, and these correspond to the different subclasses 11564 * of ViewGroup that are responsible for arranging their children. 11565 * 11566 * This method may return null if this View is not attached to a parent 11567 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 11568 * was not invoked successfully. When a View is attached to a parent 11569 * ViewGroup, this method must not return null. 11570 * 11571 * @return The LayoutParams associated with this view, or null if no 11572 * parameters have been set yet 11573 */ 11574 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 11575 public ViewGroup.LayoutParams getLayoutParams() { 11576 return mLayoutParams; 11577 } 11578 11579 /** 11580 * Set the layout parameters associated with this view. These supply 11581 * parameters to the <i>parent</i> of this view specifying how it should be 11582 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 11583 * correspond to the different subclasses of ViewGroup that are responsible 11584 * for arranging their children. 11585 * 11586 * @param params The layout parameters for this view, cannot be null 11587 */ 11588 public void setLayoutParams(ViewGroup.LayoutParams params) { 11589 if (params == null) { 11590 throw new NullPointerException("Layout parameters cannot be null"); 11591 } 11592 mLayoutParams = params; 11593 resolveLayoutParams(); 11594 if (mParent instanceof ViewGroup) { 11595 ((ViewGroup) mParent).onSetLayoutParams(this, params); 11596 } 11597 requestLayout(); 11598 } 11599 11600 /** 11601 * Resolve the layout parameters depending on the resolved layout direction 11602 * 11603 * @hide 11604 */ 11605 public void resolveLayoutParams() { 11606 if (mLayoutParams != null) { 11607 mLayoutParams.resolveLayoutDirection(getLayoutDirection()); 11608 } 11609 } 11610 11611 /** 11612 * Set the scrolled position of your view. This will cause a call to 11613 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11614 * invalidated. 11615 * @param x the x position to scroll to 11616 * @param y the y position to scroll to 11617 */ 11618 public void scrollTo(int x, int y) { 11619 if (mScrollX != x || mScrollY != y) { 11620 int oldX = mScrollX; 11621 int oldY = mScrollY; 11622 mScrollX = x; 11623 mScrollY = y; 11624 invalidateParentCaches(); 11625 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 11626 if (!awakenScrollBars()) { 11627 postInvalidateOnAnimation(); 11628 } 11629 } 11630 } 11631 11632 /** 11633 * Move the scrolled position of your view. This will cause a call to 11634 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11635 * invalidated. 11636 * @param x the amount of pixels to scroll by horizontally 11637 * @param y the amount of pixels to scroll by vertically 11638 */ 11639 public void scrollBy(int x, int y) { 11640 scrollTo(mScrollX + x, mScrollY + y); 11641 } 11642 11643 /** 11644 * <p>Trigger the scrollbars to draw. When invoked this method starts an 11645 * animation to fade the scrollbars out after a default delay. If a subclass 11646 * provides animated scrolling, the start delay should equal the duration 11647 * of the scrolling animation.</p> 11648 * 11649 * <p>The animation starts only if at least one of the scrollbars is 11650 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 11651 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11652 * this method returns true, and false otherwise. If the animation is 11653 * started, this method calls {@link #invalidate()}; in that case the 11654 * caller should not call {@link #invalidate()}.</p> 11655 * 11656 * <p>This method should be invoked every time a subclass directly updates 11657 * the scroll parameters.</p> 11658 * 11659 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 11660 * and {@link #scrollTo(int, int)}.</p> 11661 * 11662 * @return true if the animation is played, false otherwise 11663 * 11664 * @see #awakenScrollBars(int) 11665 * @see #scrollBy(int, int) 11666 * @see #scrollTo(int, int) 11667 * @see #isHorizontalScrollBarEnabled() 11668 * @see #isVerticalScrollBarEnabled() 11669 * @see #setHorizontalScrollBarEnabled(boolean) 11670 * @see #setVerticalScrollBarEnabled(boolean) 11671 */ 11672 protected boolean awakenScrollBars() { 11673 return mScrollCache != null && 11674 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 11675 } 11676 11677 /** 11678 * Trigger the scrollbars to draw. 11679 * This method differs from awakenScrollBars() only in its default duration. 11680 * initialAwakenScrollBars() will show the scroll bars for longer than 11681 * usual to give the user more of a chance to notice them. 11682 * 11683 * @return true if the animation is played, false otherwise. 11684 */ 11685 private boolean initialAwakenScrollBars() { 11686 return mScrollCache != null && 11687 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 11688 } 11689 11690 /** 11691 * <p> 11692 * Trigger the scrollbars to draw. When invoked this method starts an 11693 * animation to fade the scrollbars out after a fixed delay. If a subclass 11694 * provides animated scrolling, the start delay should equal the duration of 11695 * the scrolling animation. 11696 * </p> 11697 * 11698 * <p> 11699 * The animation starts only if at least one of the scrollbars is enabled, 11700 * as specified by {@link #isHorizontalScrollBarEnabled()} and 11701 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11702 * this method returns true, and false otherwise. If the animation is 11703 * started, this method calls {@link #invalidate()}; in that case the caller 11704 * should not call {@link #invalidate()}. 11705 * </p> 11706 * 11707 * <p> 11708 * This method should be invoked everytime a subclass directly updates the 11709 * scroll parameters. 11710 * </p> 11711 * 11712 * @param startDelay the delay, in milliseconds, after which the animation 11713 * should start; when the delay is 0, the animation starts 11714 * immediately 11715 * @return true if the animation is played, false otherwise 11716 * 11717 * @see #scrollBy(int, int) 11718 * @see #scrollTo(int, int) 11719 * @see #isHorizontalScrollBarEnabled() 11720 * @see #isVerticalScrollBarEnabled() 11721 * @see #setHorizontalScrollBarEnabled(boolean) 11722 * @see #setVerticalScrollBarEnabled(boolean) 11723 */ 11724 protected boolean awakenScrollBars(int startDelay) { 11725 return awakenScrollBars(startDelay, true); 11726 } 11727 11728 /** 11729 * <p> 11730 * Trigger the scrollbars to draw. When invoked this method starts an 11731 * animation to fade the scrollbars out after a fixed delay. If a subclass 11732 * provides animated scrolling, the start delay should equal the duration of 11733 * the scrolling animation. 11734 * </p> 11735 * 11736 * <p> 11737 * The animation starts only if at least one of the scrollbars is enabled, 11738 * as specified by {@link #isHorizontalScrollBarEnabled()} and 11739 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11740 * this method returns true, and false otherwise. If the animation is 11741 * started, this method calls {@link #invalidate()} if the invalidate parameter 11742 * is set to true; in that case the caller 11743 * should not call {@link #invalidate()}. 11744 * </p> 11745 * 11746 * <p> 11747 * This method should be invoked everytime a subclass directly updates the 11748 * scroll parameters. 11749 * </p> 11750 * 11751 * @param startDelay the delay, in milliseconds, after which the animation 11752 * should start; when the delay is 0, the animation starts 11753 * immediately 11754 * 11755 * @param invalidate Wheter this method should call invalidate 11756 * 11757 * @return true if the animation is played, false otherwise 11758 * 11759 * @see #scrollBy(int, int) 11760 * @see #scrollTo(int, int) 11761 * @see #isHorizontalScrollBarEnabled() 11762 * @see #isVerticalScrollBarEnabled() 11763 * @see #setHorizontalScrollBarEnabled(boolean) 11764 * @see #setVerticalScrollBarEnabled(boolean) 11765 */ 11766 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 11767 final ScrollabilityCache scrollCache = mScrollCache; 11768 11769 if (scrollCache == null || !scrollCache.fadeScrollBars) { 11770 return false; 11771 } 11772 11773 if (scrollCache.scrollBar == null) { 11774 scrollCache.scrollBar = new ScrollBarDrawable(); 11775 } 11776 11777 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 11778 11779 if (invalidate) { 11780 // Invalidate to show the scrollbars 11781 postInvalidateOnAnimation(); 11782 } 11783 11784 if (scrollCache.state == ScrollabilityCache.OFF) { 11785 // FIXME: this is copied from WindowManagerService. 11786 // We should get this value from the system when it 11787 // is possible to do so. 11788 final int KEY_REPEAT_FIRST_DELAY = 750; 11789 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 11790 } 11791 11792 // Tell mScrollCache when we should start fading. This may 11793 // extend the fade start time if one was already scheduled 11794 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 11795 scrollCache.fadeStartTime = fadeStartTime; 11796 scrollCache.state = ScrollabilityCache.ON; 11797 11798 // Schedule our fader to run, unscheduling any old ones first 11799 if (mAttachInfo != null) { 11800 mAttachInfo.mHandler.removeCallbacks(scrollCache); 11801 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 11802 } 11803 11804 return true; 11805 } 11806 11807 return false; 11808 } 11809 11810 /** 11811 * Do not invalidate views which are not visible and which are not running an animation. They 11812 * will not get drawn and they should not set dirty flags as if they will be drawn 11813 */ 11814 private boolean skipInvalidate() { 11815 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 11816 (!(mParent instanceof ViewGroup) || 11817 !((ViewGroup) mParent).isViewTransitioning(this)); 11818 } 11819 11820 /** 11821 * Mark the area defined by dirty as needing to be drawn. If the view is 11822 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 11823 * point in the future. 11824 * <p> 11825 * This must be called from a UI thread. To call from a non-UI thread, call 11826 * {@link #postInvalidate()}. 11827 * <p> 11828 * <b>WARNING:</b> In API 19 and below, this method may be destructive to 11829 * {@code dirty}. 11830 * 11831 * @param dirty the rectangle representing the bounds of the dirty region 11832 */ 11833 public void invalidate(Rect dirty) { 11834 final int scrollX = mScrollX; 11835 final int scrollY = mScrollY; 11836 invalidateInternal(dirty.left - scrollX, dirty.top - scrollY, 11837 dirty.right - scrollX, dirty.bottom - scrollY, true, false); 11838 } 11839 11840 /** 11841 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The 11842 * coordinates of the dirty rect are relative to the view. If the view is 11843 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 11844 * point in the future. 11845 * <p> 11846 * This must be called from a UI thread. To call from a non-UI thread, call 11847 * {@link #postInvalidate()}. 11848 * 11849 * @param l the left position of the dirty region 11850 * @param t the top position of the dirty region 11851 * @param r the right position of the dirty region 11852 * @param b the bottom position of the dirty region 11853 */ 11854 public void invalidate(int l, int t, int r, int b) { 11855 final int scrollX = mScrollX; 11856 final int scrollY = mScrollY; 11857 invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false); 11858 } 11859 11860 /** 11861 * Invalidate the whole view. If the view is visible, 11862 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 11863 * the future. 11864 * <p> 11865 * This must be called from a UI thread. To call from a non-UI thread, call 11866 * {@link #postInvalidate()}. 11867 */ 11868 public void invalidate() { 11869 invalidate(true); 11870 } 11871 11872 /** 11873 * This is where the invalidate() work actually happens. A full invalidate() 11874 * causes the drawing cache to be invalidated, but this function can be 11875 * called with invalidateCache set to false to skip that invalidation step 11876 * for cases that do not need it (for example, a component that remains at 11877 * the same dimensions with the same content). 11878 * 11879 * @param invalidateCache Whether the drawing cache for this view should be 11880 * invalidated as well. This is usually true for a full 11881 * invalidate, but may be set to false if the View's contents or 11882 * dimensions have not changed. 11883 */ 11884 void invalidate(boolean invalidateCache) { 11885 invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true); 11886 } 11887 11888 void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache, 11889 boolean fullInvalidate) { 11890 if (mGhostView != null) { 11891 mGhostView.invalidate(true); 11892 return; 11893 } 11894 11895 if (skipInvalidate()) { 11896 return; 11897 } 11898 11899 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) 11900 || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) 11901 || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED 11902 || (fullInvalidate && isOpaque() != mLastIsOpaque)) { 11903 if (fullInvalidate) { 11904 mLastIsOpaque = isOpaque(); 11905 mPrivateFlags &= ~PFLAG_DRAWN; 11906 } 11907 11908 mPrivateFlags |= PFLAG_DIRTY; 11909 11910 if (invalidateCache) { 11911 mPrivateFlags |= PFLAG_INVALIDATED; 11912 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 11913 } 11914 11915 // Propagate the damage rectangle to the parent view. 11916 final AttachInfo ai = mAttachInfo; 11917 final ViewParent p = mParent; 11918 if (p != null && ai != null && l < r && t < b) { 11919 final Rect damage = ai.mTmpInvalRect; 11920 damage.set(l, t, r, b); 11921 p.invalidateChild(this, damage); 11922 } 11923 11924 // Damage the entire projection receiver, if necessary. 11925 if (mBackground != null && mBackground.isProjected()) { 11926 final View receiver = getProjectionReceiver(); 11927 if (receiver != null) { 11928 receiver.damageInParent(); 11929 } 11930 } 11931 11932 // Damage the entire IsolatedZVolume receiving this view's shadow. 11933 if (isHardwareAccelerated() && getZ() != 0) { 11934 damageShadowReceiver(); 11935 } 11936 } 11937 } 11938 11939 /** 11940 * @return this view's projection receiver, or {@code null} if none exists 11941 */ 11942 private View getProjectionReceiver() { 11943 ViewParent p = getParent(); 11944 while (p != null && p instanceof View) { 11945 final View v = (View) p; 11946 if (v.isProjectionReceiver()) { 11947 return v; 11948 } 11949 p = p.getParent(); 11950 } 11951 11952 return null; 11953 } 11954 11955 /** 11956 * @return whether the view is a projection receiver 11957 */ 11958 private boolean isProjectionReceiver() { 11959 return mBackground != null; 11960 } 11961 11962 /** 11963 * Damage area of the screen that can be covered by this View's shadow. 11964 * 11965 * This method will guarantee that any changes to shadows cast by a View 11966 * are damaged on the screen for future redraw. 11967 */ 11968 private void damageShadowReceiver() { 11969 final AttachInfo ai = mAttachInfo; 11970 if (ai != null) { 11971 ViewParent p = getParent(); 11972 if (p != null && p instanceof ViewGroup) { 11973 final ViewGroup vg = (ViewGroup) p; 11974 vg.damageInParent(); 11975 } 11976 } 11977 } 11978 11979 /** 11980 * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to 11981 * set any flags or handle all of the cases handled by the default invalidation methods. 11982 * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate 11983 * dirty rect. This method calls into fast invalidation methods in ViewGroup that 11984 * walk up the hierarchy, transforming the dirty rect as necessary. 11985 * 11986 * The method also handles normal invalidation logic if display list properties are not 11987 * being used in this view. The invalidateParent and forceRedraw flags are used by that 11988 * backup approach, to handle these cases used in the various property-setting methods. 11989 * 11990 * @param invalidateParent Force a call to invalidateParentCaches() if display list properties 11991 * are not being used in this view 11992 * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display 11993 * list properties are not being used in this view 11994 */ 11995 void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) { 11996 if (!isHardwareAccelerated() 11997 || !mRenderNode.isValid() 11998 || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) { 11999 if (invalidateParent) { 12000 invalidateParentCaches(); 12001 } 12002 if (forceRedraw) { 12003 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 12004 } 12005 invalidate(false); 12006 } else { 12007 damageInParent(); 12008 } 12009 if (isHardwareAccelerated() && invalidateParent && getZ() != 0) { 12010 damageShadowReceiver(); 12011 } 12012 } 12013 12014 /** 12015 * Tells the parent view to damage this view's bounds. 12016 * 12017 * @hide 12018 */ 12019 protected void damageInParent() { 12020 final AttachInfo ai = mAttachInfo; 12021 final ViewParent p = mParent; 12022 if (p != null && ai != null) { 12023 final Rect r = ai.mTmpInvalRect; 12024 r.set(0, 0, mRight - mLeft, mBottom - mTop); 12025 if (mParent instanceof ViewGroup) { 12026 ((ViewGroup) mParent).damageChild(this, r); 12027 } else { 12028 mParent.invalidateChild(this, r); 12029 } 12030 } 12031 } 12032 12033 /** 12034 * Utility method to transform a given Rect by the current matrix of this view. 12035 */ 12036 void transformRect(final Rect rect) { 12037 if (!getMatrix().isIdentity()) { 12038 RectF boundingRect = mAttachInfo.mTmpTransformRect; 12039 boundingRect.set(rect); 12040 getMatrix().mapRect(boundingRect); 12041 rect.set((int) Math.floor(boundingRect.left), 12042 (int) Math.floor(boundingRect.top), 12043 (int) Math.ceil(boundingRect.right), 12044 (int) Math.ceil(boundingRect.bottom)); 12045 } 12046 } 12047 12048 /** 12049 * Used to indicate that the parent of this view should clear its caches. This functionality 12050 * is used to force the parent to rebuild its display list (when hardware-accelerated), 12051 * which is necessary when various parent-managed properties of the view change, such as 12052 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 12053 * clears the parent caches and does not causes an invalidate event. 12054 * 12055 * @hide 12056 */ 12057 protected void invalidateParentCaches() { 12058 if (mParent instanceof View) { 12059 ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED; 12060 } 12061 } 12062 12063 /** 12064 * Used to indicate that the parent of this view should be invalidated. This functionality 12065 * is used to force the parent to rebuild its display list (when hardware-accelerated), 12066 * which is necessary when various parent-managed properties of the view change, such as 12067 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 12068 * an invalidation event to the parent. 12069 * 12070 * @hide 12071 */ 12072 protected void invalidateParentIfNeeded() { 12073 if (isHardwareAccelerated() && mParent instanceof View) { 12074 ((View) mParent).invalidate(true); 12075 } 12076 } 12077 12078 /** 12079 * @hide 12080 */ 12081 protected void invalidateParentIfNeededAndWasQuickRejected() { 12082 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) { 12083 // View was rejected last time it was drawn by its parent; this may have changed 12084 invalidateParentIfNeeded(); 12085 } 12086 } 12087 12088 /** 12089 * Indicates whether this View is opaque. An opaque View guarantees that it will 12090 * draw all the pixels overlapping its bounds using a fully opaque color. 12091 * 12092 * Subclasses of View should override this method whenever possible to indicate 12093 * whether an instance is opaque. Opaque Views are treated in a special way by 12094 * the View hierarchy, possibly allowing it to perform optimizations during 12095 * invalidate/draw passes. 12096 * 12097 * @return True if this View is guaranteed to be fully opaque, false otherwise. 12098 */ 12099 @ViewDebug.ExportedProperty(category = "drawing") 12100 public boolean isOpaque() { 12101 return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK && 12102 getFinalAlpha() >= 1.0f; 12103 } 12104 12105 /** 12106 * @hide 12107 */ 12108 protected void computeOpaqueFlags() { 12109 // Opaque if: 12110 // - Has a background 12111 // - Background is opaque 12112 // - Doesn't have scrollbars or scrollbars overlay 12113 12114 if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) { 12115 mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND; 12116 } else { 12117 mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND; 12118 } 12119 12120 final int flags = mViewFlags; 12121 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 12122 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY || 12123 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) { 12124 mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS; 12125 } else { 12126 mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS; 12127 } 12128 } 12129 12130 /** 12131 * @hide 12132 */ 12133 protected boolean hasOpaqueScrollbars() { 12134 return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS; 12135 } 12136 12137 /** 12138 * @return A handler associated with the thread running the View. This 12139 * handler can be used to pump events in the UI events queue. 12140 */ 12141 public Handler getHandler() { 12142 final AttachInfo attachInfo = mAttachInfo; 12143 if (attachInfo != null) { 12144 return attachInfo.mHandler; 12145 } 12146 return null; 12147 } 12148 12149 /** 12150 * Gets the view root associated with the View. 12151 * @return The view root, or null if none. 12152 * @hide 12153 */ 12154 public ViewRootImpl getViewRootImpl() { 12155 if (mAttachInfo != null) { 12156 return mAttachInfo.mViewRootImpl; 12157 } 12158 return null; 12159 } 12160 12161 /** 12162 * @hide 12163 */ 12164 public HardwareRenderer getHardwareRenderer() { 12165 return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null; 12166 } 12167 12168 /** 12169 * <p>Causes the Runnable to be added to the message queue. 12170 * The runnable will be run on the user interface thread.</p> 12171 * 12172 * @param action The Runnable that will be executed. 12173 * 12174 * @return Returns true if the Runnable was successfully placed in to the 12175 * message queue. Returns false on failure, usually because the 12176 * looper processing the message queue is exiting. 12177 * 12178 * @see #postDelayed 12179 * @see #removeCallbacks 12180 */ 12181 public boolean post(Runnable action) { 12182 final AttachInfo attachInfo = mAttachInfo; 12183 if (attachInfo != null) { 12184 return attachInfo.mHandler.post(action); 12185 } 12186 // Assume that post will succeed later 12187 ViewRootImpl.getRunQueue().post(action); 12188 return true; 12189 } 12190 12191 /** 12192 * <p>Causes the Runnable to be added to the message queue, to be run 12193 * after the specified amount of time elapses. 12194 * The runnable will be run on the user interface thread.</p> 12195 * 12196 * @param action The Runnable that will be executed. 12197 * @param delayMillis The delay (in milliseconds) until the Runnable 12198 * will be executed. 12199 * 12200 * @return true if the Runnable was successfully placed in to the 12201 * message queue. Returns false on failure, usually because the 12202 * looper processing the message queue is exiting. Note that a 12203 * result of true does not mean the Runnable will be processed -- 12204 * if the looper is quit before the delivery time of the message 12205 * occurs then the message will be dropped. 12206 * 12207 * @see #post 12208 * @see #removeCallbacks 12209 */ 12210 public boolean postDelayed(Runnable action, long delayMillis) { 12211 final AttachInfo attachInfo = mAttachInfo; 12212 if (attachInfo != null) { 12213 return attachInfo.mHandler.postDelayed(action, delayMillis); 12214 } 12215 // Assume that post will succeed later 12216 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 12217 return true; 12218 } 12219 12220 /** 12221 * <p>Causes the Runnable to execute on the next animation time step. 12222 * The runnable will be run on the user interface thread.</p> 12223 * 12224 * @param action The Runnable that will be executed. 12225 * 12226 * @see #postOnAnimationDelayed 12227 * @see #removeCallbacks 12228 */ 12229 public void postOnAnimation(Runnable action) { 12230 final AttachInfo attachInfo = mAttachInfo; 12231 if (attachInfo != null) { 12232 attachInfo.mViewRootImpl.mChoreographer.postCallback( 12233 Choreographer.CALLBACK_ANIMATION, action, null); 12234 } else { 12235 // Assume that post will succeed later 12236 ViewRootImpl.getRunQueue().post(action); 12237 } 12238 } 12239 12240 /** 12241 * <p>Causes the Runnable to execute on the next animation time step, 12242 * after the specified amount of time elapses. 12243 * The runnable will be run on the user interface thread.</p> 12244 * 12245 * @param action The Runnable that will be executed. 12246 * @param delayMillis The delay (in milliseconds) until the Runnable 12247 * will be executed. 12248 * 12249 * @see #postOnAnimation 12250 * @see #removeCallbacks 12251 */ 12252 public void postOnAnimationDelayed(Runnable action, long delayMillis) { 12253 final AttachInfo attachInfo = mAttachInfo; 12254 if (attachInfo != null) { 12255 attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 12256 Choreographer.CALLBACK_ANIMATION, action, null, delayMillis); 12257 } else { 12258 // Assume that post will succeed later 12259 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 12260 } 12261 } 12262 12263 /** 12264 * <p>Removes the specified Runnable from the message queue.</p> 12265 * 12266 * @param action The Runnable to remove from the message handling queue 12267 * 12268 * @return true if this view could ask the Handler to remove the Runnable, 12269 * false otherwise. When the returned value is true, the Runnable 12270 * may or may not have been actually removed from the message queue 12271 * (for instance, if the Runnable was not in the queue already.) 12272 * 12273 * @see #post 12274 * @see #postDelayed 12275 * @see #postOnAnimation 12276 * @see #postOnAnimationDelayed 12277 */ 12278 public boolean removeCallbacks(Runnable action) { 12279 if (action != null) { 12280 final AttachInfo attachInfo = mAttachInfo; 12281 if (attachInfo != null) { 12282 attachInfo.mHandler.removeCallbacks(action); 12283 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 12284 Choreographer.CALLBACK_ANIMATION, action, null); 12285 } 12286 // Assume that post will succeed later 12287 ViewRootImpl.getRunQueue().removeCallbacks(action); 12288 } 12289 return true; 12290 } 12291 12292 /** 12293 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 12294 * Use this to invalidate the View from a non-UI thread.</p> 12295 * 12296 * <p>This method can be invoked from outside of the UI thread 12297 * only when this View is attached to a window.</p> 12298 * 12299 * @see #invalidate() 12300 * @see #postInvalidateDelayed(long) 12301 */ 12302 public void postInvalidate() { 12303 postInvalidateDelayed(0); 12304 } 12305 12306 /** 12307 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 12308 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 12309 * 12310 * <p>This method can be invoked from outside of the UI thread 12311 * only when this View is attached to a window.</p> 12312 * 12313 * @param left The left coordinate of the rectangle to invalidate. 12314 * @param top The top coordinate of the rectangle to invalidate. 12315 * @param right The right coordinate of the rectangle to invalidate. 12316 * @param bottom The bottom coordinate of the rectangle to invalidate. 12317 * 12318 * @see #invalidate(int, int, int, int) 12319 * @see #invalidate(Rect) 12320 * @see #postInvalidateDelayed(long, int, int, int, int) 12321 */ 12322 public void postInvalidate(int left, int top, int right, int bottom) { 12323 postInvalidateDelayed(0, left, top, right, bottom); 12324 } 12325 12326 /** 12327 * <p>Cause an invalidate to happen on a subsequent cycle through the event 12328 * loop. Waits for the specified amount of time.</p> 12329 * 12330 * <p>This method can be invoked from outside of the UI thread 12331 * only when this View is attached to a window.</p> 12332 * 12333 * @param delayMilliseconds the duration in milliseconds to delay the 12334 * invalidation by 12335 * 12336 * @see #invalidate() 12337 * @see #postInvalidate() 12338 */ 12339 public void postInvalidateDelayed(long delayMilliseconds) { 12340 // We try only with the AttachInfo because there's no point in invalidating 12341 // if we are not attached to our window 12342 final AttachInfo attachInfo = mAttachInfo; 12343 if (attachInfo != null) { 12344 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); 12345 } 12346 } 12347 12348 /** 12349 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 12350 * through the event loop. Waits for the specified amount of time.</p> 12351 * 12352 * <p>This method can be invoked from outside of the UI thread 12353 * only when this View is attached to a window.</p> 12354 * 12355 * @param delayMilliseconds the duration in milliseconds to delay the 12356 * invalidation by 12357 * @param left The left coordinate of the rectangle to invalidate. 12358 * @param top The top coordinate of the rectangle to invalidate. 12359 * @param right The right coordinate of the rectangle to invalidate. 12360 * @param bottom The bottom coordinate of the rectangle to invalidate. 12361 * 12362 * @see #invalidate(int, int, int, int) 12363 * @see #invalidate(Rect) 12364 * @see #postInvalidate(int, int, int, int) 12365 */ 12366 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 12367 int right, int bottom) { 12368 12369 // We try only with the AttachInfo because there's no point in invalidating 12370 // if we are not attached to our window 12371 final AttachInfo attachInfo = mAttachInfo; 12372 if (attachInfo != null) { 12373 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 12374 info.target = this; 12375 info.left = left; 12376 info.top = top; 12377 info.right = right; 12378 info.bottom = bottom; 12379 12380 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); 12381 } 12382 } 12383 12384 /** 12385 * <p>Cause an invalidate to happen on the next animation time step, typically the 12386 * next display frame.</p> 12387 * 12388 * <p>This method can be invoked from outside of the UI thread 12389 * only when this View is attached to a window.</p> 12390 * 12391 * @see #invalidate() 12392 */ 12393 public void postInvalidateOnAnimation() { 12394 // We try only with the AttachInfo because there's no point in invalidating 12395 // if we are not attached to our window 12396 final AttachInfo attachInfo = mAttachInfo; 12397 if (attachInfo != null) { 12398 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); 12399 } 12400 } 12401 12402 /** 12403 * <p>Cause an invalidate of the specified area to happen on the next animation 12404 * time step, typically the next display frame.</p> 12405 * 12406 * <p>This method can be invoked from outside of the UI thread 12407 * only when this View is attached to a window.</p> 12408 * 12409 * @param left The left coordinate of the rectangle to invalidate. 12410 * @param top The top coordinate of the rectangle to invalidate. 12411 * @param right The right coordinate of the rectangle to invalidate. 12412 * @param bottom The bottom coordinate of the rectangle to invalidate. 12413 * 12414 * @see #invalidate(int, int, int, int) 12415 * @see #invalidate(Rect) 12416 */ 12417 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { 12418 // We try only with the AttachInfo because there's no point in invalidating 12419 // if we are not attached to our window 12420 final AttachInfo attachInfo = mAttachInfo; 12421 if (attachInfo != null) { 12422 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 12423 info.target = this; 12424 info.left = left; 12425 info.top = top; 12426 info.right = right; 12427 info.bottom = bottom; 12428 12429 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); 12430 } 12431 } 12432 12433 /** 12434 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 12435 * This event is sent at most once every 12436 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 12437 */ 12438 private void postSendViewScrolledAccessibilityEventCallback() { 12439 if (mSendViewScrolledAccessibilityEvent == null) { 12440 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 12441 } 12442 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 12443 mSendViewScrolledAccessibilityEvent.mIsPending = true; 12444 postDelayed(mSendViewScrolledAccessibilityEvent, 12445 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 12446 } 12447 } 12448 12449 /** 12450 * Called by a parent to request that a child update its values for mScrollX 12451 * and mScrollY if necessary. This will typically be done if the child is 12452 * animating a scroll using a {@link android.widget.Scroller Scroller} 12453 * object. 12454 */ 12455 public void computeScroll() { 12456 } 12457 12458 /** 12459 * <p>Indicate whether the horizontal edges are faded when the view is 12460 * scrolled horizontally.</p> 12461 * 12462 * @return true if the horizontal edges should are faded on scroll, false 12463 * otherwise 12464 * 12465 * @see #setHorizontalFadingEdgeEnabled(boolean) 12466 * 12467 * @attr ref android.R.styleable#View_requiresFadingEdge 12468 */ 12469 public boolean isHorizontalFadingEdgeEnabled() { 12470 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 12471 } 12472 12473 /** 12474 * <p>Define whether the horizontal edges should be faded when this view 12475 * is scrolled horizontally.</p> 12476 * 12477 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 12478 * be faded when the view is scrolled 12479 * horizontally 12480 * 12481 * @see #isHorizontalFadingEdgeEnabled() 12482 * 12483 * @attr ref android.R.styleable#View_requiresFadingEdge 12484 */ 12485 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 12486 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 12487 if (horizontalFadingEdgeEnabled) { 12488 initScrollCache(); 12489 } 12490 12491 mViewFlags ^= FADING_EDGE_HORIZONTAL; 12492 } 12493 } 12494 12495 /** 12496 * <p>Indicate whether the vertical edges are faded when the view is 12497 * scrolled horizontally.</p> 12498 * 12499 * @return true if the vertical edges should are faded on scroll, false 12500 * otherwise 12501 * 12502 * @see #setVerticalFadingEdgeEnabled(boolean) 12503 * 12504 * @attr ref android.R.styleable#View_requiresFadingEdge 12505 */ 12506 public boolean isVerticalFadingEdgeEnabled() { 12507 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 12508 } 12509 12510 /** 12511 * <p>Define whether the vertical edges should be faded when this view 12512 * is scrolled vertically.</p> 12513 * 12514 * @param verticalFadingEdgeEnabled true if the vertical edges should 12515 * be faded when the view is scrolled 12516 * vertically 12517 * 12518 * @see #isVerticalFadingEdgeEnabled() 12519 * 12520 * @attr ref android.R.styleable#View_requiresFadingEdge 12521 */ 12522 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 12523 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 12524 if (verticalFadingEdgeEnabled) { 12525 initScrollCache(); 12526 } 12527 12528 mViewFlags ^= FADING_EDGE_VERTICAL; 12529 } 12530 } 12531 12532 /** 12533 * Returns the strength, or intensity, of the top faded edge. The strength is 12534 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12535 * returns 0.0 or 1.0 but no value in between. 12536 * 12537 * Subclasses should override this method to provide a smoother fade transition 12538 * when scrolling occurs. 12539 * 12540 * @return the intensity of the top fade as a float between 0.0f and 1.0f 12541 */ 12542 protected float getTopFadingEdgeStrength() { 12543 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 12544 } 12545 12546 /** 12547 * Returns the strength, or intensity, of the bottom faded edge. The strength is 12548 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12549 * returns 0.0 or 1.0 but no value in between. 12550 * 12551 * Subclasses should override this method to provide a smoother fade transition 12552 * when scrolling occurs. 12553 * 12554 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 12555 */ 12556 protected float getBottomFadingEdgeStrength() { 12557 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 12558 computeVerticalScrollRange() ? 1.0f : 0.0f; 12559 } 12560 12561 /** 12562 * Returns the strength, or intensity, of the left faded edge. The strength is 12563 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12564 * returns 0.0 or 1.0 but no value in between. 12565 * 12566 * Subclasses should override this method to provide a smoother fade transition 12567 * when scrolling occurs. 12568 * 12569 * @return the intensity of the left fade as a float between 0.0f and 1.0f 12570 */ 12571 protected float getLeftFadingEdgeStrength() { 12572 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 12573 } 12574 12575 /** 12576 * Returns the strength, or intensity, of the right faded edge. The strength is 12577 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12578 * returns 0.0 or 1.0 but no value in between. 12579 * 12580 * Subclasses should override this method to provide a smoother fade transition 12581 * when scrolling occurs. 12582 * 12583 * @return the intensity of the right fade as a float between 0.0f and 1.0f 12584 */ 12585 protected float getRightFadingEdgeStrength() { 12586 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 12587 computeHorizontalScrollRange() ? 1.0f : 0.0f; 12588 } 12589 12590 /** 12591 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 12592 * scrollbar is not drawn by default.</p> 12593 * 12594 * @return true if the horizontal scrollbar should be painted, false 12595 * otherwise 12596 * 12597 * @see #setHorizontalScrollBarEnabled(boolean) 12598 */ 12599 public boolean isHorizontalScrollBarEnabled() { 12600 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 12601 } 12602 12603 /** 12604 * <p>Define whether the horizontal scrollbar should be drawn or not. The 12605 * scrollbar is not drawn by default.</p> 12606 * 12607 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 12608 * be painted 12609 * 12610 * @see #isHorizontalScrollBarEnabled() 12611 */ 12612 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 12613 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 12614 mViewFlags ^= SCROLLBARS_HORIZONTAL; 12615 computeOpaqueFlags(); 12616 resolvePadding(); 12617 } 12618 } 12619 12620 /** 12621 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 12622 * scrollbar is not drawn by default.</p> 12623 * 12624 * @return true if the vertical scrollbar should be painted, false 12625 * otherwise 12626 * 12627 * @see #setVerticalScrollBarEnabled(boolean) 12628 */ 12629 public boolean isVerticalScrollBarEnabled() { 12630 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 12631 } 12632 12633 /** 12634 * <p>Define whether the vertical scrollbar should be drawn or not. The 12635 * scrollbar is not drawn by default.</p> 12636 * 12637 * @param verticalScrollBarEnabled true if the vertical scrollbar should 12638 * be painted 12639 * 12640 * @see #isVerticalScrollBarEnabled() 12641 */ 12642 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 12643 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 12644 mViewFlags ^= SCROLLBARS_VERTICAL; 12645 computeOpaqueFlags(); 12646 resolvePadding(); 12647 } 12648 } 12649 12650 /** 12651 * @hide 12652 */ 12653 protected void recomputePadding() { 12654 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 12655 } 12656 12657 /** 12658 * Define whether scrollbars will fade when the view is not scrolling. 12659 * 12660 * @param fadeScrollbars wheter to enable fading 12661 * 12662 * @attr ref android.R.styleable#View_fadeScrollbars 12663 */ 12664 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 12665 initScrollCache(); 12666 final ScrollabilityCache scrollabilityCache = mScrollCache; 12667 scrollabilityCache.fadeScrollBars = fadeScrollbars; 12668 if (fadeScrollbars) { 12669 scrollabilityCache.state = ScrollabilityCache.OFF; 12670 } else { 12671 scrollabilityCache.state = ScrollabilityCache.ON; 12672 } 12673 } 12674 12675 /** 12676 * 12677 * Returns true if scrollbars will fade when this view is not scrolling 12678 * 12679 * @return true if scrollbar fading is enabled 12680 * 12681 * @attr ref android.R.styleable#View_fadeScrollbars 12682 */ 12683 public boolean isScrollbarFadingEnabled() { 12684 return mScrollCache != null && mScrollCache.fadeScrollBars; 12685 } 12686 12687 /** 12688 * 12689 * Returns the delay before scrollbars fade. 12690 * 12691 * @return the delay before scrollbars fade 12692 * 12693 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 12694 */ 12695 public int getScrollBarDefaultDelayBeforeFade() { 12696 return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() : 12697 mScrollCache.scrollBarDefaultDelayBeforeFade; 12698 } 12699 12700 /** 12701 * Define the delay before scrollbars fade. 12702 * 12703 * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade 12704 * 12705 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 12706 */ 12707 public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) { 12708 getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade; 12709 } 12710 12711 /** 12712 * 12713 * Returns the scrollbar fade duration. 12714 * 12715 * @return the scrollbar fade duration 12716 * 12717 * @attr ref android.R.styleable#View_scrollbarFadeDuration 12718 */ 12719 public int getScrollBarFadeDuration() { 12720 return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() : 12721 mScrollCache.scrollBarFadeDuration; 12722 } 12723 12724 /** 12725 * Define the scrollbar fade duration. 12726 * 12727 * @param scrollBarFadeDuration - the scrollbar fade duration 12728 * 12729 * @attr ref android.R.styleable#View_scrollbarFadeDuration 12730 */ 12731 public void setScrollBarFadeDuration(int scrollBarFadeDuration) { 12732 getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration; 12733 } 12734 12735 /** 12736 * 12737 * Returns the scrollbar size. 12738 * 12739 * @return the scrollbar size 12740 * 12741 * @attr ref android.R.styleable#View_scrollbarSize 12742 */ 12743 public int getScrollBarSize() { 12744 return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() : 12745 mScrollCache.scrollBarSize; 12746 } 12747 12748 /** 12749 * Define the scrollbar size. 12750 * 12751 * @param scrollBarSize - the scrollbar size 12752 * 12753 * @attr ref android.R.styleable#View_scrollbarSize 12754 */ 12755 public void setScrollBarSize(int scrollBarSize) { 12756 getScrollCache().scrollBarSize = scrollBarSize; 12757 } 12758 12759 /** 12760 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 12761 * inset. When inset, they add to the padding of the view. And the scrollbars 12762 * can be drawn inside the padding area or on the edge of the view. For example, 12763 * if a view has a background drawable and you want to draw the scrollbars 12764 * inside the padding specified by the drawable, you can use 12765 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 12766 * appear at the edge of the view, ignoring the padding, then you can use 12767 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 12768 * @param style the style of the scrollbars. Should be one of 12769 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 12770 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 12771 * @see #SCROLLBARS_INSIDE_OVERLAY 12772 * @see #SCROLLBARS_INSIDE_INSET 12773 * @see #SCROLLBARS_OUTSIDE_OVERLAY 12774 * @see #SCROLLBARS_OUTSIDE_INSET 12775 * 12776 * @attr ref android.R.styleable#View_scrollbarStyle 12777 */ 12778 public void setScrollBarStyle(@ScrollBarStyle int style) { 12779 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 12780 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 12781 computeOpaqueFlags(); 12782 resolvePadding(); 12783 } 12784 } 12785 12786 /** 12787 * <p>Returns the current scrollbar style.</p> 12788 * @return the current scrollbar style 12789 * @see #SCROLLBARS_INSIDE_OVERLAY 12790 * @see #SCROLLBARS_INSIDE_INSET 12791 * @see #SCROLLBARS_OUTSIDE_OVERLAY 12792 * @see #SCROLLBARS_OUTSIDE_INSET 12793 * 12794 * @attr ref android.R.styleable#View_scrollbarStyle 12795 */ 12796 @ViewDebug.ExportedProperty(mapping = { 12797 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 12798 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 12799 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 12800 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 12801 }) 12802 @ScrollBarStyle 12803 public int getScrollBarStyle() { 12804 return mViewFlags & SCROLLBARS_STYLE_MASK; 12805 } 12806 12807 /** 12808 * <p>Compute the horizontal range that the horizontal scrollbar 12809 * represents.</p> 12810 * 12811 * <p>The range is expressed in arbitrary units that must be the same as the 12812 * units used by {@link #computeHorizontalScrollExtent()} and 12813 * {@link #computeHorizontalScrollOffset()}.</p> 12814 * 12815 * <p>The default range is the drawing width of this view.</p> 12816 * 12817 * @return the total horizontal range represented by the horizontal 12818 * scrollbar 12819 * 12820 * @see #computeHorizontalScrollExtent() 12821 * @see #computeHorizontalScrollOffset() 12822 * @see android.widget.ScrollBarDrawable 12823 */ 12824 protected int computeHorizontalScrollRange() { 12825 return getWidth(); 12826 } 12827 12828 /** 12829 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 12830 * within the horizontal range. This value is used to compute the position 12831 * of the thumb within the scrollbar's track.</p> 12832 * 12833 * <p>The range is expressed in arbitrary units that must be the same as the 12834 * units used by {@link #computeHorizontalScrollRange()} and 12835 * {@link #computeHorizontalScrollExtent()}.</p> 12836 * 12837 * <p>The default offset is the scroll offset of this view.</p> 12838 * 12839 * @return the horizontal offset of the scrollbar's thumb 12840 * 12841 * @see #computeHorizontalScrollRange() 12842 * @see #computeHorizontalScrollExtent() 12843 * @see android.widget.ScrollBarDrawable 12844 */ 12845 protected int computeHorizontalScrollOffset() { 12846 return mScrollX; 12847 } 12848 12849 /** 12850 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 12851 * within the horizontal range. This value is used to compute the length 12852 * of the thumb within the scrollbar's track.</p> 12853 * 12854 * <p>The range is expressed in arbitrary units that must be the same as the 12855 * units used by {@link #computeHorizontalScrollRange()} and 12856 * {@link #computeHorizontalScrollOffset()}.</p> 12857 * 12858 * <p>The default extent is the drawing width of this view.</p> 12859 * 12860 * @return the horizontal extent of the scrollbar's thumb 12861 * 12862 * @see #computeHorizontalScrollRange() 12863 * @see #computeHorizontalScrollOffset() 12864 * @see android.widget.ScrollBarDrawable 12865 */ 12866 protected int computeHorizontalScrollExtent() { 12867 return getWidth(); 12868 } 12869 12870 /** 12871 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 12872 * 12873 * <p>The range is expressed in arbitrary units that must be the same as the 12874 * units used by {@link #computeVerticalScrollExtent()} and 12875 * {@link #computeVerticalScrollOffset()}.</p> 12876 * 12877 * @return the total vertical range represented by the vertical scrollbar 12878 * 12879 * <p>The default range is the drawing height of this view.</p> 12880 * 12881 * @see #computeVerticalScrollExtent() 12882 * @see #computeVerticalScrollOffset() 12883 * @see android.widget.ScrollBarDrawable 12884 */ 12885 protected int computeVerticalScrollRange() { 12886 return getHeight(); 12887 } 12888 12889 /** 12890 * <p>Compute the vertical offset of the vertical scrollbar's thumb 12891 * within the horizontal range. This value is used to compute the position 12892 * of the thumb within the scrollbar's track.</p> 12893 * 12894 * <p>The range is expressed in arbitrary units that must be the same as the 12895 * units used by {@link #computeVerticalScrollRange()} and 12896 * {@link #computeVerticalScrollExtent()}.</p> 12897 * 12898 * <p>The default offset is the scroll offset of this view.</p> 12899 * 12900 * @return the vertical offset of the scrollbar's thumb 12901 * 12902 * @see #computeVerticalScrollRange() 12903 * @see #computeVerticalScrollExtent() 12904 * @see android.widget.ScrollBarDrawable 12905 */ 12906 protected int computeVerticalScrollOffset() { 12907 return mScrollY; 12908 } 12909 12910 /** 12911 * <p>Compute the vertical extent of the vertical scrollbar's thumb 12912 * within the vertical range. This value is used to compute the length 12913 * of the thumb within the scrollbar's track.</p> 12914 * 12915 * <p>The range is expressed in arbitrary units that must be the same as the 12916 * units used by {@link #computeVerticalScrollRange()} and 12917 * {@link #computeVerticalScrollOffset()}.</p> 12918 * 12919 * <p>The default extent is the drawing height of this view.</p> 12920 * 12921 * @return the vertical extent of the scrollbar's thumb 12922 * 12923 * @see #computeVerticalScrollRange() 12924 * @see #computeVerticalScrollOffset() 12925 * @see android.widget.ScrollBarDrawable 12926 */ 12927 protected int computeVerticalScrollExtent() { 12928 return getHeight(); 12929 } 12930 12931 /** 12932 * Check if this view can be scrolled horizontally in a certain direction. 12933 * 12934 * @param direction Negative to check scrolling left, positive to check scrolling right. 12935 * @return true if this view can be scrolled in the specified direction, false otherwise. 12936 */ 12937 public boolean canScrollHorizontally(int direction) { 12938 final int offset = computeHorizontalScrollOffset(); 12939 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 12940 if (range == 0) return false; 12941 if (direction < 0) { 12942 return offset > 0; 12943 } else { 12944 return offset < range - 1; 12945 } 12946 } 12947 12948 /** 12949 * Check if this view can be scrolled vertically in a certain direction. 12950 * 12951 * @param direction Negative to check scrolling up, positive to check scrolling down. 12952 * @return true if this view can be scrolled in the specified direction, false otherwise. 12953 */ 12954 public boolean canScrollVertically(int direction) { 12955 final int offset = computeVerticalScrollOffset(); 12956 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 12957 if (range == 0) return false; 12958 if (direction < 0) { 12959 return offset > 0; 12960 } else { 12961 return offset < range - 1; 12962 } 12963 } 12964 12965 /** 12966 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 12967 * scrollbars are painted only if they have been awakened first.</p> 12968 * 12969 * @param canvas the canvas on which to draw the scrollbars 12970 * 12971 * @see #awakenScrollBars(int) 12972 */ 12973 protected final void onDrawScrollBars(Canvas canvas) { 12974 // scrollbars are drawn only when the animation is running 12975 final ScrollabilityCache cache = mScrollCache; 12976 if (cache != null) { 12977 12978 int state = cache.state; 12979 12980 if (state == ScrollabilityCache.OFF) { 12981 return; 12982 } 12983 12984 boolean invalidate = false; 12985 12986 if (state == ScrollabilityCache.FADING) { 12987 // We're fading -- get our fade interpolation 12988 if (cache.interpolatorValues == null) { 12989 cache.interpolatorValues = new float[1]; 12990 } 12991 12992 float[] values = cache.interpolatorValues; 12993 12994 // Stops the animation if we're done 12995 if (cache.scrollBarInterpolator.timeToValues(values) == 12996 Interpolator.Result.FREEZE_END) { 12997 cache.state = ScrollabilityCache.OFF; 12998 } else { 12999 cache.scrollBar.setAlpha(Math.round(values[0])); 13000 } 13001 13002 // This will make the scroll bars inval themselves after 13003 // drawing. We only want this when we're fading so that 13004 // we prevent excessive redraws 13005 invalidate = true; 13006 } else { 13007 // We're just on -- but we may have been fading before so 13008 // reset alpha 13009 cache.scrollBar.setAlpha(255); 13010 } 13011 13012 13013 final int viewFlags = mViewFlags; 13014 13015 final boolean drawHorizontalScrollBar = 13016 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 13017 final boolean drawVerticalScrollBar = 13018 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 13019 && !isVerticalScrollBarHidden(); 13020 13021 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 13022 final int width = mRight - mLeft; 13023 final int height = mBottom - mTop; 13024 13025 final ScrollBarDrawable scrollBar = cache.scrollBar; 13026 13027 final int scrollX = mScrollX; 13028 final int scrollY = mScrollY; 13029 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 13030 13031 int left; 13032 int top; 13033 int right; 13034 int bottom; 13035 13036 if (drawHorizontalScrollBar) { 13037 int size = scrollBar.getSize(false); 13038 if (size <= 0) { 13039 size = cache.scrollBarSize; 13040 } 13041 13042 scrollBar.setParameters(computeHorizontalScrollRange(), 13043 computeHorizontalScrollOffset(), 13044 computeHorizontalScrollExtent(), false); 13045 final int verticalScrollBarGap = drawVerticalScrollBar ? 13046 getVerticalScrollbarWidth() : 0; 13047 top = scrollY + height - size - (mUserPaddingBottom & inside); 13048 left = scrollX + (mPaddingLeft & inside); 13049 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 13050 bottom = top + size; 13051 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 13052 if (invalidate) { 13053 invalidate(left, top, right, bottom); 13054 } 13055 } 13056 13057 if (drawVerticalScrollBar) { 13058 int size = scrollBar.getSize(true); 13059 if (size <= 0) { 13060 size = cache.scrollBarSize; 13061 } 13062 13063 scrollBar.setParameters(computeVerticalScrollRange(), 13064 computeVerticalScrollOffset(), 13065 computeVerticalScrollExtent(), true); 13066 int verticalScrollbarPosition = mVerticalScrollbarPosition; 13067 if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) { 13068 verticalScrollbarPosition = isLayoutRtl() ? 13069 SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT; 13070 } 13071 switch (verticalScrollbarPosition) { 13072 default: 13073 case SCROLLBAR_POSITION_RIGHT: 13074 left = scrollX + width - size - (mUserPaddingRight & inside); 13075 break; 13076 case SCROLLBAR_POSITION_LEFT: 13077 left = scrollX + (mUserPaddingLeft & inside); 13078 break; 13079 } 13080 top = scrollY + (mPaddingTop & inside); 13081 right = left + size; 13082 bottom = scrollY + height - (mUserPaddingBottom & inside); 13083 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 13084 if (invalidate) { 13085 invalidate(left, top, right, bottom); 13086 } 13087 } 13088 } 13089 } 13090 } 13091 13092 /** 13093 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 13094 * FastScroller is visible. 13095 * @return whether to temporarily hide the vertical scrollbar 13096 * @hide 13097 */ 13098 protected boolean isVerticalScrollBarHidden() { 13099 return false; 13100 } 13101 13102 /** 13103 * <p>Draw the horizontal scrollbar if 13104 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 13105 * 13106 * @param canvas the canvas on which to draw the scrollbar 13107 * @param scrollBar the scrollbar's drawable 13108 * 13109 * @see #isHorizontalScrollBarEnabled() 13110 * @see #computeHorizontalScrollRange() 13111 * @see #computeHorizontalScrollExtent() 13112 * @see #computeHorizontalScrollOffset() 13113 * @see android.widget.ScrollBarDrawable 13114 * @hide 13115 */ 13116 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 13117 int l, int t, int r, int b) { 13118 scrollBar.setBounds(l, t, r, b); 13119 scrollBar.draw(canvas); 13120 } 13121 13122 /** 13123 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 13124 * returns true.</p> 13125 * 13126 * @param canvas the canvas on which to draw the scrollbar 13127 * @param scrollBar the scrollbar's drawable 13128 * 13129 * @see #isVerticalScrollBarEnabled() 13130 * @see #computeVerticalScrollRange() 13131 * @see #computeVerticalScrollExtent() 13132 * @see #computeVerticalScrollOffset() 13133 * @see android.widget.ScrollBarDrawable 13134 * @hide 13135 */ 13136 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 13137 int l, int t, int r, int b) { 13138 scrollBar.setBounds(l, t, r, b); 13139 scrollBar.draw(canvas); 13140 } 13141 13142 /** 13143 * Implement this to do your drawing. 13144 * 13145 * @param canvas the canvas on which the background will be drawn 13146 */ 13147 protected void onDraw(Canvas canvas) { 13148 } 13149 13150 /* 13151 * Caller is responsible for calling requestLayout if necessary. 13152 * (This allows addViewInLayout to not request a new layout.) 13153 */ 13154 void assignParent(ViewParent parent) { 13155 if (mParent == null) { 13156 mParent = parent; 13157 } else if (parent == null) { 13158 mParent = null; 13159 } else { 13160 throw new RuntimeException("view " + this + " being added, but" 13161 + " it already has a parent"); 13162 } 13163 } 13164 13165 /** 13166 * This is called when the view is attached to a window. At this point it 13167 * has a Surface and will start drawing. Note that this function is 13168 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 13169 * however it may be called any time before the first onDraw -- including 13170 * before or after {@link #onMeasure(int, int)}. 13171 * 13172 * @see #onDetachedFromWindow() 13173 */ 13174 protected void onAttachedToWindow() { 13175 if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 13176 mParent.requestTransparentRegion(this); 13177 } 13178 13179 if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { 13180 initialAwakenScrollBars(); 13181 mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 13182 } 13183 13184 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 13185 13186 jumpDrawablesToCurrentState(); 13187 13188 resetSubtreeAccessibilityStateChanged(); 13189 13190 // rebuild, since Outline not maintained while View is detached 13191 rebuildOutline(); 13192 13193 if (isFocused()) { 13194 InputMethodManager imm = InputMethodManager.peekInstance(); 13195 imm.focusIn(this); 13196 } 13197 } 13198 13199 /** 13200 * Resolve all RTL related properties. 13201 * 13202 * @return true if resolution of RTL properties has been done 13203 * 13204 * @hide 13205 */ 13206 public boolean resolveRtlPropertiesIfNeeded() { 13207 if (!needRtlPropertiesResolution()) return false; 13208 13209 // Order is important here: LayoutDirection MUST be resolved first 13210 if (!isLayoutDirectionResolved()) { 13211 resolveLayoutDirection(); 13212 resolveLayoutParams(); 13213 } 13214 // ... then we can resolve the others properties depending on the resolved LayoutDirection. 13215 if (!isTextDirectionResolved()) { 13216 resolveTextDirection(); 13217 } 13218 if (!isTextAlignmentResolved()) { 13219 resolveTextAlignment(); 13220 } 13221 // Should resolve Drawables before Padding because we need the layout direction of the 13222 // Drawable to correctly resolve Padding. 13223 if (!areDrawablesResolved()) { 13224 resolveDrawables(); 13225 } 13226 if (!isPaddingResolved()) { 13227 resolvePadding(); 13228 } 13229 onRtlPropertiesChanged(getLayoutDirection()); 13230 return true; 13231 } 13232 13233 /** 13234 * Reset resolution of all RTL related properties. 13235 * 13236 * @hide 13237 */ 13238 public void resetRtlProperties() { 13239 resetResolvedLayoutDirection(); 13240 resetResolvedTextDirection(); 13241 resetResolvedTextAlignment(); 13242 resetResolvedPadding(); 13243 resetResolvedDrawables(); 13244 } 13245 13246 /** 13247 * @see #onScreenStateChanged(int) 13248 */ 13249 void dispatchScreenStateChanged(int screenState) { 13250 onScreenStateChanged(screenState); 13251 } 13252 13253 /** 13254 * This method is called whenever the state of the screen this view is 13255 * attached to changes. A state change will usually occurs when the screen 13256 * turns on or off (whether it happens automatically or the user does it 13257 * manually.) 13258 * 13259 * @param screenState The new state of the screen. Can be either 13260 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF} 13261 */ 13262 public void onScreenStateChanged(int screenState) { 13263 } 13264 13265 /** 13266 * Return true if the application tag in the AndroidManifest has set "supportRtl" to true 13267 */ 13268 private boolean hasRtlSupport() { 13269 return mContext.getApplicationInfo().hasRtlSupport(); 13270 } 13271 13272 /** 13273 * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or 13274 * RTL not supported) 13275 */ 13276 private boolean isRtlCompatibilityMode() { 13277 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 13278 return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport(); 13279 } 13280 13281 /** 13282 * @return true if RTL properties need resolution. 13283 * 13284 */ 13285 private boolean needRtlPropertiesResolution() { 13286 return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED; 13287 } 13288 13289 /** 13290 * Called when any RTL property (layout direction or text direction or text alignment) has 13291 * been changed. 13292 * 13293 * Subclasses need to override this method to take care of cached information that depends on the 13294 * resolved layout direction, or to inform child views that inherit their layout direction. 13295 * 13296 * The default implementation does nothing. 13297 * 13298 * @param layoutDirection the direction of the layout 13299 * 13300 * @see #LAYOUT_DIRECTION_LTR 13301 * @see #LAYOUT_DIRECTION_RTL 13302 */ 13303 public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) { 13304 } 13305 13306 /** 13307 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 13308 * that the parent directionality can and will be resolved before its children. 13309 * 13310 * @return true if resolution has been done, false otherwise. 13311 * 13312 * @hide 13313 */ 13314 public boolean resolveLayoutDirection() { 13315 // Clear any previous layout direction resolution 13316 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 13317 13318 if (hasRtlSupport()) { 13319 // Set resolved depending on layout direction 13320 switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> 13321 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) { 13322 case LAYOUT_DIRECTION_INHERIT: 13323 // We cannot resolve yet. LTR is by default and let the resolution happen again 13324 // later to get the correct resolved value 13325 if (!canResolveLayoutDirection()) return false; 13326 13327 // Parent has not yet resolved, LTR is still the default 13328 try { 13329 if (!mParent.isLayoutDirectionResolved()) return false; 13330 13331 if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 13332 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 13333 } 13334 } catch (AbstractMethodError e) { 13335 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 13336 " does not fully implement ViewParent", e); 13337 } 13338 break; 13339 case LAYOUT_DIRECTION_RTL: 13340 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 13341 break; 13342 case LAYOUT_DIRECTION_LOCALE: 13343 if((LAYOUT_DIRECTION_RTL == 13344 TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) { 13345 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 13346 } 13347 break; 13348 default: 13349 // Nothing to do, LTR by default 13350 } 13351 } 13352 13353 // Set to resolved 13354 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 13355 return true; 13356 } 13357 13358 /** 13359 * Check if layout direction resolution can be done. 13360 * 13361 * @return true if layout direction resolution can be done otherwise return false. 13362 */ 13363 public boolean canResolveLayoutDirection() { 13364 switch (getRawLayoutDirection()) { 13365 case LAYOUT_DIRECTION_INHERIT: 13366 if (mParent != null) { 13367 try { 13368 return mParent.canResolveLayoutDirection(); 13369 } catch (AbstractMethodError e) { 13370 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 13371 " does not fully implement ViewParent", e); 13372 } 13373 } 13374 return false; 13375 13376 default: 13377 return true; 13378 } 13379 } 13380 13381 /** 13382 * Reset the resolved layout direction. Layout direction will be resolved during a call to 13383 * {@link #onMeasure(int, int)}. 13384 * 13385 * @hide 13386 */ 13387 public void resetResolvedLayoutDirection() { 13388 // Reset the current resolved bits 13389 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 13390 } 13391 13392 /** 13393 * @return true if the layout direction is inherited. 13394 * 13395 * @hide 13396 */ 13397 public boolean isLayoutDirectionInherited() { 13398 return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT); 13399 } 13400 13401 /** 13402 * @return true if layout direction has been resolved. 13403 */ 13404 public boolean isLayoutDirectionResolved() { 13405 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED; 13406 } 13407 13408 /** 13409 * Return if padding has been resolved 13410 * 13411 * @hide 13412 */ 13413 boolean isPaddingResolved() { 13414 return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED; 13415 } 13416 13417 /** 13418 * Resolves padding depending on layout direction, if applicable, and 13419 * recomputes internal padding values to adjust for scroll bars. 13420 * 13421 * @hide 13422 */ 13423 public void resolvePadding() { 13424 final int resolvedLayoutDirection = getLayoutDirection(); 13425 13426 if (!isRtlCompatibilityMode()) { 13427 // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account. 13428 // If start / end padding are defined, they will be resolved (hence overriding) to 13429 // left / right or right / left depending on the resolved layout direction. 13430 // If start / end padding are not defined, use the left / right ones. 13431 if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) { 13432 Rect padding = sThreadLocal.get(); 13433 if (padding == null) { 13434 padding = new Rect(); 13435 sThreadLocal.set(padding); 13436 } 13437 mBackground.getPadding(padding); 13438 if (!mLeftPaddingDefined) { 13439 mUserPaddingLeftInitial = padding.left; 13440 } 13441 if (!mRightPaddingDefined) { 13442 mUserPaddingRightInitial = padding.right; 13443 } 13444 } 13445 switch (resolvedLayoutDirection) { 13446 case LAYOUT_DIRECTION_RTL: 13447 if (mUserPaddingStart != UNDEFINED_PADDING) { 13448 mUserPaddingRight = mUserPaddingStart; 13449 } else { 13450 mUserPaddingRight = mUserPaddingRightInitial; 13451 } 13452 if (mUserPaddingEnd != UNDEFINED_PADDING) { 13453 mUserPaddingLeft = mUserPaddingEnd; 13454 } else { 13455 mUserPaddingLeft = mUserPaddingLeftInitial; 13456 } 13457 break; 13458 case LAYOUT_DIRECTION_LTR: 13459 default: 13460 if (mUserPaddingStart != UNDEFINED_PADDING) { 13461 mUserPaddingLeft = mUserPaddingStart; 13462 } else { 13463 mUserPaddingLeft = mUserPaddingLeftInitial; 13464 } 13465 if (mUserPaddingEnd != UNDEFINED_PADDING) { 13466 mUserPaddingRight = mUserPaddingEnd; 13467 } else { 13468 mUserPaddingRight = mUserPaddingRightInitial; 13469 } 13470 } 13471 13472 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 13473 } 13474 13475 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 13476 onRtlPropertiesChanged(resolvedLayoutDirection); 13477 13478 mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED; 13479 } 13480 13481 /** 13482 * Reset the resolved layout direction. 13483 * 13484 * @hide 13485 */ 13486 public void resetResolvedPadding() { 13487 resetResolvedPaddingInternal(); 13488 } 13489 13490 /** 13491 * Used when we only want to reset *this* view's padding and not trigger overrides 13492 * in ViewGroup that reset children too. 13493 */ 13494 void resetResolvedPaddingInternal() { 13495 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 13496 } 13497 13498 /** 13499 * This is called when the view is detached from a window. At this point it 13500 * no longer has a surface for drawing. 13501 * 13502 * @see #onAttachedToWindow() 13503 */ 13504 protected void onDetachedFromWindow() { 13505 } 13506 13507 /** 13508 * This is a framework-internal mirror of onDetachedFromWindow() that's called 13509 * after onDetachedFromWindow(). 13510 * 13511 * If you override this you *MUST* call super.onDetachedFromWindowInternal()! 13512 * The super method should be called at the end of the overriden method to ensure 13513 * subclasses are destroyed first 13514 * 13515 * @hide 13516 */ 13517 protected void onDetachedFromWindowInternal() { 13518 mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT; 13519 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 13520 13521 removeUnsetPressCallback(); 13522 removeLongPressCallback(); 13523 removePerformClickCallback(); 13524 removeSendViewScrolledAccessibilityEventCallback(); 13525 stopNestedScroll(); 13526 13527 // Anything that started animating right before detach should already 13528 // be in its final state when re-attached. 13529 jumpDrawablesToCurrentState(); 13530 13531 destroyDrawingCache(); 13532 13533 cleanupDraw(); 13534 mCurrentAnimation = null; 13535 } 13536 13537 private void cleanupDraw() { 13538 resetDisplayList(); 13539 if (mAttachInfo != null) { 13540 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 13541 } 13542 } 13543 13544 void invalidateInheritedLayoutMode(int layoutModeOfRoot) { 13545 } 13546 13547 /** 13548 * @return The number of times this view has been attached to a window 13549 */ 13550 protected int getWindowAttachCount() { 13551 return mWindowAttachCount; 13552 } 13553 13554 /** 13555 * Retrieve a unique token identifying the window this view is attached to. 13556 * @return Return the window's token for use in 13557 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 13558 */ 13559 public IBinder getWindowToken() { 13560 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 13561 } 13562 13563 /** 13564 * Retrieve the {@link WindowId} for the window this view is 13565 * currently attached to. 13566 */ 13567 public WindowId getWindowId() { 13568 if (mAttachInfo == null) { 13569 return null; 13570 } 13571 if (mAttachInfo.mWindowId == null) { 13572 try { 13573 mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId( 13574 mAttachInfo.mWindowToken); 13575 mAttachInfo.mWindowId = new WindowId( 13576 mAttachInfo.mIWindowId); 13577 } catch (RemoteException e) { 13578 } 13579 } 13580 return mAttachInfo.mWindowId; 13581 } 13582 13583 /** 13584 * Retrieve a unique token identifying the top-level "real" window of 13585 * the window that this view is attached to. That is, this is like 13586 * {@link #getWindowToken}, except if the window this view in is a panel 13587 * window (attached to another containing window), then the token of 13588 * the containing window is returned instead. 13589 * 13590 * @return Returns the associated window token, either 13591 * {@link #getWindowToken()} or the containing window's token. 13592 */ 13593 public IBinder getApplicationWindowToken() { 13594 AttachInfo ai = mAttachInfo; 13595 if (ai != null) { 13596 IBinder appWindowToken = ai.mPanelParentWindowToken; 13597 if (appWindowToken == null) { 13598 appWindowToken = ai.mWindowToken; 13599 } 13600 return appWindowToken; 13601 } 13602 return null; 13603 } 13604 13605 /** 13606 * Gets the logical display to which the view's window has been attached. 13607 * 13608 * @return The logical display, or null if the view is not currently attached to a window. 13609 */ 13610 public Display getDisplay() { 13611 return mAttachInfo != null ? mAttachInfo.mDisplay : null; 13612 } 13613 13614 /** 13615 * Retrieve private session object this view hierarchy is using to 13616 * communicate with the window manager. 13617 * @return the session object to communicate with the window manager 13618 */ 13619 /*package*/ IWindowSession getWindowSession() { 13620 return mAttachInfo != null ? mAttachInfo.mSession : null; 13621 } 13622 13623 /** 13624 * @param info the {@link android.view.View.AttachInfo} to associated with 13625 * this view 13626 */ 13627 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 13628 //System.out.println("Attached! " + this); 13629 mAttachInfo = info; 13630 if (mOverlay != null) { 13631 mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility); 13632 } 13633 mWindowAttachCount++; 13634 // We will need to evaluate the drawable state at least once. 13635 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 13636 if (mFloatingTreeObserver != null) { 13637 info.mTreeObserver.merge(mFloatingTreeObserver); 13638 mFloatingTreeObserver = null; 13639 } 13640 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) { 13641 mAttachInfo.mScrollContainers.add(this); 13642 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 13643 } 13644 performCollectViewAttributes(mAttachInfo, visibility); 13645 onAttachedToWindow(); 13646 13647 ListenerInfo li = mListenerInfo; 13648 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 13649 li != null ? li.mOnAttachStateChangeListeners : null; 13650 if (listeners != null && listeners.size() > 0) { 13651 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 13652 // perform the dispatching. The iterator is a safe guard against listeners that 13653 // could mutate the list by calling the various add/remove methods. This prevents 13654 // the array from being modified while we iterate it. 13655 for (OnAttachStateChangeListener listener : listeners) { 13656 listener.onViewAttachedToWindow(this); 13657 } 13658 } 13659 13660 int vis = info.mWindowVisibility; 13661 if (vis != GONE) { 13662 onWindowVisibilityChanged(vis); 13663 } 13664 if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) { 13665 // If nobody has evaluated the drawable state yet, then do it now. 13666 refreshDrawableState(); 13667 } 13668 needGlobalAttributesUpdate(false); 13669 } 13670 13671 void dispatchDetachedFromWindow() { 13672 AttachInfo info = mAttachInfo; 13673 if (info != null) { 13674 int vis = info.mWindowVisibility; 13675 if (vis != GONE) { 13676 onWindowVisibilityChanged(GONE); 13677 } 13678 } 13679 13680 onDetachedFromWindow(); 13681 onDetachedFromWindowInternal(); 13682 13683 ListenerInfo li = mListenerInfo; 13684 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 13685 li != null ? li.mOnAttachStateChangeListeners : null; 13686 if (listeners != null && listeners.size() > 0) { 13687 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 13688 // perform the dispatching. The iterator is a safe guard against listeners that 13689 // could mutate the list by calling the various add/remove methods. This prevents 13690 // the array from being modified while we iterate it. 13691 for (OnAttachStateChangeListener listener : listeners) { 13692 listener.onViewDetachedFromWindow(this); 13693 } 13694 } 13695 13696 if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 13697 mAttachInfo.mScrollContainers.remove(this); 13698 mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED; 13699 } 13700 13701 mAttachInfo = null; 13702 if (mOverlay != null) { 13703 mOverlay.getOverlayView().dispatchDetachedFromWindow(); 13704 } 13705 } 13706 13707 /** 13708 * Cancel any deferred high-level input events that were previously posted to the event queue. 13709 * 13710 * <p>Many views post high-level events such as click handlers to the event queue 13711 * to run deferred in order to preserve a desired user experience - clearing visible 13712 * pressed states before executing, etc. This method will abort any events of this nature 13713 * that are currently in flight.</p> 13714 * 13715 * <p>Custom views that generate their own high-level deferred input events should override 13716 * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p> 13717 * 13718 * <p>This will also cancel pending input events for any child views.</p> 13719 * 13720 * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases. 13721 * This will not impact newer events posted after this call that may occur as a result of 13722 * lower-level input events still waiting in the queue. If you are trying to prevent 13723 * double-submitted events for the duration of some sort of asynchronous transaction 13724 * you should also take other steps to protect against unexpected double inputs e.g. calling 13725 * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when 13726 * the transaction completes, tracking already submitted transaction IDs, etc.</p> 13727 */ 13728 public final void cancelPendingInputEvents() { 13729 dispatchCancelPendingInputEvents(); 13730 } 13731 13732 /** 13733 * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight. 13734 * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling. 13735 */ 13736 void dispatchCancelPendingInputEvents() { 13737 mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER; 13738 onCancelPendingInputEvents(); 13739 if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) { 13740 throw new SuperNotCalledException("View " + getClass().getSimpleName() + 13741 " did not call through to super.onCancelPendingInputEvents()"); 13742 } 13743 } 13744 13745 /** 13746 * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or 13747 * a parent view. 13748 * 13749 * <p>This method is responsible for removing any pending high-level input events that were 13750 * posted to the event queue to run later. Custom view classes that post their own deferred 13751 * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or 13752 * {@link android.os.Handler} should override this method, call 13753 * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate. 13754 * </p> 13755 */ 13756 public void onCancelPendingInputEvents() { 13757 removePerformClickCallback(); 13758 cancelLongPress(); 13759 mPrivateFlags3 |= PFLAG3_CALLED_SUPER; 13760 } 13761 13762 /** 13763 * Store this view hierarchy's frozen state into the given container. 13764 * 13765 * @param container The SparseArray in which to save the view's state. 13766 * 13767 * @see #restoreHierarchyState(android.util.SparseArray) 13768 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13769 * @see #onSaveInstanceState() 13770 */ 13771 public void saveHierarchyState(SparseArray<Parcelable> container) { 13772 dispatchSaveInstanceState(container); 13773 } 13774 13775 /** 13776 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 13777 * this view and its children. May be overridden to modify how freezing happens to a 13778 * view's children; for example, some views may want to not store state for their children. 13779 * 13780 * @param container The SparseArray in which to save the view's state. 13781 * 13782 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13783 * @see #saveHierarchyState(android.util.SparseArray) 13784 * @see #onSaveInstanceState() 13785 */ 13786 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 13787 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 13788 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 13789 Parcelable state = onSaveInstanceState(); 13790 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 13791 throw new IllegalStateException( 13792 "Derived class did not call super.onSaveInstanceState()"); 13793 } 13794 if (state != null) { 13795 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 13796 // + ": " + state); 13797 container.put(mID, state); 13798 } 13799 } 13800 } 13801 13802 /** 13803 * Hook allowing a view to generate a representation of its internal state 13804 * that can later be used to create a new instance with that same state. 13805 * This state should only contain information that is not persistent or can 13806 * not be reconstructed later. For example, you will never store your 13807 * current position on screen because that will be computed again when a 13808 * new instance of the view is placed in its view hierarchy. 13809 * <p> 13810 * Some examples of things you may store here: the current cursor position 13811 * in a text view (but usually not the text itself since that is stored in a 13812 * content provider or other persistent storage), the currently selected 13813 * item in a list view. 13814 * 13815 * @return Returns a Parcelable object containing the view's current dynamic 13816 * state, or null if there is nothing interesting to save. The 13817 * default implementation returns null. 13818 * @see #onRestoreInstanceState(android.os.Parcelable) 13819 * @see #saveHierarchyState(android.util.SparseArray) 13820 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13821 * @see #setSaveEnabled(boolean) 13822 */ 13823 protected Parcelable onSaveInstanceState() { 13824 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 13825 return BaseSavedState.EMPTY_STATE; 13826 } 13827 13828 /** 13829 * Restore this view hierarchy's frozen state from the given container. 13830 * 13831 * @param container The SparseArray which holds previously frozen states. 13832 * 13833 * @see #saveHierarchyState(android.util.SparseArray) 13834 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13835 * @see #onRestoreInstanceState(android.os.Parcelable) 13836 */ 13837 public void restoreHierarchyState(SparseArray<Parcelable> container) { 13838 dispatchRestoreInstanceState(container); 13839 } 13840 13841 /** 13842 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 13843 * state for this view and its children. May be overridden to modify how restoring 13844 * happens to a view's children; for example, some views may want to not store state 13845 * for their children. 13846 * 13847 * @param container The SparseArray which holds previously saved state. 13848 * 13849 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13850 * @see #restoreHierarchyState(android.util.SparseArray) 13851 * @see #onRestoreInstanceState(android.os.Parcelable) 13852 */ 13853 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 13854 if (mID != NO_ID) { 13855 Parcelable state = container.get(mID); 13856 if (state != null) { 13857 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 13858 // + ": " + state); 13859 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 13860 onRestoreInstanceState(state); 13861 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 13862 throw new IllegalStateException( 13863 "Derived class did not call super.onRestoreInstanceState()"); 13864 } 13865 } 13866 } 13867 } 13868 13869 /** 13870 * Hook allowing a view to re-apply a representation of its internal state that had previously 13871 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 13872 * null state. 13873 * 13874 * @param state The frozen state that had previously been returned by 13875 * {@link #onSaveInstanceState}. 13876 * 13877 * @see #onSaveInstanceState() 13878 * @see #restoreHierarchyState(android.util.SparseArray) 13879 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13880 */ 13881 protected void onRestoreInstanceState(Parcelable state) { 13882 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 13883 if (state != BaseSavedState.EMPTY_STATE && state != null) { 13884 throw new IllegalArgumentException("Wrong state class, expecting View State but " 13885 + "received " + state.getClass().toString() + " instead. This usually happens " 13886 + "when two views of different type have the same id in the same hierarchy. " 13887 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 13888 + "other views do not use the same id."); 13889 } 13890 } 13891 13892 /** 13893 * <p>Return the time at which the drawing of the view hierarchy started.</p> 13894 * 13895 * @return the drawing start time in milliseconds 13896 */ 13897 public long getDrawingTime() { 13898 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 13899 } 13900 13901 /** 13902 * <p>Enables or disables the duplication of the parent's state into this view. When 13903 * duplication is enabled, this view gets its drawable state from its parent rather 13904 * than from its own internal properties.</p> 13905 * 13906 * <p>Note: in the current implementation, setting this property to true after the 13907 * view was added to a ViewGroup might have no effect at all. This property should 13908 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 13909 * 13910 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 13911 * property is enabled, an exception will be thrown.</p> 13912 * 13913 * <p>Note: if the child view uses and updates additionnal states which are unknown to the 13914 * parent, these states should not be affected by this method.</p> 13915 * 13916 * @param enabled True to enable duplication of the parent's drawable state, false 13917 * to disable it. 13918 * 13919 * @see #getDrawableState() 13920 * @see #isDuplicateParentStateEnabled() 13921 */ 13922 public void setDuplicateParentStateEnabled(boolean enabled) { 13923 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 13924 } 13925 13926 /** 13927 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 13928 * 13929 * @return True if this view's drawable state is duplicated from the parent, 13930 * false otherwise 13931 * 13932 * @see #getDrawableState() 13933 * @see #setDuplicateParentStateEnabled(boolean) 13934 */ 13935 public boolean isDuplicateParentStateEnabled() { 13936 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 13937 } 13938 13939 /** 13940 * <p>Specifies the type of layer backing this view. The layer can be 13941 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13942 * {@link #LAYER_TYPE_HARDWARE}.</p> 13943 * 13944 * <p>A layer is associated with an optional {@link android.graphics.Paint} 13945 * instance that controls how the layer is composed on screen. The following 13946 * properties of the paint are taken into account when composing the layer:</p> 13947 * <ul> 13948 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 13949 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 13950 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 13951 * </ul> 13952 * 13953 * <p>If this view has an alpha value set to < 1.0 by calling 13954 * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded 13955 * by this view's alpha value.</p> 13956 * 13957 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE}, 13958 * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE} 13959 * for more information on when and how to use layers.</p> 13960 * 13961 * @param layerType The type of layer to use with this view, must be one of 13962 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13963 * {@link #LAYER_TYPE_HARDWARE} 13964 * @param paint The paint used to compose the layer. This argument is optional 13965 * and can be null. It is ignored when the layer type is 13966 * {@link #LAYER_TYPE_NONE} 13967 * 13968 * @see #getLayerType() 13969 * @see #LAYER_TYPE_NONE 13970 * @see #LAYER_TYPE_SOFTWARE 13971 * @see #LAYER_TYPE_HARDWARE 13972 * @see #setAlpha(float) 13973 * 13974 * @attr ref android.R.styleable#View_layerType 13975 */ 13976 public void setLayerType(int layerType, Paint paint) { 13977 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 13978 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 13979 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 13980 } 13981 13982 boolean typeChanged = mRenderNode.setLayerType(layerType); 13983 13984 if (!typeChanged) { 13985 setLayerPaint(paint); 13986 return; 13987 } 13988 13989 // Destroy any previous software drawing cache if needed 13990 if (mLayerType == LAYER_TYPE_SOFTWARE) { 13991 destroyDrawingCache(); 13992 } 13993 13994 mLayerType = layerType; 13995 final boolean layerDisabled = (mLayerType == LAYER_TYPE_NONE); 13996 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 13997 mRenderNode.setLayerPaint(mLayerPaint); 13998 13999 // draw() behaves differently if we are on a layer, so we need to 14000 // invalidate() here 14001 invalidateParentCaches(); 14002 invalidate(true); 14003 } 14004 14005 /** 14006 * Updates the {@link Paint} object used with the current layer (used only if the current 14007 * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint 14008 * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time 14009 * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to 14010 * ensure that the view gets redrawn immediately. 14011 * 14012 * <p>A layer is associated with an optional {@link android.graphics.Paint} 14013 * instance that controls how the layer is composed on screen. The following 14014 * properties of the paint are taken into account when composing the layer:</p> 14015 * <ul> 14016 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 14017 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 14018 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 14019 * </ul> 14020 * 14021 * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the 14022 * alpha value of the layer's paint is superceded by this view's alpha value.</p> 14023 * 14024 * @param paint The paint used to compose the layer. This argument is optional 14025 * and can be null. It is ignored when the layer type is 14026 * {@link #LAYER_TYPE_NONE} 14027 * 14028 * @see #setLayerType(int, android.graphics.Paint) 14029 */ 14030 public void setLayerPaint(Paint paint) { 14031 int layerType = getLayerType(); 14032 if (layerType != LAYER_TYPE_NONE) { 14033 mLayerPaint = paint == null ? new Paint() : paint; 14034 if (layerType == LAYER_TYPE_HARDWARE) { 14035 if (mRenderNode.setLayerPaint(mLayerPaint)) { 14036 invalidateViewProperty(false, false); 14037 } 14038 } else { 14039 invalidate(); 14040 } 14041 } 14042 } 14043 14044 /** 14045 * Indicates whether this view has a static layer. A view with layer type 14046 * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are 14047 * dynamic. 14048 */ 14049 boolean hasStaticLayer() { 14050 return true; 14051 } 14052 14053 /** 14054 * Indicates what type of layer is currently associated with this view. By default 14055 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 14056 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 14057 * for more information on the different types of layers. 14058 * 14059 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 14060 * {@link #LAYER_TYPE_HARDWARE} 14061 * 14062 * @see #setLayerType(int, android.graphics.Paint) 14063 * @see #buildLayer() 14064 * @see #LAYER_TYPE_NONE 14065 * @see #LAYER_TYPE_SOFTWARE 14066 * @see #LAYER_TYPE_HARDWARE 14067 */ 14068 public int getLayerType() { 14069 return mLayerType; 14070 } 14071 14072 /** 14073 * Forces this view's layer to be created and this view to be rendered 14074 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 14075 * invoking this method will have no effect. 14076 * 14077 * This method can for instance be used to render a view into its layer before 14078 * starting an animation. If this view is complex, rendering into the layer 14079 * before starting the animation will avoid skipping frames. 14080 * 14081 * @throws IllegalStateException If this view is not attached to a window 14082 * 14083 * @see #setLayerType(int, android.graphics.Paint) 14084 */ 14085 public void buildLayer() { 14086 if (mLayerType == LAYER_TYPE_NONE) return; 14087 14088 final AttachInfo attachInfo = mAttachInfo; 14089 if (attachInfo == null) { 14090 throw new IllegalStateException("This view must be attached to a window first"); 14091 } 14092 14093 if (getWidth() == 0 || getHeight() == 0) { 14094 return; 14095 } 14096 14097 switch (mLayerType) { 14098 case LAYER_TYPE_HARDWARE: 14099 updateDisplayListIfDirty(); 14100 if (attachInfo.mHardwareRenderer != null && mRenderNode.isValid()) { 14101 attachInfo.mHardwareRenderer.buildLayer(mRenderNode); 14102 } 14103 break; 14104 case LAYER_TYPE_SOFTWARE: 14105 buildDrawingCache(true); 14106 break; 14107 } 14108 } 14109 14110 /** 14111 * If this View draws with a HardwareLayer, returns it. 14112 * Otherwise returns null 14113 * 14114 * TODO: Only TextureView uses this, can we eliminate it? 14115 */ 14116 HardwareLayer getHardwareLayer() { 14117 return null; 14118 } 14119 14120 /** 14121 * Destroys all hardware rendering resources. This method is invoked 14122 * when the system needs to reclaim resources. Upon execution of this 14123 * method, you should free any OpenGL resources created by the view. 14124 * 14125 * Note: you <strong>must</strong> call 14126 * <code>super.destroyHardwareResources()</code> when overriding 14127 * this method. 14128 * 14129 * @hide 14130 */ 14131 protected void destroyHardwareResources() { 14132 // Although the Layer will be destroyed by RenderNode, we want to release 14133 // the staging display list, which is also a signal to RenderNode that it's 14134 // safe to free its copy of the display list as it knows that we will 14135 // push an updated DisplayList if we try to draw again 14136 resetDisplayList(); 14137 } 14138 14139 /** 14140 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 14141 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 14142 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 14143 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 14144 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 14145 * null.</p> 14146 * 14147 * <p>Enabling the drawing cache is similar to 14148 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 14149 * acceleration is turned off. When hardware acceleration is turned on, enabling the 14150 * drawing cache has no effect on rendering because the system uses a different mechanism 14151 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 14152 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 14153 * for information on how to enable software and hardware layers.</p> 14154 * 14155 * <p>This API can be used to manually generate 14156 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 14157 * {@link #getDrawingCache()}.</p> 14158 * 14159 * @param enabled true to enable the drawing cache, false otherwise 14160 * 14161 * @see #isDrawingCacheEnabled() 14162 * @see #getDrawingCache() 14163 * @see #buildDrawingCache() 14164 * @see #setLayerType(int, android.graphics.Paint) 14165 */ 14166 public void setDrawingCacheEnabled(boolean enabled) { 14167 mCachingFailed = false; 14168 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 14169 } 14170 14171 /** 14172 * <p>Indicates whether the drawing cache is enabled for this view.</p> 14173 * 14174 * @return true if the drawing cache is enabled 14175 * 14176 * @see #setDrawingCacheEnabled(boolean) 14177 * @see #getDrawingCache() 14178 */ 14179 @ViewDebug.ExportedProperty(category = "drawing") 14180 public boolean isDrawingCacheEnabled() { 14181 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 14182 } 14183 14184 /** 14185 * Debugging utility which recursively outputs the dirty state of a view and its 14186 * descendants. 14187 * 14188 * @hide 14189 */ 14190 @SuppressWarnings({"UnusedDeclaration"}) 14191 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 14192 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) + 14193 ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" + 14194 (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) + 14195 ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")"); 14196 if (clear) { 14197 mPrivateFlags &= clearMask; 14198 } 14199 if (this instanceof ViewGroup) { 14200 ViewGroup parent = (ViewGroup) this; 14201 final int count = parent.getChildCount(); 14202 for (int i = 0; i < count; i++) { 14203 final View child = parent.getChildAt(i); 14204 child.outputDirtyFlags(indent + " ", clear, clearMask); 14205 } 14206 } 14207 } 14208 14209 /** 14210 * This method is used by ViewGroup to cause its children to restore or recreate their 14211 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 14212 * to recreate its own display list, which would happen if it went through the normal 14213 * draw/dispatchDraw mechanisms. 14214 * 14215 * @hide 14216 */ 14217 protected void dispatchGetDisplayList() {} 14218 14219 /** 14220 * A view that is not attached or hardware accelerated cannot create a display list. 14221 * This method checks these conditions and returns the appropriate result. 14222 * 14223 * @return true if view has the ability to create a display list, false otherwise. 14224 * 14225 * @hide 14226 */ 14227 public boolean canHaveDisplayList() { 14228 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 14229 } 14230 14231 private void updateDisplayListIfDirty() { 14232 final RenderNode renderNode = mRenderNode; 14233 if (!canHaveDisplayList()) { 14234 // can't populate RenderNode, don't try 14235 return; 14236 } 14237 14238 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 14239 || !renderNode.isValid() 14240 || (mRecreateDisplayList)) { 14241 // Don't need to recreate the display list, just need to tell our 14242 // children to restore/recreate theirs 14243 if (renderNode.isValid() 14244 && !mRecreateDisplayList) { 14245 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 14246 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14247 dispatchGetDisplayList(); 14248 14249 return; // no work needed 14250 } 14251 14252 // If we got here, we're recreating it. Mark it as such to ensure that 14253 // we copy in child display lists into ours in drawChild() 14254 mRecreateDisplayList = true; 14255 14256 int width = mRight - mLeft; 14257 int height = mBottom - mTop; 14258 int layerType = getLayerType(); 14259 14260 final HardwareCanvas canvas = renderNode.start(width, height); 14261 canvas.setHighContrastText(mAttachInfo.mHighContrastText); 14262 14263 try { 14264 final HardwareLayer layer = getHardwareLayer(); 14265 if (layer != null && layer.isValid()) { 14266 canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint); 14267 } else if (layerType == LAYER_TYPE_SOFTWARE) { 14268 buildDrawingCache(true); 14269 Bitmap cache = getDrawingCache(true); 14270 if (cache != null) { 14271 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 14272 } 14273 } else { 14274 computeScroll(); 14275 14276 canvas.translate(-mScrollX, -mScrollY); 14277 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 14278 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14279 14280 // Fast path for layouts with no backgrounds 14281 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14282 dispatchDraw(canvas); 14283 if (mOverlay != null && !mOverlay.isEmpty()) { 14284 mOverlay.getOverlayView().draw(canvas); 14285 } 14286 } else { 14287 draw(canvas); 14288 } 14289 } 14290 } finally { 14291 renderNode.end(canvas); 14292 setDisplayListProperties(renderNode); 14293 } 14294 } else { 14295 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 14296 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14297 } 14298 } 14299 14300 /** 14301 * Returns a RenderNode with View draw content recorded, which can be 14302 * used to draw this view again without executing its draw method. 14303 * 14304 * @return A RenderNode ready to replay, or null if caching is not enabled. 14305 * 14306 * @hide 14307 */ 14308 public RenderNode getDisplayList() { 14309 updateDisplayListIfDirty(); 14310 return mRenderNode; 14311 } 14312 14313 private void resetDisplayList() { 14314 if (mRenderNode.isValid()) { 14315 mRenderNode.destroyDisplayListData(); 14316 } 14317 14318 if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) { 14319 mBackgroundRenderNode.destroyDisplayListData(); 14320 } 14321 } 14322 14323 /** 14324 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 14325 * 14326 * @return A non-scaled bitmap representing this view or null if cache is disabled. 14327 * 14328 * @see #getDrawingCache(boolean) 14329 */ 14330 public Bitmap getDrawingCache() { 14331 return getDrawingCache(false); 14332 } 14333 14334 /** 14335 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 14336 * is null when caching is disabled. If caching is enabled and the cache is not ready, 14337 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 14338 * draw from the cache when the cache is enabled. To benefit from the cache, you must 14339 * request the drawing cache by calling this method and draw it on screen if the 14340 * returned bitmap is not null.</p> 14341 * 14342 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 14343 * this method will create a bitmap of the same size as this view. Because this bitmap 14344 * will be drawn scaled by the parent ViewGroup, the result on screen might show 14345 * scaling artifacts. To avoid such artifacts, you should call this method by setting 14346 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 14347 * size than the view. This implies that your application must be able to handle this 14348 * size.</p> 14349 * 14350 * @param autoScale Indicates whether the generated bitmap should be scaled based on 14351 * the current density of the screen when the application is in compatibility 14352 * mode. 14353 * 14354 * @return A bitmap representing this view or null if cache is disabled. 14355 * 14356 * @see #setDrawingCacheEnabled(boolean) 14357 * @see #isDrawingCacheEnabled() 14358 * @see #buildDrawingCache(boolean) 14359 * @see #destroyDrawingCache() 14360 */ 14361 public Bitmap getDrawingCache(boolean autoScale) { 14362 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 14363 return null; 14364 } 14365 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 14366 buildDrawingCache(autoScale); 14367 } 14368 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 14369 } 14370 14371 /** 14372 * <p>Frees the resources used by the drawing cache. If you call 14373 * {@link #buildDrawingCache()} manually without calling 14374 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 14375 * should cleanup the cache with this method afterwards.</p> 14376 * 14377 * @see #setDrawingCacheEnabled(boolean) 14378 * @see #buildDrawingCache() 14379 * @see #getDrawingCache() 14380 */ 14381 public void destroyDrawingCache() { 14382 if (mDrawingCache != null) { 14383 mDrawingCache.recycle(); 14384 mDrawingCache = null; 14385 } 14386 if (mUnscaledDrawingCache != null) { 14387 mUnscaledDrawingCache.recycle(); 14388 mUnscaledDrawingCache = null; 14389 } 14390 } 14391 14392 /** 14393 * Setting a solid background color for the drawing cache's bitmaps will improve 14394 * performance and memory usage. Note, though that this should only be used if this 14395 * view will always be drawn on top of a solid color. 14396 * 14397 * @param color The background color to use for the drawing cache's bitmap 14398 * 14399 * @see #setDrawingCacheEnabled(boolean) 14400 * @see #buildDrawingCache() 14401 * @see #getDrawingCache() 14402 */ 14403 public void setDrawingCacheBackgroundColor(int color) { 14404 if (color != mDrawingCacheBackgroundColor) { 14405 mDrawingCacheBackgroundColor = color; 14406 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 14407 } 14408 } 14409 14410 /** 14411 * @see #setDrawingCacheBackgroundColor(int) 14412 * 14413 * @return The background color to used for the drawing cache's bitmap 14414 */ 14415 public int getDrawingCacheBackgroundColor() { 14416 return mDrawingCacheBackgroundColor; 14417 } 14418 14419 /** 14420 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 14421 * 14422 * @see #buildDrawingCache(boolean) 14423 */ 14424 public void buildDrawingCache() { 14425 buildDrawingCache(false); 14426 } 14427 14428 /** 14429 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 14430 * 14431 * <p>If you call {@link #buildDrawingCache()} manually without calling 14432 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 14433 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 14434 * 14435 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 14436 * this method will create a bitmap of the same size as this view. Because this bitmap 14437 * will be drawn scaled by the parent ViewGroup, the result on screen might show 14438 * scaling artifacts. To avoid such artifacts, you should call this method by setting 14439 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 14440 * size than the view. This implies that your application must be able to handle this 14441 * size.</p> 14442 * 14443 * <p>You should avoid calling this method when hardware acceleration is enabled. If 14444 * you do not need the drawing cache bitmap, calling this method will increase memory 14445 * usage and cause the view to be rendered in software once, thus negatively impacting 14446 * performance.</p> 14447 * 14448 * @see #getDrawingCache() 14449 * @see #destroyDrawingCache() 14450 */ 14451 public void buildDrawingCache(boolean autoScale) { 14452 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ? 14453 mDrawingCache == null : mUnscaledDrawingCache == null)) { 14454 if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) { 14455 Trace.traceBegin(Trace.TRACE_TAG_VIEW, 14456 "buildDrawingCache/SW Layer for " + getClass().getSimpleName()); 14457 } 14458 try { 14459 buildDrawingCacheImpl(autoScale); 14460 } finally { 14461 Trace.traceEnd(Trace.TRACE_TAG_VIEW); 14462 } 14463 } 14464 } 14465 14466 /** 14467 * private, internal implementation of buildDrawingCache, used to enable tracing 14468 */ 14469 private void buildDrawingCacheImpl(boolean autoScale) { 14470 mCachingFailed = false; 14471 14472 int width = mRight - mLeft; 14473 int height = mBottom - mTop; 14474 14475 final AttachInfo attachInfo = mAttachInfo; 14476 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 14477 14478 if (autoScale && scalingRequired) { 14479 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 14480 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 14481 } 14482 14483 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 14484 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 14485 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 14486 14487 final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4); 14488 final long drawingCacheSize = 14489 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize(); 14490 if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) { 14491 if (width > 0 && height > 0) { 14492 Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs " 14493 + projectedBitmapSize + " bytes, only " 14494 + drawingCacheSize + " available"); 14495 } 14496 destroyDrawingCache(); 14497 mCachingFailed = true; 14498 return; 14499 } 14500 14501 boolean clear = true; 14502 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 14503 14504 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 14505 Bitmap.Config quality; 14506 if (!opaque) { 14507 // Never pick ARGB_4444 because it looks awful 14508 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 14509 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 14510 case DRAWING_CACHE_QUALITY_AUTO: 14511 case DRAWING_CACHE_QUALITY_LOW: 14512 case DRAWING_CACHE_QUALITY_HIGH: 14513 default: 14514 quality = Bitmap.Config.ARGB_8888; 14515 break; 14516 } 14517 } else { 14518 // Optimization for translucent windows 14519 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 14520 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 14521 } 14522 14523 // Try to cleanup memory 14524 if (bitmap != null) bitmap.recycle(); 14525 14526 try { 14527 bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 14528 width, height, quality); 14529 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 14530 if (autoScale) { 14531 mDrawingCache = bitmap; 14532 } else { 14533 mUnscaledDrawingCache = bitmap; 14534 } 14535 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 14536 } catch (OutOfMemoryError e) { 14537 // If there is not enough memory to create the bitmap cache, just 14538 // ignore the issue as bitmap caches are not required to draw the 14539 // view hierarchy 14540 if (autoScale) { 14541 mDrawingCache = null; 14542 } else { 14543 mUnscaledDrawingCache = null; 14544 } 14545 mCachingFailed = true; 14546 return; 14547 } 14548 14549 clear = drawingCacheBackgroundColor != 0; 14550 } 14551 14552 Canvas canvas; 14553 if (attachInfo != null) { 14554 canvas = attachInfo.mCanvas; 14555 if (canvas == null) { 14556 canvas = new Canvas(); 14557 } 14558 canvas.setBitmap(bitmap); 14559 // Temporarily clobber the cached Canvas in case one of our children 14560 // is also using a drawing cache. Without this, the children would 14561 // steal the canvas by attaching their own bitmap to it and bad, bad 14562 // thing would happen (invisible views, corrupted drawings, etc.) 14563 attachInfo.mCanvas = null; 14564 } else { 14565 // This case should hopefully never or seldom happen 14566 canvas = new Canvas(bitmap); 14567 } 14568 14569 if (clear) { 14570 bitmap.eraseColor(drawingCacheBackgroundColor); 14571 } 14572 14573 computeScroll(); 14574 final int restoreCount = canvas.save(); 14575 14576 if (autoScale && scalingRequired) { 14577 final float scale = attachInfo.mApplicationScale; 14578 canvas.scale(scale, scale); 14579 } 14580 14581 canvas.translate(-mScrollX, -mScrollY); 14582 14583 mPrivateFlags |= PFLAG_DRAWN; 14584 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 14585 mLayerType != LAYER_TYPE_NONE) { 14586 mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID; 14587 } 14588 14589 // Fast path for layouts with no backgrounds 14590 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14591 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14592 dispatchDraw(canvas); 14593 if (mOverlay != null && !mOverlay.isEmpty()) { 14594 mOverlay.getOverlayView().draw(canvas); 14595 } 14596 } else { 14597 draw(canvas); 14598 } 14599 14600 canvas.restoreToCount(restoreCount); 14601 canvas.setBitmap(null); 14602 14603 if (attachInfo != null) { 14604 // Restore the cached Canvas for our siblings 14605 attachInfo.mCanvas = canvas; 14606 } 14607 } 14608 14609 /** 14610 * Create a snapshot of the view into a bitmap. We should probably make 14611 * some form of this public, but should think about the API. 14612 */ 14613 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 14614 int width = mRight - mLeft; 14615 int height = mBottom - mTop; 14616 14617 final AttachInfo attachInfo = mAttachInfo; 14618 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 14619 width = (int) ((width * scale) + 0.5f); 14620 height = (int) ((height * scale) + 0.5f); 14621 14622 Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 14623 width > 0 ? width : 1, height > 0 ? height : 1, quality); 14624 if (bitmap == null) { 14625 throw new OutOfMemoryError(); 14626 } 14627 14628 Resources resources = getResources(); 14629 if (resources != null) { 14630 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 14631 } 14632 14633 Canvas canvas; 14634 if (attachInfo != null) { 14635 canvas = attachInfo.mCanvas; 14636 if (canvas == null) { 14637 canvas = new Canvas(); 14638 } 14639 canvas.setBitmap(bitmap); 14640 // Temporarily clobber the cached Canvas in case one of our children 14641 // is also using a drawing cache. Without this, the children would 14642 // steal the canvas by attaching their own bitmap to it and bad, bad 14643 // things would happen (invisible views, corrupted drawings, etc.) 14644 attachInfo.mCanvas = null; 14645 } else { 14646 // This case should hopefully never or seldom happen 14647 canvas = new Canvas(bitmap); 14648 } 14649 14650 if ((backgroundColor & 0xff000000) != 0) { 14651 bitmap.eraseColor(backgroundColor); 14652 } 14653 14654 computeScroll(); 14655 final int restoreCount = canvas.save(); 14656 canvas.scale(scale, scale); 14657 canvas.translate(-mScrollX, -mScrollY); 14658 14659 // Temporarily remove the dirty mask 14660 int flags = mPrivateFlags; 14661 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14662 14663 // Fast path for layouts with no backgrounds 14664 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14665 dispatchDraw(canvas); 14666 if (mOverlay != null && !mOverlay.isEmpty()) { 14667 mOverlay.getOverlayView().draw(canvas); 14668 } 14669 } else { 14670 draw(canvas); 14671 } 14672 14673 mPrivateFlags = flags; 14674 14675 canvas.restoreToCount(restoreCount); 14676 canvas.setBitmap(null); 14677 14678 if (attachInfo != null) { 14679 // Restore the cached Canvas for our siblings 14680 attachInfo.mCanvas = canvas; 14681 } 14682 14683 return bitmap; 14684 } 14685 14686 /** 14687 * Indicates whether this View is currently in edit mode. A View is usually 14688 * in edit mode when displayed within a developer tool. For instance, if 14689 * this View is being drawn by a visual user interface builder, this method 14690 * should return true. 14691 * 14692 * Subclasses should check the return value of this method to provide 14693 * different behaviors if their normal behavior might interfere with the 14694 * host environment. For instance: the class spawns a thread in its 14695 * constructor, the drawing code relies on device-specific features, etc. 14696 * 14697 * This method is usually checked in the drawing code of custom widgets. 14698 * 14699 * @return True if this View is in edit mode, false otherwise. 14700 */ 14701 public boolean isInEditMode() { 14702 return false; 14703 } 14704 14705 /** 14706 * If the View draws content inside its padding and enables fading edges, 14707 * it needs to support padding offsets. Padding offsets are added to the 14708 * fading edges to extend the length of the fade so that it covers pixels 14709 * drawn inside the padding. 14710 * 14711 * Subclasses of this class should override this method if they need 14712 * to draw content inside the padding. 14713 * 14714 * @return True if padding offset must be applied, false otherwise. 14715 * 14716 * @see #getLeftPaddingOffset() 14717 * @see #getRightPaddingOffset() 14718 * @see #getTopPaddingOffset() 14719 * @see #getBottomPaddingOffset() 14720 * 14721 * @since CURRENT 14722 */ 14723 protected boolean isPaddingOffsetRequired() { 14724 return false; 14725 } 14726 14727 /** 14728 * Amount by which to extend the left fading region. Called only when 14729 * {@link #isPaddingOffsetRequired()} returns true. 14730 * 14731 * @return The left padding offset in pixels. 14732 * 14733 * @see #isPaddingOffsetRequired() 14734 * 14735 * @since CURRENT 14736 */ 14737 protected int getLeftPaddingOffset() { 14738 return 0; 14739 } 14740 14741 /** 14742 * Amount by which to extend the right fading region. Called only when 14743 * {@link #isPaddingOffsetRequired()} returns true. 14744 * 14745 * @return The right padding offset in pixels. 14746 * 14747 * @see #isPaddingOffsetRequired() 14748 * 14749 * @since CURRENT 14750 */ 14751 protected int getRightPaddingOffset() { 14752 return 0; 14753 } 14754 14755 /** 14756 * Amount by which to extend the top fading region. Called only when 14757 * {@link #isPaddingOffsetRequired()} returns true. 14758 * 14759 * @return The top padding offset in pixels. 14760 * 14761 * @see #isPaddingOffsetRequired() 14762 * 14763 * @since CURRENT 14764 */ 14765 protected int getTopPaddingOffset() { 14766 return 0; 14767 } 14768 14769 /** 14770 * Amount by which to extend the bottom fading region. Called only when 14771 * {@link #isPaddingOffsetRequired()} returns true. 14772 * 14773 * @return The bottom padding offset in pixels. 14774 * 14775 * @see #isPaddingOffsetRequired() 14776 * 14777 * @since CURRENT 14778 */ 14779 protected int getBottomPaddingOffset() { 14780 return 0; 14781 } 14782 14783 /** 14784 * @hide 14785 * @param offsetRequired 14786 */ 14787 protected int getFadeTop(boolean offsetRequired) { 14788 int top = mPaddingTop; 14789 if (offsetRequired) top += getTopPaddingOffset(); 14790 return top; 14791 } 14792 14793 /** 14794 * @hide 14795 * @param offsetRequired 14796 */ 14797 protected int getFadeHeight(boolean offsetRequired) { 14798 int padding = mPaddingTop; 14799 if (offsetRequired) padding += getTopPaddingOffset(); 14800 return mBottom - mTop - mPaddingBottom - padding; 14801 } 14802 14803 /** 14804 * <p>Indicates whether this view is attached to a hardware accelerated 14805 * window or not.</p> 14806 * 14807 * <p>Even if this method returns true, it does not mean that every call 14808 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 14809 * accelerated {@link android.graphics.Canvas}. For instance, if this view 14810 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 14811 * window is hardware accelerated, 14812 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 14813 * return false, and this method will return true.</p> 14814 * 14815 * @return True if the view is attached to a window and the window is 14816 * hardware accelerated; false in any other case. 14817 */ 14818 @ViewDebug.ExportedProperty(category = "drawing") 14819 public boolean isHardwareAccelerated() { 14820 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 14821 } 14822 14823 /** 14824 * Sets a rectangular area on this view to which the view will be clipped 14825 * when it is drawn. Setting the value to null will remove the clip bounds 14826 * and the view will draw normally, using its full bounds. 14827 * 14828 * @param clipBounds The rectangular area, in the local coordinates of 14829 * this view, to which future drawing operations will be clipped. 14830 */ 14831 public void setClipBounds(Rect clipBounds) { 14832 if (clipBounds == mClipBounds 14833 || (clipBounds != null && clipBounds.equals(mClipBounds))) { 14834 return; 14835 } 14836 if (clipBounds != null) { 14837 if (mClipBounds == null) { 14838 mClipBounds = new Rect(clipBounds); 14839 } else { 14840 mClipBounds.set(clipBounds); 14841 } 14842 } else { 14843 mClipBounds = null; 14844 } 14845 mRenderNode.setClipBounds(mClipBounds); 14846 invalidateViewProperty(false, false); 14847 } 14848 14849 /** 14850 * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}. 14851 * 14852 * @return A copy of the current clip bounds if clip bounds are set, 14853 * otherwise null. 14854 */ 14855 public Rect getClipBounds() { 14856 return (mClipBounds != null) ? new Rect(mClipBounds) : null; 14857 } 14858 14859 /** 14860 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 14861 * case of an active Animation being run on the view. 14862 */ 14863 private boolean drawAnimation(ViewGroup parent, long drawingTime, 14864 Animation a, boolean scalingRequired) { 14865 Transformation invalidationTransform; 14866 final int flags = parent.mGroupFlags; 14867 final boolean initialized = a.isInitialized(); 14868 if (!initialized) { 14869 a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight()); 14870 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 14871 if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler); 14872 onAnimationStart(); 14873 } 14874 14875 final Transformation t = parent.getChildTransformation(); 14876 boolean more = a.getTransformation(drawingTime, t, 1f); 14877 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 14878 if (parent.mInvalidationTransformation == null) { 14879 parent.mInvalidationTransformation = new Transformation(); 14880 } 14881 invalidationTransform = parent.mInvalidationTransformation; 14882 a.getTransformation(drawingTime, invalidationTransform, 1f); 14883 } else { 14884 invalidationTransform = t; 14885 } 14886 14887 if (more) { 14888 if (!a.willChangeBounds()) { 14889 if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) == 14890 ViewGroup.FLAG_OPTIMIZE_INVALIDATE) { 14891 parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED; 14892 } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) { 14893 // The child need to draw an animation, potentially offscreen, so 14894 // make sure we do not cancel invalidate requests 14895 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 14896 parent.invalidate(mLeft, mTop, mRight, mBottom); 14897 } 14898 } else { 14899 if (parent.mInvalidateRegion == null) { 14900 parent.mInvalidateRegion = new RectF(); 14901 } 14902 final RectF region = parent.mInvalidateRegion; 14903 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 14904 invalidationTransform); 14905 14906 // The child need to draw an animation, potentially offscreen, so 14907 // make sure we do not cancel invalidate requests 14908 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 14909 14910 final int left = mLeft + (int) region.left; 14911 final int top = mTop + (int) region.top; 14912 parent.invalidate(left, top, left + (int) (region.width() + .5f), 14913 top + (int) (region.height() + .5f)); 14914 } 14915 } 14916 return more; 14917 } 14918 14919 /** 14920 * This method is called by getDisplayList() when a display list is recorded for a View. 14921 * It pushes any properties to the RenderNode that aren't managed by the RenderNode. 14922 */ 14923 void setDisplayListProperties(RenderNode renderNode) { 14924 if (renderNode != null) { 14925 renderNode.setHasOverlappingRendering(hasOverlappingRendering()); 14926 if (mParent instanceof ViewGroup) { 14927 renderNode.setClipToBounds( 14928 (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0); 14929 } 14930 float alpha = 1; 14931 if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags & 14932 ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 14933 ViewGroup parentVG = (ViewGroup) mParent; 14934 final Transformation t = parentVG.getChildTransformation(); 14935 if (parentVG.getChildStaticTransformation(this, t)) { 14936 final int transformType = t.getTransformationType(); 14937 if (transformType != Transformation.TYPE_IDENTITY) { 14938 if ((transformType & Transformation.TYPE_ALPHA) != 0) { 14939 alpha = t.getAlpha(); 14940 } 14941 if ((transformType & Transformation.TYPE_MATRIX) != 0) { 14942 renderNode.setStaticMatrix(t.getMatrix()); 14943 } 14944 } 14945 } 14946 } 14947 if (mTransformationInfo != null) { 14948 alpha *= getFinalAlpha(); 14949 if (alpha < 1) { 14950 final int multipliedAlpha = (int) (255 * alpha); 14951 if (onSetAlpha(multipliedAlpha)) { 14952 alpha = 1; 14953 } 14954 } 14955 renderNode.setAlpha(alpha); 14956 } else if (alpha < 1) { 14957 renderNode.setAlpha(alpha); 14958 } 14959 } 14960 } 14961 14962 /** 14963 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 14964 * This draw() method is an implementation detail and is not intended to be overridden or 14965 * to be called from anywhere else other than ViewGroup.drawChild(). 14966 */ 14967 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 14968 boolean usingRenderNodeProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 14969 boolean more = false; 14970 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 14971 final int flags = parent.mGroupFlags; 14972 14973 if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) { 14974 parent.getChildTransformation().clear(); 14975 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14976 } 14977 14978 Transformation transformToApply = null; 14979 boolean concatMatrix = false; 14980 14981 boolean scalingRequired = false; 14982 boolean caching; 14983 int layerType = getLayerType(); 14984 14985 final boolean hardwareAccelerated = canvas.isHardwareAccelerated(); 14986 if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 || 14987 (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) { 14988 caching = true; 14989 // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList 14990 if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired; 14991 } else { 14992 caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated; 14993 } 14994 14995 final Animation a = getAnimation(); 14996 if (a != null) { 14997 more = drawAnimation(parent, drawingTime, a, scalingRequired); 14998 concatMatrix = a.willChangeTransformationMatrix(); 14999 if (concatMatrix) { 15000 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 15001 } 15002 transformToApply = parent.getChildTransformation(); 15003 } else { 15004 if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) { 15005 // No longer animating: clear out old animation matrix 15006 mRenderNode.setAnimationMatrix(null); 15007 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 15008 } 15009 if (!usingRenderNodeProperties && 15010 (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 15011 final Transformation t = parent.getChildTransformation(); 15012 final boolean hasTransform = parent.getChildStaticTransformation(this, t); 15013 if (hasTransform) { 15014 final int transformType = t.getTransformationType(); 15015 transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null; 15016 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 15017 } 15018 } 15019 } 15020 15021 concatMatrix |= !childHasIdentityMatrix; 15022 15023 // Sets the flag as early as possible to allow draw() implementations 15024 // to call invalidate() successfully when doing animations 15025 mPrivateFlags |= PFLAG_DRAWN; 15026 15027 if (!concatMatrix && 15028 (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS | 15029 ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN && 15030 canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 15031 (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) { 15032 mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED; 15033 return more; 15034 } 15035 mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED; 15036 15037 if (hardwareAccelerated) { 15038 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 15039 // retain the flag's value temporarily in the mRecreateDisplayList flag 15040 mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED; 15041 mPrivateFlags &= ~PFLAG_INVALIDATED; 15042 } 15043 15044 RenderNode renderNode = null; 15045 Bitmap cache = null; 15046 boolean hasDisplayList = false; 15047 if (caching) { 15048 if (!hardwareAccelerated) { 15049 if (layerType != LAYER_TYPE_NONE) { 15050 layerType = LAYER_TYPE_SOFTWARE; 15051 buildDrawingCache(true); 15052 } 15053 cache = getDrawingCache(true); 15054 } else { 15055 switch (layerType) { 15056 case LAYER_TYPE_SOFTWARE: 15057 if (usingRenderNodeProperties) { 15058 hasDisplayList = canHaveDisplayList(); 15059 } else { 15060 buildDrawingCache(true); 15061 cache = getDrawingCache(true); 15062 } 15063 break; 15064 case LAYER_TYPE_HARDWARE: 15065 if (usingRenderNodeProperties) { 15066 hasDisplayList = canHaveDisplayList(); 15067 } 15068 break; 15069 case LAYER_TYPE_NONE: 15070 // Delay getting the display list until animation-driven alpha values are 15071 // set up and possibly passed on to the view 15072 hasDisplayList = canHaveDisplayList(); 15073 break; 15074 } 15075 } 15076 } 15077 usingRenderNodeProperties &= hasDisplayList; 15078 if (usingRenderNodeProperties) { 15079 renderNode = getDisplayList(); 15080 if (!renderNode.isValid()) { 15081 // Uncommon, but possible. If a view is removed from the hierarchy during the call 15082 // to getDisplayList(), the display list will be marked invalid and we should not 15083 // try to use it again. 15084 renderNode = null; 15085 hasDisplayList = false; 15086 usingRenderNodeProperties = false; 15087 } 15088 } 15089 15090 int sx = 0; 15091 int sy = 0; 15092 if (!hasDisplayList) { 15093 computeScroll(); 15094 sx = mScrollX; 15095 sy = mScrollY; 15096 } 15097 15098 final boolean hasNoCache = cache == null || hasDisplayList; 15099 final boolean offsetForScroll = cache == null && !hasDisplayList && 15100 layerType != LAYER_TYPE_HARDWARE; 15101 15102 int restoreTo = -1; 15103 if (!usingRenderNodeProperties || transformToApply != null) { 15104 restoreTo = canvas.save(); 15105 } 15106 if (offsetForScroll) { 15107 canvas.translate(mLeft - sx, mTop - sy); 15108 } else { 15109 if (!usingRenderNodeProperties) { 15110 canvas.translate(mLeft, mTop); 15111 } 15112 if (scalingRequired) { 15113 if (usingRenderNodeProperties) { 15114 // TODO: Might not need this if we put everything inside the DL 15115 restoreTo = canvas.save(); 15116 } 15117 // mAttachInfo cannot be null, otherwise scalingRequired == false 15118 final float scale = 1.0f / mAttachInfo.mApplicationScale; 15119 canvas.scale(scale, scale); 15120 } 15121 } 15122 15123 float alpha = usingRenderNodeProperties ? 1 : (getAlpha() * getTransitionAlpha()); 15124 if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() || 15125 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 15126 if (transformToApply != null || !childHasIdentityMatrix) { 15127 int transX = 0; 15128 int transY = 0; 15129 15130 if (offsetForScroll) { 15131 transX = -sx; 15132 transY = -sy; 15133 } 15134 15135 if (transformToApply != null) { 15136 if (concatMatrix) { 15137 if (usingRenderNodeProperties) { 15138 renderNode.setAnimationMatrix(transformToApply.getMatrix()); 15139 } else { 15140 // Undo the scroll translation, apply the transformation matrix, 15141 // then redo the scroll translate to get the correct result. 15142 canvas.translate(-transX, -transY); 15143 canvas.concat(transformToApply.getMatrix()); 15144 canvas.translate(transX, transY); 15145 } 15146 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 15147 } 15148 15149 float transformAlpha = transformToApply.getAlpha(); 15150 if (transformAlpha < 1) { 15151 alpha *= transformAlpha; 15152 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 15153 } 15154 } 15155 15156 if (!childHasIdentityMatrix && !usingRenderNodeProperties) { 15157 canvas.translate(-transX, -transY); 15158 canvas.concat(getMatrix()); 15159 canvas.translate(transX, transY); 15160 } 15161 } 15162 15163 // Deal with alpha if it is or used to be <1 15164 if (alpha < 1 || 15165 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 15166 if (alpha < 1) { 15167 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA; 15168 } else { 15169 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA; 15170 } 15171 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 15172 if (hasNoCache) { 15173 final int multipliedAlpha = (int) (255 * alpha); 15174 if (!onSetAlpha(multipliedAlpha)) { 15175 int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 15176 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 || 15177 layerType != LAYER_TYPE_NONE) { 15178 layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG; 15179 } 15180 if (usingRenderNodeProperties) { 15181 renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha()); 15182 } else if (layerType == LAYER_TYPE_NONE) { 15183 final int scrollX = hasDisplayList ? 0 : sx; 15184 final int scrollY = hasDisplayList ? 0 : sy; 15185 canvas.saveLayerAlpha(scrollX, scrollY, 15186 scrollX + (mRight - mLeft), scrollY + (mBottom - mTop), 15187 multipliedAlpha, layerFlags); 15188 } 15189 } else { 15190 // Alpha is handled by the child directly, clobber the layer's alpha 15191 mPrivateFlags |= PFLAG_ALPHA_SET; 15192 } 15193 } 15194 } 15195 } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 15196 onSetAlpha(255); 15197 mPrivateFlags &= ~PFLAG_ALPHA_SET; 15198 } 15199 15200 if (!usingRenderNodeProperties) { 15201 // apply clips directly, since RenderNode won't do it for this draw 15202 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN 15203 && cache == null) { 15204 if (offsetForScroll) { 15205 canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop)); 15206 } else { 15207 if (!scalingRequired || cache == null) { 15208 canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop); 15209 } else { 15210 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 15211 } 15212 } 15213 } 15214 15215 if (mClipBounds != null) { 15216 // clip bounds ignore scroll 15217 canvas.clipRect(mClipBounds); 15218 } 15219 } 15220 15221 15222 15223 if (!usingRenderNodeProperties && hasDisplayList) { 15224 renderNode = getDisplayList(); 15225 if (!renderNode.isValid()) { 15226 // Uncommon, but possible. If a view is removed from the hierarchy during the call 15227 // to getDisplayList(), the display list will be marked invalid and we should not 15228 // try to use it again. 15229 renderNode = null; 15230 hasDisplayList = false; 15231 } 15232 } 15233 15234 if (hasNoCache) { 15235 boolean layerRendered = false; 15236 if (layerType == LAYER_TYPE_HARDWARE && !usingRenderNodeProperties) { 15237 final HardwareLayer layer = getHardwareLayer(); 15238 if (layer != null && layer.isValid()) { 15239 int restoreAlpha = mLayerPaint.getAlpha(); 15240 mLayerPaint.setAlpha((int) (alpha * 255)); 15241 ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint); 15242 mLayerPaint.setAlpha(restoreAlpha); 15243 layerRendered = true; 15244 } else { 15245 final int scrollX = hasDisplayList ? 0 : sx; 15246 final int scrollY = hasDisplayList ? 0 : sy; 15247 canvas.saveLayer(scrollX, scrollY, 15248 scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint, 15249 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG); 15250 } 15251 } 15252 15253 if (!layerRendered) { 15254 if (!hasDisplayList) { 15255 // Fast path for layouts with no backgrounds 15256 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 15257 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 15258 dispatchDraw(canvas); 15259 } else { 15260 draw(canvas); 15261 } 15262 } else { 15263 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 15264 ((HardwareCanvas) canvas).drawRenderNode(renderNode, null, flags); 15265 } 15266 } 15267 } else if (cache != null) { 15268 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 15269 Paint cachePaint; 15270 int restoreAlpha = 0; 15271 15272 if (layerType == LAYER_TYPE_NONE) { 15273 cachePaint = parent.mCachePaint; 15274 if (cachePaint == null) { 15275 cachePaint = new Paint(); 15276 cachePaint.setDither(false); 15277 parent.mCachePaint = cachePaint; 15278 } 15279 } else { 15280 cachePaint = mLayerPaint; 15281 restoreAlpha = mLayerPaint.getAlpha(); 15282 } 15283 cachePaint.setAlpha((int) (alpha * 255)); 15284 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 15285 cachePaint.setAlpha(restoreAlpha); 15286 } 15287 15288 if (restoreTo >= 0) { 15289 canvas.restoreToCount(restoreTo); 15290 } 15291 15292 if (a != null && !more) { 15293 if (!hardwareAccelerated && !a.getFillAfter()) { 15294 onSetAlpha(255); 15295 } 15296 parent.finishAnimatingView(this, a); 15297 } 15298 15299 if (more && hardwareAccelerated) { 15300 if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 15301 // alpha animations should cause the child to recreate its display list 15302 invalidate(true); 15303 } 15304 } 15305 15306 mRecreateDisplayList = false; 15307 15308 return more; 15309 } 15310 15311 /** 15312 * Manually render this view (and all of its children) to the given Canvas. 15313 * The view must have already done a full layout before this function is 15314 * called. When implementing a view, implement 15315 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 15316 * If you do need to override this method, call the superclass version. 15317 * 15318 * @param canvas The Canvas to which the View is rendered. 15319 */ 15320 public void draw(Canvas canvas) { 15321 final int privateFlags = mPrivateFlags; 15322 final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE && 15323 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 15324 mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN; 15325 15326 /* 15327 * Draw traversal performs several drawing steps which must be executed 15328 * in the appropriate order: 15329 * 15330 * 1. Draw the background 15331 * 2. If necessary, save the canvas' layers to prepare for fading 15332 * 3. Draw view's content 15333 * 4. Draw children 15334 * 5. If necessary, draw the fading edges and restore layers 15335 * 6. Draw decorations (scrollbars for instance) 15336 */ 15337 15338 // Step 1, draw the background, if needed 15339 int saveCount; 15340 15341 if (!dirtyOpaque) { 15342 drawBackground(canvas); 15343 } 15344 15345 // skip step 2 & 5 if possible (common case) 15346 final int viewFlags = mViewFlags; 15347 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 15348 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 15349 if (!verticalEdges && !horizontalEdges) { 15350 // Step 3, draw the content 15351 if (!dirtyOpaque) onDraw(canvas); 15352 15353 // Step 4, draw the children 15354 dispatchDraw(canvas); 15355 15356 // Step 6, draw decorations (scrollbars) 15357 onDrawScrollBars(canvas); 15358 15359 if (mOverlay != null && !mOverlay.isEmpty()) { 15360 mOverlay.getOverlayView().dispatchDraw(canvas); 15361 } 15362 15363 // we're done... 15364 return; 15365 } 15366 15367 /* 15368 * Here we do the full fledged routine... 15369 * (this is an uncommon case where speed matters less, 15370 * this is why we repeat some of the tests that have been 15371 * done above) 15372 */ 15373 15374 boolean drawTop = false; 15375 boolean drawBottom = false; 15376 boolean drawLeft = false; 15377 boolean drawRight = false; 15378 15379 float topFadeStrength = 0.0f; 15380 float bottomFadeStrength = 0.0f; 15381 float leftFadeStrength = 0.0f; 15382 float rightFadeStrength = 0.0f; 15383 15384 // Step 2, save the canvas' layers 15385 int paddingLeft = mPaddingLeft; 15386 15387 final boolean offsetRequired = isPaddingOffsetRequired(); 15388 if (offsetRequired) { 15389 paddingLeft += getLeftPaddingOffset(); 15390 } 15391 15392 int left = mScrollX + paddingLeft; 15393 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 15394 int top = mScrollY + getFadeTop(offsetRequired); 15395 int bottom = top + getFadeHeight(offsetRequired); 15396 15397 if (offsetRequired) { 15398 right += getRightPaddingOffset(); 15399 bottom += getBottomPaddingOffset(); 15400 } 15401 15402 final ScrollabilityCache scrollabilityCache = mScrollCache; 15403 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 15404 int length = (int) fadeHeight; 15405 15406 // clip the fade length if top and bottom fades overlap 15407 // overlapping fades produce odd-looking artifacts 15408 if (verticalEdges && (top + length > bottom - length)) { 15409 length = (bottom - top) / 2; 15410 } 15411 15412 // also clip horizontal fades if necessary 15413 if (horizontalEdges && (left + length > right - length)) { 15414 length = (right - left) / 2; 15415 } 15416 15417 if (verticalEdges) { 15418 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 15419 drawTop = topFadeStrength * fadeHeight > 1.0f; 15420 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 15421 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 15422 } 15423 15424 if (horizontalEdges) { 15425 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 15426 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 15427 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 15428 drawRight = rightFadeStrength * fadeHeight > 1.0f; 15429 } 15430 15431 saveCount = canvas.getSaveCount(); 15432 15433 int solidColor = getSolidColor(); 15434 if (solidColor == 0) { 15435 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 15436 15437 if (drawTop) { 15438 canvas.saveLayer(left, top, right, top + length, null, flags); 15439 } 15440 15441 if (drawBottom) { 15442 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 15443 } 15444 15445 if (drawLeft) { 15446 canvas.saveLayer(left, top, left + length, bottom, null, flags); 15447 } 15448 15449 if (drawRight) { 15450 canvas.saveLayer(right - length, top, right, bottom, null, flags); 15451 } 15452 } else { 15453 scrollabilityCache.setFadeColor(solidColor); 15454 } 15455 15456 // Step 3, draw the content 15457 if (!dirtyOpaque) onDraw(canvas); 15458 15459 // Step 4, draw the children 15460 dispatchDraw(canvas); 15461 15462 // Step 5, draw the fade effect and restore layers 15463 final Paint p = scrollabilityCache.paint; 15464 final Matrix matrix = scrollabilityCache.matrix; 15465 final Shader fade = scrollabilityCache.shader; 15466 15467 if (drawTop) { 15468 matrix.setScale(1, fadeHeight * topFadeStrength); 15469 matrix.postTranslate(left, top); 15470 fade.setLocalMatrix(matrix); 15471 p.setShader(fade); 15472 canvas.drawRect(left, top, right, top + length, p); 15473 } 15474 15475 if (drawBottom) { 15476 matrix.setScale(1, fadeHeight * bottomFadeStrength); 15477 matrix.postRotate(180); 15478 matrix.postTranslate(left, bottom); 15479 fade.setLocalMatrix(matrix); 15480 p.setShader(fade); 15481 canvas.drawRect(left, bottom - length, right, bottom, p); 15482 } 15483 15484 if (drawLeft) { 15485 matrix.setScale(1, fadeHeight * leftFadeStrength); 15486 matrix.postRotate(-90); 15487 matrix.postTranslate(left, top); 15488 fade.setLocalMatrix(matrix); 15489 p.setShader(fade); 15490 canvas.drawRect(left, top, left + length, bottom, p); 15491 } 15492 15493 if (drawRight) { 15494 matrix.setScale(1, fadeHeight * rightFadeStrength); 15495 matrix.postRotate(90); 15496 matrix.postTranslate(right, top); 15497 fade.setLocalMatrix(matrix); 15498 p.setShader(fade); 15499 canvas.drawRect(right - length, top, right, bottom, p); 15500 } 15501 15502 canvas.restoreToCount(saveCount); 15503 15504 // Step 6, draw decorations (scrollbars) 15505 onDrawScrollBars(canvas); 15506 15507 if (mOverlay != null && !mOverlay.isEmpty()) { 15508 mOverlay.getOverlayView().dispatchDraw(canvas); 15509 } 15510 } 15511 15512 /** 15513 * Draws the background onto the specified canvas. 15514 * 15515 * @param canvas Canvas on which to draw the background 15516 */ 15517 private void drawBackground(Canvas canvas) { 15518 final Drawable background = mBackground; 15519 if (background == null) { 15520 return; 15521 } 15522 15523 if (mBackgroundSizeChanged) { 15524 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 15525 mBackgroundSizeChanged = false; 15526 rebuildOutline(); 15527 } 15528 15529 // Attempt to use a display list if requested. 15530 if (canvas.isHardwareAccelerated() && mAttachInfo != null 15531 && mAttachInfo.mHardwareRenderer != null) { 15532 mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode); 15533 15534 final RenderNode renderNode = mBackgroundRenderNode; 15535 if (renderNode != null && renderNode.isValid()) { 15536 setBackgroundRenderNodeProperties(renderNode); 15537 ((HardwareCanvas) canvas).drawRenderNode(renderNode); 15538 return; 15539 } 15540 } 15541 15542 final int scrollX = mScrollX; 15543 final int scrollY = mScrollY; 15544 if ((scrollX | scrollY) == 0) { 15545 background.draw(canvas); 15546 } else { 15547 canvas.translate(scrollX, scrollY); 15548 background.draw(canvas); 15549 canvas.translate(-scrollX, -scrollY); 15550 } 15551 } 15552 15553 private void setBackgroundRenderNodeProperties(RenderNode renderNode) { 15554 renderNode.setTranslationX(mScrollX); 15555 renderNode.setTranslationY(mScrollY); 15556 } 15557 15558 /** 15559 * Creates a new display list or updates the existing display list for the 15560 * specified Drawable. 15561 * 15562 * @param drawable Drawable for which to create a display list 15563 * @param renderNode Existing RenderNode, or {@code null} 15564 * @return A valid display list for the specified drawable 15565 */ 15566 private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) { 15567 if (renderNode == null) { 15568 renderNode = RenderNode.create(drawable.getClass().getName(), this); 15569 } 15570 15571 final Rect bounds = drawable.getBounds(); 15572 final int width = bounds.width(); 15573 final int height = bounds.height(); 15574 final HardwareCanvas canvas = renderNode.start(width, height); 15575 15576 // Reverse left/top translation done by drawable canvas, which will 15577 // instead be applied by rendernode's LTRB bounds below. This way, the 15578 // drawable's bounds match with its rendernode bounds and its content 15579 // will lie within those bounds in the rendernode tree. 15580 canvas.translate(-bounds.left, -bounds.top); 15581 15582 try { 15583 drawable.draw(canvas); 15584 } finally { 15585 renderNode.end(canvas); 15586 } 15587 15588 // Set up drawable properties that are view-independent. 15589 renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom); 15590 renderNode.setProjectBackwards(drawable.isProjected()); 15591 renderNode.setProjectionReceiver(true); 15592 renderNode.setClipToBounds(false); 15593 return renderNode; 15594 } 15595 15596 /** 15597 * Returns the overlay for this view, creating it if it does not yet exist. 15598 * Adding drawables to the overlay will cause them to be displayed whenever 15599 * the view itself is redrawn. Objects in the overlay should be actively 15600 * managed: remove them when they should not be displayed anymore. The 15601 * overlay will always have the same size as its host view. 15602 * 15603 * <p>Note: Overlays do not currently work correctly with {@link 15604 * SurfaceView} or {@link TextureView}; contents in overlays for these 15605 * types of views may not display correctly.</p> 15606 * 15607 * @return The ViewOverlay object for this view. 15608 * @see ViewOverlay 15609 */ 15610 public ViewOverlay getOverlay() { 15611 if (mOverlay == null) { 15612 mOverlay = new ViewOverlay(mContext, this); 15613 } 15614 return mOverlay; 15615 } 15616 15617 /** 15618 * Override this if your view is known to always be drawn on top of a solid color background, 15619 * and needs to draw fading edges. Returning a non-zero color enables the view system to 15620 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 15621 * should be set to 0xFF. 15622 * 15623 * @see #setVerticalFadingEdgeEnabled(boolean) 15624 * @see #setHorizontalFadingEdgeEnabled(boolean) 15625 * 15626 * @return The known solid color background for this view, or 0 if the color may vary 15627 */ 15628 @ViewDebug.ExportedProperty(category = "drawing") 15629 public int getSolidColor() { 15630 return 0; 15631 } 15632 15633 /** 15634 * Build a human readable string representation of the specified view flags. 15635 * 15636 * @param flags the view flags to convert to a string 15637 * @return a String representing the supplied flags 15638 */ 15639 private static String printFlags(int flags) { 15640 String output = ""; 15641 int numFlags = 0; 15642 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 15643 output += "TAKES_FOCUS"; 15644 numFlags++; 15645 } 15646 15647 switch (flags & VISIBILITY_MASK) { 15648 case INVISIBLE: 15649 if (numFlags > 0) { 15650 output += " "; 15651 } 15652 output += "INVISIBLE"; 15653 // USELESS HERE numFlags++; 15654 break; 15655 case GONE: 15656 if (numFlags > 0) { 15657 output += " "; 15658 } 15659 output += "GONE"; 15660 // USELESS HERE numFlags++; 15661 break; 15662 default: 15663 break; 15664 } 15665 return output; 15666 } 15667 15668 /** 15669 * Build a human readable string representation of the specified private 15670 * view flags. 15671 * 15672 * @param privateFlags the private view flags to convert to a string 15673 * @return a String representing the supplied flags 15674 */ 15675 private static String printPrivateFlags(int privateFlags) { 15676 String output = ""; 15677 int numFlags = 0; 15678 15679 if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) { 15680 output += "WANTS_FOCUS"; 15681 numFlags++; 15682 } 15683 15684 if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) { 15685 if (numFlags > 0) { 15686 output += " "; 15687 } 15688 output += "FOCUSED"; 15689 numFlags++; 15690 } 15691 15692 if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) { 15693 if (numFlags > 0) { 15694 output += " "; 15695 } 15696 output += "SELECTED"; 15697 numFlags++; 15698 } 15699 15700 if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) { 15701 if (numFlags > 0) { 15702 output += " "; 15703 } 15704 output += "IS_ROOT_NAMESPACE"; 15705 numFlags++; 15706 } 15707 15708 if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) { 15709 if (numFlags > 0) { 15710 output += " "; 15711 } 15712 output += "HAS_BOUNDS"; 15713 numFlags++; 15714 } 15715 15716 if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) { 15717 if (numFlags > 0) { 15718 output += " "; 15719 } 15720 output += "DRAWN"; 15721 // USELESS HERE numFlags++; 15722 } 15723 return output; 15724 } 15725 15726 /** 15727 * <p>Indicates whether or not this view's layout will be requested during 15728 * the next hierarchy layout pass.</p> 15729 * 15730 * @return true if the layout will be forced during next layout pass 15731 */ 15732 public boolean isLayoutRequested() { 15733 return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 15734 } 15735 15736 /** 15737 * Return true if o is a ViewGroup that is laying out using optical bounds. 15738 * @hide 15739 */ 15740 public static boolean isLayoutModeOptical(Object o) { 15741 return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical(); 15742 } 15743 15744 private boolean setOpticalFrame(int left, int top, int right, int bottom) { 15745 Insets parentInsets = mParent instanceof View ? 15746 ((View) mParent).getOpticalInsets() : Insets.NONE; 15747 Insets childInsets = getOpticalInsets(); 15748 return setFrame( 15749 left + parentInsets.left - childInsets.left, 15750 top + parentInsets.top - childInsets.top, 15751 right + parentInsets.left + childInsets.right, 15752 bottom + parentInsets.top + childInsets.bottom); 15753 } 15754 15755 /** 15756 * Assign a size and position to a view and all of its 15757 * descendants 15758 * 15759 * <p>This is the second phase of the layout mechanism. 15760 * (The first is measuring). In this phase, each parent calls 15761 * layout on all of its children to position them. 15762 * This is typically done using the child measurements 15763 * that were stored in the measure pass().</p> 15764 * 15765 * <p>Derived classes should not override this method. 15766 * Derived classes with children should override 15767 * onLayout. In that method, they should 15768 * call layout on each of their children.</p> 15769 * 15770 * @param l Left position, relative to parent 15771 * @param t Top position, relative to parent 15772 * @param r Right position, relative to parent 15773 * @param b Bottom position, relative to parent 15774 */ 15775 @SuppressWarnings({"unchecked"}) 15776 public void layout(int l, int t, int r, int b) { 15777 if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) { 15778 onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec); 15779 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 15780 } 15781 15782 int oldL = mLeft; 15783 int oldT = mTop; 15784 int oldB = mBottom; 15785 int oldR = mRight; 15786 15787 boolean changed = isLayoutModeOptical(mParent) ? 15788 setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b); 15789 15790 if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) { 15791 onLayout(changed, l, t, r, b); 15792 mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED; 15793 15794 ListenerInfo li = mListenerInfo; 15795 if (li != null && li.mOnLayoutChangeListeners != null) { 15796 ArrayList<OnLayoutChangeListener> listenersCopy = 15797 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 15798 int numListeners = listenersCopy.size(); 15799 for (int i = 0; i < numListeners; ++i) { 15800 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 15801 } 15802 } 15803 } 15804 15805 mPrivateFlags &= ~PFLAG_FORCE_LAYOUT; 15806 mPrivateFlags3 |= PFLAG3_IS_LAID_OUT; 15807 } 15808 15809 /** 15810 * Called from layout when this view should 15811 * assign a size and position to each of its children. 15812 * 15813 * Derived classes with children should override 15814 * this method and call layout on each of 15815 * their children. 15816 * @param changed This is a new size or position for this view 15817 * @param left Left position, relative to parent 15818 * @param top Top position, relative to parent 15819 * @param right Right position, relative to parent 15820 * @param bottom Bottom position, relative to parent 15821 */ 15822 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 15823 } 15824 15825 /** 15826 * Assign a size and position to this view. 15827 * 15828 * This is called from layout. 15829 * 15830 * @param left Left position, relative to parent 15831 * @param top Top position, relative to parent 15832 * @param right Right position, relative to parent 15833 * @param bottom Bottom position, relative to parent 15834 * @return true if the new size and position are different than the 15835 * previous ones 15836 * {@hide} 15837 */ 15838 protected boolean setFrame(int left, int top, int right, int bottom) { 15839 boolean changed = false; 15840 15841 if (DBG) { 15842 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 15843 + right + "," + bottom + ")"); 15844 } 15845 15846 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 15847 changed = true; 15848 15849 // Remember our drawn bit 15850 int drawn = mPrivateFlags & PFLAG_DRAWN; 15851 15852 int oldWidth = mRight - mLeft; 15853 int oldHeight = mBottom - mTop; 15854 int newWidth = right - left; 15855 int newHeight = bottom - top; 15856 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 15857 15858 // Invalidate our old position 15859 invalidate(sizeChanged); 15860 15861 mLeft = left; 15862 mTop = top; 15863 mRight = right; 15864 mBottom = bottom; 15865 mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 15866 15867 mPrivateFlags |= PFLAG_HAS_BOUNDS; 15868 15869 15870 if (sizeChanged) { 15871 sizeChange(newWidth, newHeight, oldWidth, oldHeight); 15872 } 15873 15874 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) { 15875 // If we are visible, force the DRAWN bit to on so that 15876 // this invalidate will go through (at least to our parent). 15877 // This is because someone may have invalidated this view 15878 // before this call to setFrame came in, thereby clearing 15879 // the DRAWN bit. 15880 mPrivateFlags |= PFLAG_DRAWN; 15881 invalidate(sizeChanged); 15882 // parent display list may need to be recreated based on a change in the bounds 15883 // of any child 15884 invalidateParentCaches(); 15885 } 15886 15887 // Reset drawn bit to original value (invalidate turns it off) 15888 mPrivateFlags |= drawn; 15889 15890 mBackgroundSizeChanged = true; 15891 15892 notifySubtreeAccessibilityStateChangedIfNeeded(); 15893 } 15894 return changed; 15895 } 15896 15897 /** 15898 * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}. 15899 * @hide 15900 */ 15901 public void setLeftTopRightBottom(int left, int top, int right, int bottom) { 15902 setFrame(left, top, right, bottom); 15903 } 15904 15905 private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) { 15906 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 15907 if (mOverlay != null) { 15908 mOverlay.getOverlayView().setRight(newWidth); 15909 mOverlay.getOverlayView().setBottom(newHeight); 15910 } 15911 rebuildOutline(); 15912 } 15913 15914 /** 15915 * Finalize inflating a view from XML. This is called as the last phase 15916 * of inflation, after all child views have been added. 15917 * 15918 * <p>Even if the subclass overrides onFinishInflate, they should always be 15919 * sure to call the super method, so that we get called. 15920 */ 15921 protected void onFinishInflate() { 15922 } 15923 15924 /** 15925 * Returns the resources associated with this view. 15926 * 15927 * @return Resources object. 15928 */ 15929 public Resources getResources() { 15930 return mResources; 15931 } 15932 15933 /** 15934 * Invalidates the specified Drawable. 15935 * 15936 * @param drawable the drawable to invalidate 15937 */ 15938 @Override 15939 public void invalidateDrawable(@NonNull Drawable drawable) { 15940 if (verifyDrawable(drawable)) { 15941 final Rect dirty = drawable.getDirtyBounds(); 15942 final int scrollX = mScrollX; 15943 final int scrollY = mScrollY; 15944 15945 invalidate(dirty.left + scrollX, dirty.top + scrollY, 15946 dirty.right + scrollX, dirty.bottom + scrollY); 15947 rebuildOutline(); 15948 } 15949 } 15950 15951 /** 15952 * Schedules an action on a drawable to occur at a specified time. 15953 * 15954 * @param who the recipient of the action 15955 * @param what the action to run on the drawable 15956 * @param when the time at which the action must occur. Uses the 15957 * {@link SystemClock#uptimeMillis} timebase. 15958 */ 15959 @Override 15960 public void scheduleDrawable(Drawable who, Runnable what, long when) { 15961 if (verifyDrawable(who) && what != null) { 15962 final long delay = when - SystemClock.uptimeMillis(); 15963 if (mAttachInfo != null) { 15964 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 15965 Choreographer.CALLBACK_ANIMATION, what, who, 15966 Choreographer.subtractFrameDelay(delay)); 15967 } else { 15968 ViewRootImpl.getRunQueue().postDelayed(what, delay); 15969 } 15970 } 15971 } 15972 15973 /** 15974 * Cancels a scheduled action on a drawable. 15975 * 15976 * @param who the recipient of the action 15977 * @param what the action to cancel 15978 */ 15979 @Override 15980 public void unscheduleDrawable(Drawable who, Runnable what) { 15981 if (verifyDrawable(who) && what != null) { 15982 if (mAttachInfo != null) { 15983 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 15984 Choreographer.CALLBACK_ANIMATION, what, who); 15985 } 15986 ViewRootImpl.getRunQueue().removeCallbacks(what); 15987 } 15988 } 15989 15990 /** 15991 * Unschedule any events associated with the given Drawable. This can be 15992 * used when selecting a new Drawable into a view, so that the previous 15993 * one is completely unscheduled. 15994 * 15995 * @param who The Drawable to unschedule. 15996 * 15997 * @see #drawableStateChanged 15998 */ 15999 public void unscheduleDrawable(Drawable who) { 16000 if (mAttachInfo != null && who != null) { 16001 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 16002 Choreographer.CALLBACK_ANIMATION, null, who); 16003 } 16004 } 16005 16006 /** 16007 * Resolve the Drawables depending on the layout direction. This is implicitly supposing 16008 * that the View directionality can and will be resolved before its Drawables. 16009 * 16010 * Will call {@link View#onResolveDrawables} when resolution is done. 16011 * 16012 * @hide 16013 */ 16014 protected void resolveDrawables() { 16015 // Drawables resolution may need to happen before resolving the layout direction (which is 16016 // done only during the measure() call). 16017 // If the layout direction is not resolved yet, we cannot resolve the Drawables except in 16018 // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT. 16019 // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or 16020 // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout 16021 // direction to be resolved as its resolved value will be the same as its raw value. 16022 if (!isLayoutDirectionResolved() && 16023 getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) { 16024 return; 16025 } 16026 16027 final int layoutDirection = isLayoutDirectionResolved() ? 16028 getLayoutDirection() : getRawLayoutDirection(); 16029 16030 if (mBackground != null) { 16031 mBackground.setLayoutDirection(layoutDirection); 16032 } 16033 mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED; 16034 onResolveDrawables(layoutDirection); 16035 } 16036 16037 boolean areDrawablesResolved() { 16038 return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED; 16039 } 16040 16041 /** 16042 * Called when layout direction has been resolved. 16043 * 16044 * The default implementation does nothing. 16045 * 16046 * @param layoutDirection The resolved layout direction. 16047 * 16048 * @see #LAYOUT_DIRECTION_LTR 16049 * @see #LAYOUT_DIRECTION_RTL 16050 * 16051 * @hide 16052 */ 16053 public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) { 16054 } 16055 16056 /** 16057 * @hide 16058 */ 16059 protected void resetResolvedDrawables() { 16060 resetResolvedDrawablesInternal(); 16061 } 16062 16063 void resetResolvedDrawablesInternal() { 16064 mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED; 16065 } 16066 16067 /** 16068 * If your view subclass is displaying its own Drawable objects, it should 16069 * override this function and return true for any Drawable it is 16070 * displaying. This allows animations for those drawables to be 16071 * scheduled. 16072 * 16073 * <p>Be sure to call through to the super class when overriding this 16074 * function. 16075 * 16076 * @param who The Drawable to verify. Return true if it is one you are 16077 * displaying, else return the result of calling through to the 16078 * super class. 16079 * 16080 * @return boolean If true than the Drawable is being displayed in the 16081 * view; else false and it is not allowed to animate. 16082 * 16083 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 16084 * @see #drawableStateChanged() 16085 */ 16086 protected boolean verifyDrawable(Drawable who) { 16087 return who == mBackground; 16088 } 16089 16090 /** 16091 * This function is called whenever the state of the view changes in such 16092 * a way that it impacts the state of drawables being shown. 16093 * <p> 16094 * If the View has a StateListAnimator, it will also be called to run necessary state 16095 * change animations. 16096 * <p> 16097 * Be sure to call through to the superclass when overriding this function. 16098 * 16099 * @see Drawable#setState(int[]) 16100 */ 16101 protected void drawableStateChanged() { 16102 final Drawable d = mBackground; 16103 if (d != null && d.isStateful()) { 16104 d.setState(getDrawableState()); 16105 } 16106 16107 if (mStateListAnimator != null) { 16108 mStateListAnimator.setState(getDrawableState()); 16109 } 16110 } 16111 16112 /** 16113 * This function is called whenever the view hotspot changes and needs to 16114 * be propagated to drawables or child views managed by the view. 16115 * <p> 16116 * Dispatching to child views is handled by 16117 * {@link #dispatchDrawableHotspotChanged(float, float)}. 16118 * <p> 16119 * Be sure to call through to the superclass when overriding this function. 16120 * 16121 * @param x hotspot x coordinate 16122 * @param y hotspot y coordinate 16123 */ 16124 public void drawableHotspotChanged(float x, float y) { 16125 if (mBackground != null) { 16126 mBackground.setHotspot(x, y); 16127 } 16128 16129 dispatchDrawableHotspotChanged(x, y); 16130 } 16131 16132 /** 16133 * Dispatches drawableHotspotChanged to all of this View's children. 16134 * 16135 * @param x hotspot x coordinate 16136 * @param y hotspot y coordinate 16137 * @see #drawableHotspotChanged(float, float) 16138 */ 16139 public void dispatchDrawableHotspotChanged(float x, float y) { 16140 } 16141 16142 /** 16143 * Call this to force a view to update its drawable state. This will cause 16144 * drawableStateChanged to be called on this view. Views that are interested 16145 * in the new state should call getDrawableState. 16146 * 16147 * @see #drawableStateChanged 16148 * @see #getDrawableState 16149 */ 16150 public void refreshDrawableState() { 16151 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 16152 drawableStateChanged(); 16153 16154 ViewParent parent = mParent; 16155 if (parent != null) { 16156 parent.childDrawableStateChanged(this); 16157 } 16158 } 16159 16160 /** 16161 * Return an array of resource IDs of the drawable states representing the 16162 * current state of the view. 16163 * 16164 * @return The current drawable state 16165 * 16166 * @see Drawable#setState(int[]) 16167 * @see #drawableStateChanged() 16168 * @see #onCreateDrawableState(int) 16169 */ 16170 public final int[] getDrawableState() { 16171 if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) { 16172 return mDrawableState; 16173 } else { 16174 mDrawableState = onCreateDrawableState(0); 16175 mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY; 16176 return mDrawableState; 16177 } 16178 } 16179 16180 /** 16181 * Generate the new {@link android.graphics.drawable.Drawable} state for 16182 * this view. This is called by the view 16183 * system when the cached Drawable state is determined to be invalid. To 16184 * retrieve the current state, you should use {@link #getDrawableState}. 16185 * 16186 * @param extraSpace if non-zero, this is the number of extra entries you 16187 * would like in the returned array in which you can place your own 16188 * states. 16189 * 16190 * @return Returns an array holding the current {@link Drawable} state of 16191 * the view. 16192 * 16193 * @see #mergeDrawableStates(int[], int[]) 16194 */ 16195 protected int[] onCreateDrawableState(int extraSpace) { 16196 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 16197 mParent instanceof View) { 16198 return ((View) mParent).onCreateDrawableState(extraSpace); 16199 } 16200 16201 int[] drawableState; 16202 16203 int privateFlags = mPrivateFlags; 16204 16205 int viewStateIndex = 0; 16206 if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED; 16207 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED; 16208 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED; 16209 if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED; 16210 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED; 16211 if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED; 16212 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 16213 HardwareRenderer.isAvailable()) { 16214 // This is set if HW acceleration is requested, even if the current 16215 // process doesn't allow it. This is just to allow app preview 16216 // windows to better match their app. 16217 viewStateIndex |= VIEW_STATE_ACCELERATED; 16218 } 16219 if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED; 16220 16221 final int privateFlags2 = mPrivateFlags2; 16222 if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT; 16223 if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED; 16224 16225 drawableState = VIEW_STATE_SETS[viewStateIndex]; 16226 16227 //noinspection ConstantIfStatement 16228 if (false) { 16229 Log.i("View", "drawableStateIndex=" + viewStateIndex); 16230 Log.i("View", toString() 16231 + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0) 16232 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 16233 + " fo=" + hasFocus() 16234 + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0) 16235 + " wf=" + hasWindowFocus() 16236 + ": " + Arrays.toString(drawableState)); 16237 } 16238 16239 if (extraSpace == 0) { 16240 return drawableState; 16241 } 16242 16243 final int[] fullState; 16244 if (drawableState != null) { 16245 fullState = new int[drawableState.length + extraSpace]; 16246 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 16247 } else { 16248 fullState = new int[extraSpace]; 16249 } 16250 16251 return fullState; 16252 } 16253 16254 /** 16255 * Merge your own state values in <var>additionalState</var> into the base 16256 * state values <var>baseState</var> that were returned by 16257 * {@link #onCreateDrawableState(int)}. 16258 * 16259 * @param baseState The base state values returned by 16260 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 16261 * own additional state values. 16262 * 16263 * @param additionalState The additional state values you would like 16264 * added to <var>baseState</var>; this array is not modified. 16265 * 16266 * @return As a convenience, the <var>baseState</var> array you originally 16267 * passed into the function is returned. 16268 * 16269 * @see #onCreateDrawableState(int) 16270 */ 16271 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 16272 final int N = baseState.length; 16273 int i = N - 1; 16274 while (i >= 0 && baseState[i] == 0) { 16275 i--; 16276 } 16277 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 16278 return baseState; 16279 } 16280 16281 /** 16282 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 16283 * on all Drawable objects associated with this view. 16284 * <p> 16285 * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator 16286 * attached to this view. 16287 */ 16288 public void jumpDrawablesToCurrentState() { 16289 if (mBackground != null) { 16290 mBackground.jumpToCurrentState(); 16291 } 16292 if (mStateListAnimator != null) { 16293 mStateListAnimator.jumpToCurrentState(); 16294 } 16295 } 16296 16297 /** 16298 * Sets the background color for this view. 16299 * @param color the color of the background 16300 */ 16301 @RemotableViewMethod 16302 public void setBackgroundColor(int color) { 16303 if (mBackground instanceof ColorDrawable) { 16304 ((ColorDrawable) mBackground.mutate()).setColor(color); 16305 computeOpaqueFlags(); 16306 mBackgroundResource = 0; 16307 } else { 16308 setBackground(new ColorDrawable(color)); 16309 } 16310 } 16311 16312 /** 16313 * Set the background to a given resource. The resource should refer to 16314 * a Drawable object or 0 to remove the background. 16315 * @param resid The identifier of the resource. 16316 * 16317 * @attr ref android.R.styleable#View_background 16318 */ 16319 @RemotableViewMethod 16320 public void setBackgroundResource(int resid) { 16321 if (resid != 0 && resid == mBackgroundResource) { 16322 return; 16323 } 16324 16325 Drawable d = null; 16326 if (resid != 0) { 16327 d = mContext.getDrawable(resid); 16328 } 16329 setBackground(d); 16330 16331 mBackgroundResource = resid; 16332 } 16333 16334 /** 16335 * Set the background to a given Drawable, or remove the background. If the 16336 * background has padding, this View's padding is set to the background's 16337 * padding. However, when a background is removed, this View's padding isn't 16338 * touched. If setting the padding is desired, please use 16339 * {@link #setPadding(int, int, int, int)}. 16340 * 16341 * @param background The Drawable to use as the background, or null to remove the 16342 * background 16343 */ 16344 public void setBackground(Drawable background) { 16345 //noinspection deprecation 16346 setBackgroundDrawable(background); 16347 } 16348 16349 /** 16350 * @deprecated use {@link #setBackground(Drawable)} instead 16351 */ 16352 @Deprecated 16353 public void setBackgroundDrawable(Drawable background) { 16354 computeOpaqueFlags(); 16355 16356 if (background == mBackground) { 16357 return; 16358 } 16359 16360 boolean requestLayout = false; 16361 16362 mBackgroundResource = 0; 16363 16364 /* 16365 * Regardless of whether we're setting a new background or not, we want 16366 * to clear the previous drawable. 16367 */ 16368 if (mBackground != null) { 16369 mBackground.setCallback(null); 16370 unscheduleDrawable(mBackground); 16371 } 16372 16373 if (background != null) { 16374 Rect padding = sThreadLocal.get(); 16375 if (padding == null) { 16376 padding = new Rect(); 16377 sThreadLocal.set(padding); 16378 } 16379 resetResolvedDrawablesInternal(); 16380 background.setLayoutDirection(getLayoutDirection()); 16381 if (background.getPadding(padding)) { 16382 resetResolvedPaddingInternal(); 16383 switch (background.getLayoutDirection()) { 16384 case LAYOUT_DIRECTION_RTL: 16385 mUserPaddingLeftInitial = padding.right; 16386 mUserPaddingRightInitial = padding.left; 16387 internalSetPadding(padding.right, padding.top, padding.left, padding.bottom); 16388 break; 16389 case LAYOUT_DIRECTION_LTR: 16390 default: 16391 mUserPaddingLeftInitial = padding.left; 16392 mUserPaddingRightInitial = padding.right; 16393 internalSetPadding(padding.left, padding.top, padding.right, padding.bottom); 16394 } 16395 mLeftPaddingDefined = false; 16396 mRightPaddingDefined = false; 16397 } 16398 16399 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 16400 // if it has a different minimum size, we should layout again 16401 if (mBackground == null 16402 || mBackground.getMinimumHeight() != background.getMinimumHeight() 16403 || mBackground.getMinimumWidth() != background.getMinimumWidth()) { 16404 requestLayout = true; 16405 } 16406 16407 background.setCallback(this); 16408 if (background.isStateful()) { 16409 background.setState(getDrawableState()); 16410 } 16411 background.setVisible(getVisibility() == VISIBLE, false); 16412 mBackground = background; 16413 16414 applyBackgroundTint(); 16415 16416 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 16417 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 16418 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 16419 requestLayout = true; 16420 } 16421 } else { 16422 /* Remove the background */ 16423 mBackground = null; 16424 16425 if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) { 16426 /* 16427 * This view ONLY drew the background before and we're removing 16428 * the background, so now it won't draw anything 16429 * (hence we SKIP_DRAW) 16430 */ 16431 mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND; 16432 mPrivateFlags |= PFLAG_SKIP_DRAW; 16433 } 16434 16435 /* 16436 * When the background is set, we try to apply its padding to this 16437 * View. When the background is removed, we don't touch this View's 16438 * padding. This is noted in the Javadocs. Hence, we don't need to 16439 * requestLayout(), the invalidate() below is sufficient. 16440 */ 16441 16442 // The old background's minimum size could have affected this 16443 // View's layout, so let's requestLayout 16444 requestLayout = true; 16445 } 16446 16447 computeOpaqueFlags(); 16448 16449 if (requestLayout) { 16450 requestLayout(); 16451 } 16452 16453 mBackgroundSizeChanged = true; 16454 invalidate(true); 16455 } 16456 16457 /** 16458 * Gets the background drawable 16459 * 16460 * @return The drawable used as the background for this view, if any. 16461 * 16462 * @see #setBackground(Drawable) 16463 * 16464 * @attr ref android.R.styleable#View_background 16465 */ 16466 public Drawable getBackground() { 16467 return mBackground; 16468 } 16469 16470 /** 16471 * Applies a tint to the background drawable. Does not modify the current tint 16472 * mode, which is {@link PorterDuff.Mode#SRC_IN} by default. 16473 * <p> 16474 * Subsequent calls to {@link #setBackground(Drawable)} will automatically 16475 * mutate the drawable and apply the specified tint and tint mode using 16476 * {@link Drawable#setTintList(ColorStateList)}. 16477 * 16478 * @param tint the tint to apply, may be {@code null} to clear tint 16479 * 16480 * @attr ref android.R.styleable#View_backgroundTint 16481 * @see #getBackgroundTintList() 16482 * @see Drawable#setTintList(ColorStateList) 16483 */ 16484 public void setBackgroundTintList(@Nullable ColorStateList tint) { 16485 if (mBackgroundTint == null) { 16486 mBackgroundTint = new TintInfo(); 16487 } 16488 mBackgroundTint.mTintList = tint; 16489 mBackgroundTint.mHasTintList = true; 16490 16491 applyBackgroundTint(); 16492 } 16493 16494 /** 16495 * Return the tint applied to the background drawable, if specified. 16496 * 16497 * @return the tint applied to the background drawable 16498 * @attr ref android.R.styleable#View_backgroundTint 16499 * @see #setBackgroundTintList(ColorStateList) 16500 */ 16501 @Nullable 16502 public ColorStateList getBackgroundTintList() { 16503 return mBackgroundTint != null ? mBackgroundTint.mTintList : null; 16504 } 16505 16506 /** 16507 * Specifies the blending mode used to apply the tint specified by 16508 * {@link #setBackgroundTintList(ColorStateList)}} to the background 16509 * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}. 16510 * 16511 * @param tintMode the blending mode used to apply the tint, may be 16512 * {@code null} to clear tint 16513 * @attr ref android.R.styleable#View_backgroundTintMode 16514 * @see #getBackgroundTintMode() 16515 * @see Drawable#setTintMode(PorterDuff.Mode) 16516 */ 16517 public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) { 16518 if (mBackgroundTint == null) { 16519 mBackgroundTint = new TintInfo(); 16520 } 16521 mBackgroundTint.mTintMode = tintMode; 16522 mBackgroundTint.mHasTintMode = true; 16523 16524 applyBackgroundTint(); 16525 } 16526 16527 /** 16528 * Return the blending mode used to apply the tint to the background 16529 * drawable, if specified. 16530 * 16531 * @return the blending mode used to apply the tint to the background 16532 * drawable 16533 * @attr ref android.R.styleable#View_backgroundTintMode 16534 * @see #setBackgroundTintMode(PorterDuff.Mode) 16535 */ 16536 @Nullable 16537 public PorterDuff.Mode getBackgroundTintMode() { 16538 return mBackgroundTint != null ? mBackgroundTint.mTintMode : null; 16539 } 16540 16541 private void applyBackgroundTint() { 16542 if (mBackground != null && mBackgroundTint != null) { 16543 final TintInfo tintInfo = mBackgroundTint; 16544 if (tintInfo.mHasTintList || tintInfo.mHasTintMode) { 16545 mBackground = mBackground.mutate(); 16546 16547 if (tintInfo.mHasTintList) { 16548 mBackground.setTintList(tintInfo.mTintList); 16549 } 16550 16551 if (tintInfo.mHasTintMode) { 16552 mBackground.setTintMode(tintInfo.mTintMode); 16553 } 16554 16555 // The drawable (or one of its children) may not have been 16556 // stateful before applying the tint, so let's try again. 16557 if (mBackground.isStateful()) { 16558 mBackground.setState(getDrawableState()); 16559 } 16560 } 16561 } 16562 } 16563 16564 /** 16565 * Sets the padding. The view may add on the space required to display 16566 * the scrollbars, depending on the style and visibility of the scrollbars. 16567 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 16568 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 16569 * from the values set in this call. 16570 * 16571 * @attr ref android.R.styleable#View_padding 16572 * @attr ref android.R.styleable#View_paddingBottom 16573 * @attr ref android.R.styleable#View_paddingLeft 16574 * @attr ref android.R.styleable#View_paddingRight 16575 * @attr ref android.R.styleable#View_paddingTop 16576 * @param left the left padding in pixels 16577 * @param top the top padding in pixels 16578 * @param right the right padding in pixels 16579 * @param bottom the bottom padding in pixels 16580 */ 16581 public void setPadding(int left, int top, int right, int bottom) { 16582 resetResolvedPaddingInternal(); 16583 16584 mUserPaddingStart = UNDEFINED_PADDING; 16585 mUserPaddingEnd = UNDEFINED_PADDING; 16586 16587 mUserPaddingLeftInitial = left; 16588 mUserPaddingRightInitial = right; 16589 16590 mLeftPaddingDefined = true; 16591 mRightPaddingDefined = true; 16592 16593 internalSetPadding(left, top, right, bottom); 16594 } 16595 16596 /** 16597 * @hide 16598 */ 16599 protected void internalSetPadding(int left, int top, int right, int bottom) { 16600 mUserPaddingLeft = left; 16601 mUserPaddingRight = right; 16602 mUserPaddingBottom = bottom; 16603 16604 final int viewFlags = mViewFlags; 16605 boolean changed = false; 16606 16607 // Common case is there are no scroll bars. 16608 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 16609 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 16610 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 16611 ? 0 : getVerticalScrollbarWidth(); 16612 switch (mVerticalScrollbarPosition) { 16613 case SCROLLBAR_POSITION_DEFAULT: 16614 if (isLayoutRtl()) { 16615 left += offset; 16616 } else { 16617 right += offset; 16618 } 16619 break; 16620 case SCROLLBAR_POSITION_RIGHT: 16621 right += offset; 16622 break; 16623 case SCROLLBAR_POSITION_LEFT: 16624 left += offset; 16625 break; 16626 } 16627 } 16628 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 16629 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 16630 ? 0 : getHorizontalScrollbarHeight(); 16631 } 16632 } 16633 16634 if (mPaddingLeft != left) { 16635 changed = true; 16636 mPaddingLeft = left; 16637 } 16638 if (mPaddingTop != top) { 16639 changed = true; 16640 mPaddingTop = top; 16641 } 16642 if (mPaddingRight != right) { 16643 changed = true; 16644 mPaddingRight = right; 16645 } 16646 if (mPaddingBottom != bottom) { 16647 changed = true; 16648 mPaddingBottom = bottom; 16649 } 16650 16651 if (changed) { 16652 requestLayout(); 16653 } 16654 } 16655 16656 /** 16657 * Sets the relative padding. The view may add on the space required to display 16658 * the scrollbars, depending on the style and visibility of the scrollbars. 16659 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 16660 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 16661 * from the values set in this call. 16662 * 16663 * @attr ref android.R.styleable#View_padding 16664 * @attr ref android.R.styleable#View_paddingBottom 16665 * @attr ref android.R.styleable#View_paddingStart 16666 * @attr ref android.R.styleable#View_paddingEnd 16667 * @attr ref android.R.styleable#View_paddingTop 16668 * @param start the start padding in pixels 16669 * @param top the top padding in pixels 16670 * @param end the end padding in pixels 16671 * @param bottom the bottom padding in pixels 16672 */ 16673 public void setPaddingRelative(int start, int top, int end, int bottom) { 16674 resetResolvedPaddingInternal(); 16675 16676 mUserPaddingStart = start; 16677 mUserPaddingEnd = end; 16678 mLeftPaddingDefined = true; 16679 mRightPaddingDefined = true; 16680 16681 switch(getLayoutDirection()) { 16682 case LAYOUT_DIRECTION_RTL: 16683 mUserPaddingLeftInitial = end; 16684 mUserPaddingRightInitial = start; 16685 internalSetPadding(end, top, start, bottom); 16686 break; 16687 case LAYOUT_DIRECTION_LTR: 16688 default: 16689 mUserPaddingLeftInitial = start; 16690 mUserPaddingRightInitial = end; 16691 internalSetPadding(start, top, end, bottom); 16692 } 16693 } 16694 16695 /** 16696 * Returns the top padding of this view. 16697 * 16698 * @return the top padding in pixels 16699 */ 16700 public int getPaddingTop() { 16701 return mPaddingTop; 16702 } 16703 16704 /** 16705 * Returns the bottom padding of this view. If there are inset and enabled 16706 * scrollbars, this value may include the space required to display the 16707 * scrollbars as well. 16708 * 16709 * @return the bottom padding in pixels 16710 */ 16711 public int getPaddingBottom() { 16712 return mPaddingBottom; 16713 } 16714 16715 /** 16716 * Returns the left padding of this view. If there are inset and enabled 16717 * scrollbars, this value may include the space required to display the 16718 * scrollbars as well. 16719 * 16720 * @return the left padding in pixels 16721 */ 16722 public int getPaddingLeft() { 16723 if (!isPaddingResolved()) { 16724 resolvePadding(); 16725 } 16726 return mPaddingLeft; 16727 } 16728 16729 /** 16730 * Returns the start padding of this view depending on its resolved layout direction. 16731 * If there are inset and enabled scrollbars, this value may include the space 16732 * required to display the scrollbars as well. 16733 * 16734 * @return the start padding in pixels 16735 */ 16736 public int getPaddingStart() { 16737 if (!isPaddingResolved()) { 16738 resolvePadding(); 16739 } 16740 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 16741 mPaddingRight : mPaddingLeft; 16742 } 16743 16744 /** 16745 * Returns the right padding of this view. If there are inset and enabled 16746 * scrollbars, this value may include the space required to display the 16747 * scrollbars as well. 16748 * 16749 * @return the right padding in pixels 16750 */ 16751 public int getPaddingRight() { 16752 if (!isPaddingResolved()) { 16753 resolvePadding(); 16754 } 16755 return mPaddingRight; 16756 } 16757 16758 /** 16759 * Returns the end padding of this view depending on its resolved layout direction. 16760 * If there are inset and enabled scrollbars, this value may include the space 16761 * required to display the scrollbars as well. 16762 * 16763 * @return the end padding in pixels 16764 */ 16765 public int getPaddingEnd() { 16766 if (!isPaddingResolved()) { 16767 resolvePadding(); 16768 } 16769 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 16770 mPaddingLeft : mPaddingRight; 16771 } 16772 16773 /** 16774 * Return if the padding as been set thru relative values 16775 * {@link #setPaddingRelative(int, int, int, int)} or thru 16776 * @attr ref android.R.styleable#View_paddingStart or 16777 * @attr ref android.R.styleable#View_paddingEnd 16778 * 16779 * @return true if the padding is relative or false if it is not. 16780 */ 16781 public boolean isPaddingRelative() { 16782 return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING); 16783 } 16784 16785 Insets computeOpticalInsets() { 16786 return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets(); 16787 } 16788 16789 /** 16790 * @hide 16791 */ 16792 public void resetPaddingToInitialValues() { 16793 if (isRtlCompatibilityMode()) { 16794 mPaddingLeft = mUserPaddingLeftInitial; 16795 mPaddingRight = mUserPaddingRightInitial; 16796 return; 16797 } 16798 if (isLayoutRtl()) { 16799 mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial; 16800 mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial; 16801 } else { 16802 mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial; 16803 mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial; 16804 } 16805 } 16806 16807 /** 16808 * @hide 16809 */ 16810 public Insets getOpticalInsets() { 16811 if (mLayoutInsets == null) { 16812 mLayoutInsets = computeOpticalInsets(); 16813 } 16814 return mLayoutInsets; 16815 } 16816 16817 /** 16818 * Set this view's optical insets. 16819 * 16820 * <p>This method should be treated similarly to setMeasuredDimension and not as a general 16821 * property. Views that compute their own optical insets should call it as part of measurement. 16822 * This method does not request layout. If you are setting optical insets outside of 16823 * measure/layout itself you will want to call requestLayout() yourself. 16824 * </p> 16825 * @hide 16826 */ 16827 public void setOpticalInsets(Insets insets) { 16828 mLayoutInsets = insets; 16829 } 16830 16831 /** 16832 * Changes the selection state of this view. A view can be selected or not. 16833 * Note that selection is not the same as focus. Views are typically 16834 * selected in the context of an AdapterView like ListView or GridView; 16835 * the selected view is the view that is highlighted. 16836 * 16837 * @param selected true if the view must be selected, false otherwise 16838 */ 16839 public void setSelected(boolean selected) { 16840 //noinspection DoubleNegation 16841 if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) { 16842 mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0); 16843 if (!selected) resetPressedState(); 16844 invalidate(true); 16845 refreshDrawableState(); 16846 dispatchSetSelected(selected); 16847 if (selected) { 16848 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED); 16849 } else { 16850 notifyViewAccessibilityStateChangedIfNeeded( 16851 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 16852 } 16853 } 16854 } 16855 16856 /** 16857 * Dispatch setSelected to all of this View's children. 16858 * 16859 * @see #setSelected(boolean) 16860 * 16861 * @param selected The new selected state 16862 */ 16863 protected void dispatchSetSelected(boolean selected) { 16864 } 16865 16866 /** 16867 * Indicates the selection state of this view. 16868 * 16869 * @return true if the view is selected, false otherwise 16870 */ 16871 @ViewDebug.ExportedProperty 16872 public boolean isSelected() { 16873 return (mPrivateFlags & PFLAG_SELECTED) != 0; 16874 } 16875 16876 /** 16877 * Changes the activated state of this view. A view can be activated or not. 16878 * Note that activation is not the same as selection. Selection is 16879 * a transient property, representing the view (hierarchy) the user is 16880 * currently interacting with. Activation is a longer-term state that the 16881 * user can move views in and out of. For example, in a list view with 16882 * single or multiple selection enabled, the views in the current selection 16883 * set are activated. (Um, yeah, we are deeply sorry about the terminology 16884 * here.) The activated state is propagated down to children of the view it 16885 * is set on. 16886 * 16887 * @param activated true if the view must be activated, false otherwise 16888 */ 16889 public void setActivated(boolean activated) { 16890 //noinspection DoubleNegation 16891 if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) { 16892 mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0); 16893 invalidate(true); 16894 refreshDrawableState(); 16895 dispatchSetActivated(activated); 16896 } 16897 } 16898 16899 /** 16900 * Dispatch setActivated to all of this View's children. 16901 * 16902 * @see #setActivated(boolean) 16903 * 16904 * @param activated The new activated state 16905 */ 16906 protected void dispatchSetActivated(boolean activated) { 16907 } 16908 16909 /** 16910 * Indicates the activation state of this view. 16911 * 16912 * @return true if the view is activated, false otherwise 16913 */ 16914 @ViewDebug.ExportedProperty 16915 public boolean isActivated() { 16916 return (mPrivateFlags & PFLAG_ACTIVATED) != 0; 16917 } 16918 16919 /** 16920 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 16921 * observer can be used to get notifications when global events, like 16922 * layout, happen. 16923 * 16924 * The returned ViewTreeObserver observer is not guaranteed to remain 16925 * valid for the lifetime of this View. If the caller of this method keeps 16926 * a long-lived reference to ViewTreeObserver, it should always check for 16927 * the return value of {@link ViewTreeObserver#isAlive()}. 16928 * 16929 * @return The ViewTreeObserver for this view's hierarchy. 16930 */ 16931 public ViewTreeObserver getViewTreeObserver() { 16932 if (mAttachInfo != null) { 16933 return mAttachInfo.mTreeObserver; 16934 } 16935 if (mFloatingTreeObserver == null) { 16936 mFloatingTreeObserver = new ViewTreeObserver(); 16937 } 16938 return mFloatingTreeObserver; 16939 } 16940 16941 /** 16942 * <p>Finds the topmost view in the current view hierarchy.</p> 16943 * 16944 * @return the topmost view containing this view 16945 */ 16946 public View getRootView() { 16947 if (mAttachInfo != null) { 16948 final View v = mAttachInfo.mRootView; 16949 if (v != null) { 16950 return v; 16951 } 16952 } 16953 16954 View parent = this; 16955 16956 while (parent.mParent != null && parent.mParent instanceof View) { 16957 parent = (View) parent.mParent; 16958 } 16959 16960 return parent; 16961 } 16962 16963 /** 16964 * Transforms a motion event from view-local coordinates to on-screen 16965 * coordinates. 16966 * 16967 * @param ev the view-local motion event 16968 * @return false if the transformation could not be applied 16969 * @hide 16970 */ 16971 public boolean toGlobalMotionEvent(MotionEvent ev) { 16972 final AttachInfo info = mAttachInfo; 16973 if (info == null) { 16974 return false; 16975 } 16976 16977 final Matrix m = info.mTmpMatrix; 16978 m.set(Matrix.IDENTITY_MATRIX); 16979 transformMatrixToGlobal(m); 16980 ev.transform(m); 16981 return true; 16982 } 16983 16984 /** 16985 * Transforms a motion event from on-screen coordinates to view-local 16986 * coordinates. 16987 * 16988 * @param ev the on-screen motion event 16989 * @return false if the transformation could not be applied 16990 * @hide 16991 */ 16992 public boolean toLocalMotionEvent(MotionEvent ev) { 16993 final AttachInfo info = mAttachInfo; 16994 if (info == null) { 16995 return false; 16996 } 16997 16998 final Matrix m = info.mTmpMatrix; 16999 m.set(Matrix.IDENTITY_MATRIX); 17000 transformMatrixToLocal(m); 17001 ev.transform(m); 17002 return true; 17003 } 17004 17005 /** 17006 * Modifies the input matrix such that it maps view-local coordinates to 17007 * on-screen coordinates. 17008 * 17009 * @param m input matrix to modify 17010 * @hide 17011 */ 17012 public void transformMatrixToGlobal(Matrix m) { 17013 final ViewParent parent = mParent; 17014 if (parent instanceof View) { 17015 final View vp = (View) parent; 17016 vp.transformMatrixToGlobal(m); 17017 m.preTranslate(-vp.mScrollX, -vp.mScrollY); 17018 } else if (parent instanceof ViewRootImpl) { 17019 final ViewRootImpl vr = (ViewRootImpl) parent; 17020 vr.transformMatrixToGlobal(m); 17021 m.preTranslate(0, -vr.mCurScrollY); 17022 } 17023 17024 m.preTranslate(mLeft, mTop); 17025 17026 if (!hasIdentityMatrix()) { 17027 m.preConcat(getMatrix()); 17028 } 17029 } 17030 17031 /** 17032 * Modifies the input matrix such that it maps on-screen coordinates to 17033 * view-local coordinates. 17034 * 17035 * @param m input matrix to modify 17036 * @hide 17037 */ 17038 public void transformMatrixToLocal(Matrix m) { 17039 final ViewParent parent = mParent; 17040 if (parent instanceof View) { 17041 final View vp = (View) parent; 17042 vp.transformMatrixToLocal(m); 17043 m.postTranslate(vp.mScrollX, vp.mScrollY); 17044 } else if (parent instanceof ViewRootImpl) { 17045 final ViewRootImpl vr = (ViewRootImpl) parent; 17046 vr.transformMatrixToLocal(m); 17047 m.postTranslate(0, vr.mCurScrollY); 17048 } 17049 17050 m.postTranslate(-mLeft, -mTop); 17051 17052 if (!hasIdentityMatrix()) { 17053 m.postConcat(getInverseMatrix()); 17054 } 17055 } 17056 17057 /** 17058 * @hide 17059 */ 17060 @ViewDebug.ExportedProperty(category = "layout", indexMapping = { 17061 @ViewDebug.IntToString(from = 0, to = "x"), 17062 @ViewDebug.IntToString(from = 1, to = "y") 17063 }) 17064 public int[] getLocationOnScreen() { 17065 int[] location = new int[2]; 17066 getLocationOnScreen(location); 17067 return location; 17068 } 17069 17070 /** 17071 * <p>Computes the coordinates of this view on the screen. The argument 17072 * must be an array of two integers. After the method returns, the array 17073 * contains the x and y location in that order.</p> 17074 * 17075 * @param location an array of two integers in which to hold the coordinates 17076 */ 17077 public void getLocationOnScreen(int[] location) { 17078 getLocationInWindow(location); 17079 17080 final AttachInfo info = mAttachInfo; 17081 if (info != null) { 17082 location[0] += info.mWindowLeft; 17083 location[1] += info.mWindowTop; 17084 } 17085 } 17086 17087 /** 17088 * <p>Computes the coordinates of this view in its window. The argument 17089 * must be an array of two integers. After the method returns, the array 17090 * contains the x and y location in that order.</p> 17091 * 17092 * @param location an array of two integers in which to hold the coordinates 17093 */ 17094 public void getLocationInWindow(int[] location) { 17095 if (location == null || location.length < 2) { 17096 throw new IllegalArgumentException("location must be an array of two integers"); 17097 } 17098 17099 if (mAttachInfo == null) { 17100 // When the view is not attached to a window, this method does not make sense 17101 location[0] = location[1] = 0; 17102 return; 17103 } 17104 17105 float[] position = mAttachInfo.mTmpTransformLocation; 17106 position[0] = position[1] = 0.0f; 17107 17108 if (!hasIdentityMatrix()) { 17109 getMatrix().mapPoints(position); 17110 } 17111 17112 position[0] += mLeft; 17113 position[1] += mTop; 17114 17115 ViewParent viewParent = mParent; 17116 while (viewParent instanceof View) { 17117 final View view = (View) viewParent; 17118 17119 position[0] -= view.mScrollX; 17120 position[1] -= view.mScrollY; 17121 17122 if (!view.hasIdentityMatrix()) { 17123 view.getMatrix().mapPoints(position); 17124 } 17125 17126 position[0] += view.mLeft; 17127 position[1] += view.mTop; 17128 17129 viewParent = view.mParent; 17130 } 17131 17132 if (viewParent instanceof ViewRootImpl) { 17133 // *cough* 17134 final ViewRootImpl vr = (ViewRootImpl) viewParent; 17135 position[1] -= vr.mCurScrollY; 17136 } 17137 17138 location[0] = (int) (position[0] + 0.5f); 17139 location[1] = (int) (position[1] + 0.5f); 17140 } 17141 17142 /** 17143 * {@hide} 17144 * @param id the id of the view to be found 17145 * @return the view of the specified id, null if cannot be found 17146 */ 17147 protected View findViewTraversal(int id) { 17148 if (id == mID) { 17149 return this; 17150 } 17151 return null; 17152 } 17153 17154 /** 17155 * {@hide} 17156 * @param tag the tag of the view to be found 17157 * @return the view of specified tag, null if cannot be found 17158 */ 17159 protected View findViewWithTagTraversal(Object tag) { 17160 if (tag != null && tag.equals(mTag)) { 17161 return this; 17162 } 17163 return null; 17164 } 17165 17166 /** 17167 * {@hide} 17168 * @param predicate The predicate to evaluate. 17169 * @param childToSkip If not null, ignores this child during the recursive traversal. 17170 * @return The first view that matches the predicate or null. 17171 */ 17172 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 17173 if (predicate.apply(this)) { 17174 return this; 17175 } 17176 return null; 17177 } 17178 17179 /** 17180 * Look for a child view with the given id. If this view has the given 17181 * id, return this view. 17182 * 17183 * @param id The id to search for. 17184 * @return The view that has the given id in the hierarchy or null 17185 */ 17186 public final View findViewById(int id) { 17187 if (id < 0) { 17188 return null; 17189 } 17190 return findViewTraversal(id); 17191 } 17192 17193 /** 17194 * Finds a view by its unuque and stable accessibility id. 17195 * 17196 * @param accessibilityId The searched accessibility id. 17197 * @return The found view. 17198 */ 17199 final View findViewByAccessibilityId(int accessibilityId) { 17200 if (accessibilityId < 0) { 17201 return null; 17202 } 17203 return findViewByAccessibilityIdTraversal(accessibilityId); 17204 } 17205 17206 /** 17207 * Performs the traversal to find a view by its unuque and stable accessibility id. 17208 * 17209 * <strong>Note:</strong>This method does not stop at the root namespace 17210 * boundary since the user can touch the screen at an arbitrary location 17211 * potentially crossing the root namespace bounday which will send an 17212 * accessibility event to accessibility services and they should be able 17213 * to obtain the event source. Also accessibility ids are guaranteed to be 17214 * unique in the window. 17215 * 17216 * @param accessibilityId The accessibility id. 17217 * @return The found view. 17218 * 17219 * @hide 17220 */ 17221 public View findViewByAccessibilityIdTraversal(int accessibilityId) { 17222 if (getAccessibilityViewId() == accessibilityId) { 17223 return this; 17224 } 17225 return null; 17226 } 17227 17228 /** 17229 * Look for a child view with the given tag. If this view has the given 17230 * tag, return this view. 17231 * 17232 * @param tag The tag to search for, using "tag.equals(getTag())". 17233 * @return The View that has the given tag in the hierarchy or null 17234 */ 17235 public final View findViewWithTag(Object tag) { 17236 if (tag == null) { 17237 return null; 17238 } 17239 return findViewWithTagTraversal(tag); 17240 } 17241 17242 /** 17243 * {@hide} 17244 * Look for a child view that matches the specified predicate. 17245 * If this view matches the predicate, return this view. 17246 * 17247 * @param predicate The predicate to evaluate. 17248 * @return The first view that matches the predicate or null. 17249 */ 17250 public final View findViewByPredicate(Predicate<View> predicate) { 17251 return findViewByPredicateTraversal(predicate, null); 17252 } 17253 17254 /** 17255 * {@hide} 17256 * Look for a child view that matches the specified predicate, 17257 * starting with the specified view and its descendents and then 17258 * recusively searching the ancestors and siblings of that view 17259 * until this view is reached. 17260 * 17261 * This method is useful in cases where the predicate does not match 17262 * a single unique view (perhaps multiple views use the same id) 17263 * and we are trying to find the view that is "closest" in scope to the 17264 * starting view. 17265 * 17266 * @param start The view to start from. 17267 * @param predicate The predicate to evaluate. 17268 * @return The first view that matches the predicate or null. 17269 */ 17270 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 17271 View childToSkip = null; 17272 for (;;) { 17273 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 17274 if (view != null || start == this) { 17275 return view; 17276 } 17277 17278 ViewParent parent = start.getParent(); 17279 if (parent == null || !(parent instanceof View)) { 17280 return null; 17281 } 17282 17283 childToSkip = start; 17284 start = (View) parent; 17285 } 17286 } 17287 17288 /** 17289 * Sets the identifier for this view. The identifier does not have to be 17290 * unique in this view's hierarchy. The identifier should be a positive 17291 * number. 17292 * 17293 * @see #NO_ID 17294 * @see #getId() 17295 * @see #findViewById(int) 17296 * 17297 * @param id a number used to identify the view 17298 * 17299 * @attr ref android.R.styleable#View_id 17300 */ 17301 public void setId(int id) { 17302 mID = id; 17303 if (mID == View.NO_ID && mLabelForId != View.NO_ID) { 17304 mID = generateViewId(); 17305 } 17306 } 17307 17308 /** 17309 * {@hide} 17310 * 17311 * @param isRoot true if the view belongs to the root namespace, false 17312 * otherwise 17313 */ 17314 public void setIsRootNamespace(boolean isRoot) { 17315 if (isRoot) { 17316 mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE; 17317 } else { 17318 mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE; 17319 } 17320 } 17321 17322 /** 17323 * {@hide} 17324 * 17325 * @return true if the view belongs to the root namespace, false otherwise 17326 */ 17327 public boolean isRootNamespace() { 17328 return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0; 17329 } 17330 17331 /** 17332 * Returns this view's identifier. 17333 * 17334 * @return a positive integer used to identify the view or {@link #NO_ID} 17335 * if the view has no ID 17336 * 17337 * @see #setId(int) 17338 * @see #findViewById(int) 17339 * @attr ref android.R.styleable#View_id 17340 */ 17341 @ViewDebug.CapturedViewProperty 17342 public int getId() { 17343 return mID; 17344 } 17345 17346 /** 17347 * Returns this view's tag. 17348 * 17349 * @return the Object stored in this view as a tag, or {@code null} if not 17350 * set 17351 * 17352 * @see #setTag(Object) 17353 * @see #getTag(int) 17354 */ 17355 @ViewDebug.ExportedProperty 17356 public Object getTag() { 17357 return mTag; 17358 } 17359 17360 /** 17361 * Sets the tag associated with this view. A tag can be used to mark 17362 * a view in its hierarchy and does not have to be unique within the 17363 * hierarchy. Tags can also be used to store data within a view without 17364 * resorting to another data structure. 17365 * 17366 * @param tag an Object to tag the view with 17367 * 17368 * @see #getTag() 17369 * @see #setTag(int, Object) 17370 */ 17371 public void setTag(final Object tag) { 17372 mTag = tag; 17373 } 17374 17375 /** 17376 * Returns the tag associated with this view and the specified key. 17377 * 17378 * @param key The key identifying the tag 17379 * 17380 * @return the Object stored in this view as a tag, or {@code null} if not 17381 * set 17382 * 17383 * @see #setTag(int, Object) 17384 * @see #getTag() 17385 */ 17386 public Object getTag(int key) { 17387 if (mKeyedTags != null) return mKeyedTags.get(key); 17388 return null; 17389 } 17390 17391 /** 17392 * Sets a tag associated with this view and a key. A tag can be used 17393 * to mark a view in its hierarchy and does not have to be unique within 17394 * the hierarchy. Tags can also be used to store data within a view 17395 * without resorting to another data structure. 17396 * 17397 * The specified key should be an id declared in the resources of the 17398 * application to ensure it is unique (see the <a 17399 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 17400 * Keys identified as belonging to 17401 * the Android framework or not associated with any package will cause 17402 * an {@link IllegalArgumentException} to be thrown. 17403 * 17404 * @param key The key identifying the tag 17405 * @param tag An Object to tag the view with 17406 * 17407 * @throws IllegalArgumentException If they specified key is not valid 17408 * 17409 * @see #setTag(Object) 17410 * @see #getTag(int) 17411 */ 17412 public void setTag(int key, final Object tag) { 17413 // If the package id is 0x00 or 0x01, it's either an undefined package 17414 // or a framework id 17415 if ((key >>> 24) < 2) { 17416 throw new IllegalArgumentException("The key must be an application-specific " 17417 + "resource id."); 17418 } 17419 17420 setKeyedTag(key, tag); 17421 } 17422 17423 /** 17424 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 17425 * framework id. 17426 * 17427 * @hide 17428 */ 17429 public void setTagInternal(int key, Object tag) { 17430 if ((key >>> 24) != 0x1) { 17431 throw new IllegalArgumentException("The key must be a framework-specific " 17432 + "resource id."); 17433 } 17434 17435 setKeyedTag(key, tag); 17436 } 17437 17438 private void setKeyedTag(int key, Object tag) { 17439 if (mKeyedTags == null) { 17440 mKeyedTags = new SparseArray<Object>(2); 17441 } 17442 17443 mKeyedTags.put(key, tag); 17444 } 17445 17446 /** 17447 * Prints information about this view in the log output, with the tag 17448 * {@link #VIEW_LOG_TAG}. 17449 * 17450 * @hide 17451 */ 17452 public void debug() { 17453 debug(0); 17454 } 17455 17456 /** 17457 * Prints information about this view in the log output, with the tag 17458 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 17459 * indentation defined by the <code>depth</code>. 17460 * 17461 * @param depth the indentation level 17462 * 17463 * @hide 17464 */ 17465 protected void debug(int depth) { 17466 String output = debugIndent(depth - 1); 17467 17468 output += "+ " + this; 17469 int id = getId(); 17470 if (id != -1) { 17471 output += " (id=" + id + ")"; 17472 } 17473 Object tag = getTag(); 17474 if (tag != null) { 17475 output += " (tag=" + tag + ")"; 17476 } 17477 Log.d(VIEW_LOG_TAG, output); 17478 17479 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 17480 output = debugIndent(depth) + " FOCUSED"; 17481 Log.d(VIEW_LOG_TAG, output); 17482 } 17483 17484 output = debugIndent(depth); 17485 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 17486 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 17487 + "} "; 17488 Log.d(VIEW_LOG_TAG, output); 17489 17490 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 17491 || mPaddingBottom != 0) { 17492 output = debugIndent(depth); 17493 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 17494 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 17495 Log.d(VIEW_LOG_TAG, output); 17496 } 17497 17498 output = debugIndent(depth); 17499 output += "mMeasureWidth=" + mMeasuredWidth + 17500 " mMeasureHeight=" + mMeasuredHeight; 17501 Log.d(VIEW_LOG_TAG, output); 17502 17503 output = debugIndent(depth); 17504 if (mLayoutParams == null) { 17505 output += "BAD! no layout params"; 17506 } else { 17507 output = mLayoutParams.debug(output); 17508 } 17509 Log.d(VIEW_LOG_TAG, output); 17510 17511 output = debugIndent(depth); 17512 output += "flags={"; 17513 output += View.printFlags(mViewFlags); 17514 output += "}"; 17515 Log.d(VIEW_LOG_TAG, output); 17516 17517 output = debugIndent(depth); 17518 output += "privateFlags={"; 17519 output += View.printPrivateFlags(mPrivateFlags); 17520 output += "}"; 17521 Log.d(VIEW_LOG_TAG, output); 17522 } 17523 17524 /** 17525 * Creates a string of whitespaces used for indentation. 17526 * 17527 * @param depth the indentation level 17528 * @return a String containing (depth * 2 + 3) * 2 white spaces 17529 * 17530 * @hide 17531 */ 17532 protected static String debugIndent(int depth) { 17533 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 17534 for (int i = 0; i < (depth * 2) + 3; i++) { 17535 spaces.append(' ').append(' '); 17536 } 17537 return spaces.toString(); 17538 } 17539 17540 /** 17541 * <p>Return the offset of the widget's text baseline from the widget's top 17542 * boundary. If this widget does not support baseline alignment, this 17543 * method returns -1. </p> 17544 * 17545 * @return the offset of the baseline within the widget's bounds or -1 17546 * if baseline alignment is not supported 17547 */ 17548 @ViewDebug.ExportedProperty(category = "layout") 17549 public int getBaseline() { 17550 return -1; 17551 } 17552 17553 /** 17554 * Returns whether the view hierarchy is currently undergoing a layout pass. This 17555 * information is useful to avoid situations such as calling {@link #requestLayout()} during 17556 * a layout pass. 17557 * 17558 * @return whether the view hierarchy is currently undergoing a layout pass 17559 */ 17560 public boolean isInLayout() { 17561 ViewRootImpl viewRoot = getViewRootImpl(); 17562 return (viewRoot != null && viewRoot.isInLayout()); 17563 } 17564 17565 /** 17566 * Call this when something has changed which has invalidated the 17567 * layout of this view. This will schedule a layout pass of the view 17568 * tree. This should not be called while the view hierarchy is currently in a layout 17569 * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the 17570 * end of the current layout pass (and then layout will run again) or after the current 17571 * frame is drawn and the next layout occurs. 17572 * 17573 * <p>Subclasses which override this method should call the superclass method to 17574 * handle possible request-during-layout errors correctly.</p> 17575 */ 17576 public void requestLayout() { 17577 if (mMeasureCache != null) mMeasureCache.clear(); 17578 17579 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) { 17580 // Only trigger request-during-layout logic if this is the view requesting it, 17581 // not the views in its parent hierarchy 17582 ViewRootImpl viewRoot = getViewRootImpl(); 17583 if (viewRoot != null && viewRoot.isInLayout()) { 17584 if (!viewRoot.requestLayoutDuringLayout(this)) { 17585 return; 17586 } 17587 } 17588 mAttachInfo.mViewRequestingLayout = this; 17589 } 17590 17591 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 17592 mPrivateFlags |= PFLAG_INVALIDATED; 17593 17594 if (mParent != null && !mParent.isLayoutRequested()) { 17595 mParent.requestLayout(); 17596 } 17597 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) { 17598 mAttachInfo.mViewRequestingLayout = null; 17599 } 17600 } 17601 17602 /** 17603 * Forces this view to be laid out during the next layout pass. 17604 * This method does not call requestLayout() or forceLayout() 17605 * on the parent. 17606 */ 17607 public void forceLayout() { 17608 if (mMeasureCache != null) mMeasureCache.clear(); 17609 17610 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 17611 mPrivateFlags |= PFLAG_INVALIDATED; 17612 } 17613 17614 /** 17615 * <p> 17616 * This is called to find out how big a view should be. The parent 17617 * supplies constraint information in the width and height parameters. 17618 * </p> 17619 * 17620 * <p> 17621 * The actual measurement work of a view is performed in 17622 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 17623 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 17624 * </p> 17625 * 17626 * 17627 * @param widthMeasureSpec Horizontal space requirements as imposed by the 17628 * parent 17629 * @param heightMeasureSpec Vertical space requirements as imposed by the 17630 * parent 17631 * 17632 * @see #onMeasure(int, int) 17633 */ 17634 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 17635 boolean optical = isLayoutModeOptical(this); 17636 if (optical != isLayoutModeOptical(mParent)) { 17637 Insets insets = getOpticalInsets(); 17638 int oWidth = insets.left + insets.right; 17639 int oHeight = insets.top + insets.bottom; 17640 widthMeasureSpec = MeasureSpec.adjust(widthMeasureSpec, optical ? -oWidth : oWidth); 17641 heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight); 17642 } 17643 17644 // Suppress sign extension for the low bytes 17645 long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL; 17646 if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2); 17647 17648 final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 17649 final boolean isExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY && 17650 MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY; 17651 final boolean matchingSize = isExactly && 17652 getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec) && 17653 getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec); 17654 if (forceLayout || !matchingSize && 17655 (widthMeasureSpec != mOldWidthMeasureSpec || 17656 heightMeasureSpec != mOldHeightMeasureSpec)) { 17657 17658 // first clears the measured dimension flag 17659 mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET; 17660 17661 resolveRtlPropertiesIfNeeded(); 17662 17663 int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key); 17664 if (cacheIndex < 0 || sIgnoreMeasureCache) { 17665 // measure ourselves, this should set the measured dimension flag back 17666 onMeasure(widthMeasureSpec, heightMeasureSpec); 17667 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 17668 } else { 17669 long value = mMeasureCache.valueAt(cacheIndex); 17670 // Casting a long to int drops the high 32 bits, no mask needed 17671 setMeasuredDimensionRaw((int) (value >> 32), (int) value); 17672 mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 17673 } 17674 17675 // flag not set, setMeasuredDimension() was not invoked, we raise 17676 // an exception to warn the developer 17677 if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) { 17678 throw new IllegalStateException("onMeasure() did not set the" 17679 + " measured dimension by calling" 17680 + " setMeasuredDimension()"); 17681 } 17682 17683 mPrivateFlags |= PFLAG_LAYOUT_REQUIRED; 17684 } 17685 17686 mOldWidthMeasureSpec = widthMeasureSpec; 17687 mOldHeightMeasureSpec = heightMeasureSpec; 17688 17689 mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 | 17690 (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension 17691 } 17692 17693 /** 17694 * <p> 17695 * Measure the view and its content to determine the measured width and the 17696 * measured height. This method is invoked by {@link #measure(int, int)} and 17697 * should be overriden by subclasses to provide accurate and efficient 17698 * measurement of their contents. 17699 * </p> 17700 * 17701 * <p> 17702 * <strong>CONTRACT:</strong> When overriding this method, you 17703 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 17704 * measured width and height of this view. Failure to do so will trigger an 17705 * <code>IllegalStateException</code>, thrown by 17706 * {@link #measure(int, int)}. Calling the superclass' 17707 * {@link #onMeasure(int, int)} is a valid use. 17708 * </p> 17709 * 17710 * <p> 17711 * The base class implementation of measure defaults to the background size, 17712 * unless a larger size is allowed by the MeasureSpec. Subclasses should 17713 * override {@link #onMeasure(int, int)} to provide better measurements of 17714 * their content. 17715 * </p> 17716 * 17717 * <p> 17718 * If this method is overridden, it is the subclass's responsibility to make 17719 * sure the measured height and width are at least the view's minimum height 17720 * and width ({@link #getSuggestedMinimumHeight()} and 17721 * {@link #getSuggestedMinimumWidth()}). 17722 * </p> 17723 * 17724 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 17725 * The requirements are encoded with 17726 * {@link android.view.View.MeasureSpec}. 17727 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 17728 * The requirements are encoded with 17729 * {@link android.view.View.MeasureSpec}. 17730 * 17731 * @see #getMeasuredWidth() 17732 * @see #getMeasuredHeight() 17733 * @see #setMeasuredDimension(int, int) 17734 * @see #getSuggestedMinimumHeight() 17735 * @see #getSuggestedMinimumWidth() 17736 * @see android.view.View.MeasureSpec#getMode(int) 17737 * @see android.view.View.MeasureSpec#getSize(int) 17738 */ 17739 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 17740 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 17741 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 17742 } 17743 17744 /** 17745 * <p>This method must be called by {@link #onMeasure(int, int)} to store the 17746 * measured width and measured height. Failing to do so will trigger an 17747 * exception at measurement time.</p> 17748 * 17749 * @param measuredWidth The measured width of this view. May be a complex 17750 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17751 * {@link #MEASURED_STATE_TOO_SMALL}. 17752 * @param measuredHeight The measured height of this view. May be a complex 17753 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17754 * {@link #MEASURED_STATE_TOO_SMALL}. 17755 */ 17756 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 17757 boolean optical = isLayoutModeOptical(this); 17758 if (optical != isLayoutModeOptical(mParent)) { 17759 Insets insets = getOpticalInsets(); 17760 int opticalWidth = insets.left + insets.right; 17761 int opticalHeight = insets.top + insets.bottom; 17762 17763 measuredWidth += optical ? opticalWidth : -opticalWidth; 17764 measuredHeight += optical ? opticalHeight : -opticalHeight; 17765 } 17766 setMeasuredDimensionRaw(measuredWidth, measuredHeight); 17767 } 17768 17769 /** 17770 * Sets the measured dimension without extra processing for things like optical bounds. 17771 * Useful for reapplying consistent values that have already been cooked with adjustments 17772 * for optical bounds, etc. such as those from the measurement cache. 17773 * 17774 * @param measuredWidth The measured width of this view. May be a complex 17775 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17776 * {@link #MEASURED_STATE_TOO_SMALL}. 17777 * @param measuredHeight The measured height of this view. May be a complex 17778 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17779 * {@link #MEASURED_STATE_TOO_SMALL}. 17780 */ 17781 private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) { 17782 mMeasuredWidth = measuredWidth; 17783 mMeasuredHeight = measuredHeight; 17784 17785 mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET; 17786 } 17787 17788 /** 17789 * Merge two states as returned by {@link #getMeasuredState()}. 17790 * @param curState The current state as returned from a view or the result 17791 * of combining multiple views. 17792 * @param newState The new view state to combine. 17793 * @return Returns a new integer reflecting the combination of the two 17794 * states. 17795 */ 17796 public static int combineMeasuredStates(int curState, int newState) { 17797 return curState | newState; 17798 } 17799 17800 /** 17801 * Version of {@link #resolveSizeAndState(int, int, int)} 17802 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 17803 */ 17804 public static int resolveSize(int size, int measureSpec) { 17805 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 17806 } 17807 17808 /** 17809 * Utility to reconcile a desired size and state, with constraints imposed 17810 * by a MeasureSpec. Will take the desired size, unless a different size 17811 * is imposed by the constraints. The returned value is a compound integer, 17812 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 17813 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting 17814 * size is smaller than the size the view wants to be. 17815 * 17816 * @param size How big the view wants to be 17817 * @param measureSpec Constraints imposed by the parent 17818 * @return Size information bit mask as defined by 17819 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 17820 */ 17821 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 17822 int result = size; 17823 int specMode = MeasureSpec.getMode(measureSpec); 17824 int specSize = MeasureSpec.getSize(measureSpec); 17825 switch (specMode) { 17826 case MeasureSpec.UNSPECIFIED: 17827 result = size; 17828 break; 17829 case MeasureSpec.AT_MOST: 17830 if (specSize < size) { 17831 result = specSize | MEASURED_STATE_TOO_SMALL; 17832 } else { 17833 result = size; 17834 } 17835 break; 17836 case MeasureSpec.EXACTLY: 17837 result = specSize; 17838 break; 17839 } 17840 return result | (childMeasuredState&MEASURED_STATE_MASK); 17841 } 17842 17843 /** 17844 * Utility to return a default size. Uses the supplied size if the 17845 * MeasureSpec imposed no constraints. Will get larger if allowed 17846 * by the MeasureSpec. 17847 * 17848 * @param size Default size for this view 17849 * @param measureSpec Constraints imposed by the parent 17850 * @return The size this view should be. 17851 */ 17852 public static int getDefaultSize(int size, int measureSpec) { 17853 int result = size; 17854 int specMode = MeasureSpec.getMode(measureSpec); 17855 int specSize = MeasureSpec.getSize(measureSpec); 17856 17857 switch (specMode) { 17858 case MeasureSpec.UNSPECIFIED: 17859 result = size; 17860 break; 17861 case MeasureSpec.AT_MOST: 17862 case MeasureSpec.EXACTLY: 17863 result = specSize; 17864 break; 17865 } 17866 return result; 17867 } 17868 17869 /** 17870 * Returns the suggested minimum height that the view should use. This 17871 * returns the maximum of the view's minimum height 17872 * and the background's minimum height 17873 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 17874 * <p> 17875 * When being used in {@link #onMeasure(int, int)}, the caller should still 17876 * ensure the returned height is within the requirements of the parent. 17877 * 17878 * @return The suggested minimum height of the view. 17879 */ 17880 protected int getSuggestedMinimumHeight() { 17881 return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight()); 17882 17883 } 17884 17885 /** 17886 * Returns the suggested minimum width that the view should use. This 17887 * returns the maximum of the view's minimum width) 17888 * and the background's minimum width 17889 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 17890 * <p> 17891 * When being used in {@link #onMeasure(int, int)}, the caller should still 17892 * ensure the returned width is within the requirements of the parent. 17893 * 17894 * @return The suggested minimum width of the view. 17895 */ 17896 protected int getSuggestedMinimumWidth() { 17897 return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); 17898 } 17899 17900 /** 17901 * Returns the minimum height of the view. 17902 * 17903 * @return the minimum height the view will try to be. 17904 * 17905 * @see #setMinimumHeight(int) 17906 * 17907 * @attr ref android.R.styleable#View_minHeight 17908 */ 17909 public int getMinimumHeight() { 17910 return mMinHeight; 17911 } 17912 17913 /** 17914 * Sets the minimum height of the view. It is not guaranteed the view will 17915 * be able to achieve this minimum height (for example, if its parent layout 17916 * constrains it with less available height). 17917 * 17918 * @param minHeight The minimum height the view will try to be. 17919 * 17920 * @see #getMinimumHeight() 17921 * 17922 * @attr ref android.R.styleable#View_minHeight 17923 */ 17924 public void setMinimumHeight(int minHeight) { 17925 mMinHeight = minHeight; 17926 requestLayout(); 17927 } 17928 17929 /** 17930 * Returns the minimum width of the view. 17931 * 17932 * @return the minimum width the view will try to be. 17933 * 17934 * @see #setMinimumWidth(int) 17935 * 17936 * @attr ref android.R.styleable#View_minWidth 17937 */ 17938 public int getMinimumWidth() { 17939 return mMinWidth; 17940 } 17941 17942 /** 17943 * Sets the minimum width of the view. It is not guaranteed the view will 17944 * be able to achieve this minimum width (for example, if its parent layout 17945 * constrains it with less available width). 17946 * 17947 * @param minWidth The minimum width the view will try to be. 17948 * 17949 * @see #getMinimumWidth() 17950 * 17951 * @attr ref android.R.styleable#View_minWidth 17952 */ 17953 public void setMinimumWidth(int minWidth) { 17954 mMinWidth = minWidth; 17955 requestLayout(); 17956 17957 } 17958 17959 /** 17960 * Get the animation currently associated with this view. 17961 * 17962 * @return The animation that is currently playing or 17963 * scheduled to play for this view. 17964 */ 17965 public Animation getAnimation() { 17966 return mCurrentAnimation; 17967 } 17968 17969 /** 17970 * Start the specified animation now. 17971 * 17972 * @param animation the animation to start now 17973 */ 17974 public void startAnimation(Animation animation) { 17975 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 17976 setAnimation(animation); 17977 invalidateParentCaches(); 17978 invalidate(true); 17979 } 17980 17981 /** 17982 * Cancels any animations for this view. 17983 */ 17984 public void clearAnimation() { 17985 if (mCurrentAnimation != null) { 17986 mCurrentAnimation.detach(); 17987 } 17988 mCurrentAnimation = null; 17989 invalidateParentIfNeeded(); 17990 } 17991 17992 /** 17993 * Sets the next animation to play for this view. 17994 * If you want the animation to play immediately, use 17995 * {@link #startAnimation(android.view.animation.Animation)} instead. 17996 * This method provides allows fine-grained 17997 * control over the start time and invalidation, but you 17998 * must make sure that 1) the animation has a start time set, and 17999 * 2) the view's parent (which controls animations on its children) 18000 * will be invalidated when the animation is supposed to 18001 * start. 18002 * 18003 * @param animation The next animation, or null. 18004 */ 18005 public void setAnimation(Animation animation) { 18006 mCurrentAnimation = animation; 18007 18008 if (animation != null) { 18009 // If the screen is off assume the animation start time is now instead of 18010 // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time 18011 // would cause the animation to start when the screen turns back on 18012 if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF 18013 && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) { 18014 animation.setStartTime(AnimationUtils.currentAnimationTimeMillis()); 18015 } 18016 animation.reset(); 18017 } 18018 } 18019 18020 /** 18021 * Invoked by a parent ViewGroup to notify the start of the animation 18022 * currently associated with this view. If you override this method, 18023 * always call super.onAnimationStart(); 18024 * 18025 * @see #setAnimation(android.view.animation.Animation) 18026 * @see #getAnimation() 18027 */ 18028 protected void onAnimationStart() { 18029 mPrivateFlags |= PFLAG_ANIMATION_STARTED; 18030 } 18031 18032 /** 18033 * Invoked by a parent ViewGroup to notify the end of the animation 18034 * currently associated with this view. If you override this method, 18035 * always call super.onAnimationEnd(); 18036 * 18037 * @see #setAnimation(android.view.animation.Animation) 18038 * @see #getAnimation() 18039 */ 18040 protected void onAnimationEnd() { 18041 mPrivateFlags &= ~PFLAG_ANIMATION_STARTED; 18042 } 18043 18044 /** 18045 * Invoked if there is a Transform that involves alpha. Subclass that can 18046 * draw themselves with the specified alpha should return true, and then 18047 * respect that alpha when their onDraw() is called. If this returns false 18048 * then the view may be redirected to draw into an offscreen buffer to 18049 * fulfill the request, which will look fine, but may be slower than if the 18050 * subclass handles it internally. The default implementation returns false. 18051 * 18052 * @param alpha The alpha (0..255) to apply to the view's drawing 18053 * @return true if the view can draw with the specified alpha. 18054 */ 18055 protected boolean onSetAlpha(int alpha) { 18056 return false; 18057 } 18058 18059 /** 18060 * This is used by the RootView to perform an optimization when 18061 * the view hierarchy contains one or several SurfaceView. 18062 * SurfaceView is always considered transparent, but its children are not, 18063 * therefore all View objects remove themselves from the global transparent 18064 * region (passed as a parameter to this function). 18065 * 18066 * @param region The transparent region for this ViewAncestor (window). 18067 * 18068 * @return Returns true if the effective visibility of the view at this 18069 * point is opaque, regardless of the transparent region; returns false 18070 * if it is possible for underlying windows to be seen behind the view. 18071 * 18072 * {@hide} 18073 */ 18074 public boolean gatherTransparentRegion(Region region) { 18075 final AttachInfo attachInfo = mAttachInfo; 18076 if (region != null && attachInfo != null) { 18077 final int pflags = mPrivateFlags; 18078 if ((pflags & PFLAG_SKIP_DRAW) == 0) { 18079 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 18080 // remove it from the transparent region. 18081 final int[] location = attachInfo.mTransparentLocation; 18082 getLocationInWindow(location); 18083 region.op(location[0], location[1], location[0] + mRight - mLeft, 18084 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 18085 } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null && 18086 mBackground.getOpacity() != PixelFormat.TRANSPARENT) { 18087 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 18088 // exists, so we remove the background drawable's non-transparent 18089 // parts from this transparent region. 18090 applyDrawableToTransparentRegion(mBackground, region); 18091 } 18092 } 18093 return true; 18094 } 18095 18096 /** 18097 * Play a sound effect for this view. 18098 * 18099 * <p>The framework will play sound effects for some built in actions, such as 18100 * clicking, but you may wish to play these effects in your widget, 18101 * for instance, for internal navigation. 18102 * 18103 * <p>The sound effect will only be played if sound effects are enabled by the user, and 18104 * {@link #isSoundEffectsEnabled()} is true. 18105 * 18106 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 18107 */ 18108 public void playSoundEffect(int soundConstant) { 18109 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 18110 return; 18111 } 18112 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 18113 } 18114 18115 /** 18116 * BZZZTT!!1! 18117 * 18118 * <p>Provide haptic feedback to the user for this view. 18119 * 18120 * <p>The framework will provide haptic feedback for some built in actions, 18121 * such as long presses, but you may wish to provide feedback for your 18122 * own widget. 18123 * 18124 * <p>The feedback will only be performed if 18125 * {@link #isHapticFeedbackEnabled()} is true. 18126 * 18127 * @param feedbackConstant One of the constants defined in 18128 * {@link HapticFeedbackConstants} 18129 */ 18130 public boolean performHapticFeedback(int feedbackConstant) { 18131 return performHapticFeedback(feedbackConstant, 0); 18132 } 18133 18134 /** 18135 * BZZZTT!!1! 18136 * 18137 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 18138 * 18139 * @param feedbackConstant One of the constants defined in 18140 * {@link HapticFeedbackConstants} 18141 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 18142 */ 18143 public boolean performHapticFeedback(int feedbackConstant, int flags) { 18144 if (mAttachInfo == null) { 18145 return false; 18146 } 18147 //noinspection SimplifiableIfStatement 18148 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 18149 && !isHapticFeedbackEnabled()) { 18150 return false; 18151 } 18152 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 18153 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 18154 } 18155 18156 /** 18157 * Request that the visibility of the status bar or other screen/window 18158 * decorations be changed. 18159 * 18160 * <p>This method is used to put the over device UI into temporary modes 18161 * where the user's attention is focused more on the application content, 18162 * by dimming or hiding surrounding system affordances. This is typically 18163 * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY 18164 * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content 18165 * to be placed behind the action bar (and with these flags other system 18166 * affordances) so that smooth transitions between hiding and showing them 18167 * can be done. 18168 * 18169 * <p>Two representative examples of the use of system UI visibility is 18170 * implementing a content browsing application (like a magazine reader) 18171 * and a video playing application. 18172 * 18173 * <p>The first code shows a typical implementation of a View in a content 18174 * browsing application. In this implementation, the application goes 18175 * into a content-oriented mode by hiding the status bar and action bar, 18176 * and putting the navigation elements into lights out mode. The user can 18177 * then interact with content while in this mode. Such an application should 18178 * provide an easy way for the user to toggle out of the mode (such as to 18179 * check information in the status bar or access notifications). In the 18180 * implementation here, this is done simply by tapping on the content. 18181 * 18182 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java 18183 * content} 18184 * 18185 * <p>This second code sample shows a typical implementation of a View 18186 * in a video playing application. In this situation, while the video is 18187 * playing the application would like to go into a complete full-screen mode, 18188 * to use as much of the display as possible for the video. When in this state 18189 * the user can not interact with the application; the system intercepts 18190 * touching on the screen to pop the UI out of full screen mode. See 18191 * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code. 18192 * 18193 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java 18194 * content} 18195 * 18196 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 18197 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 18198 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 18199 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 18200 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 18201 */ 18202 public void setSystemUiVisibility(int visibility) { 18203 if (visibility != mSystemUiVisibility) { 18204 mSystemUiVisibility = visibility; 18205 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 18206 mParent.recomputeViewAttributes(this); 18207 } 18208 } 18209 } 18210 18211 /** 18212 * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested. 18213 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 18214 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 18215 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 18216 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 18217 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 18218 */ 18219 public int getSystemUiVisibility() { 18220 return mSystemUiVisibility; 18221 } 18222 18223 /** 18224 * Returns the current system UI visibility that is currently set for 18225 * the entire window. This is the combination of the 18226 * {@link #setSystemUiVisibility(int)} values supplied by all of the 18227 * views in the window. 18228 */ 18229 public int getWindowSystemUiVisibility() { 18230 return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0; 18231 } 18232 18233 /** 18234 * Override to find out when the window's requested system UI visibility 18235 * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}. 18236 * This is different from the callbacks received through 18237 * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)} 18238 * in that this is only telling you about the local request of the window, 18239 * not the actual values applied by the system. 18240 */ 18241 public void onWindowSystemUiVisibilityChanged(int visible) { 18242 } 18243 18244 /** 18245 * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down 18246 * the view hierarchy. 18247 */ 18248 public void dispatchWindowSystemUiVisiblityChanged(int visible) { 18249 onWindowSystemUiVisibilityChanged(visible); 18250 } 18251 18252 /** 18253 * Set a listener to receive callbacks when the visibility of the system bar changes. 18254 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 18255 */ 18256 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 18257 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 18258 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 18259 mParent.recomputeViewAttributes(this); 18260 } 18261 } 18262 18263 /** 18264 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 18265 * the view hierarchy. 18266 */ 18267 public void dispatchSystemUiVisibilityChanged(int visibility) { 18268 ListenerInfo li = mListenerInfo; 18269 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 18270 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 18271 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 18272 } 18273 } 18274 18275 boolean updateLocalSystemUiVisibility(int localValue, int localChanges) { 18276 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 18277 if (val != mSystemUiVisibility) { 18278 setSystemUiVisibility(val); 18279 return true; 18280 } 18281 return false; 18282 } 18283 18284 /** @hide */ 18285 public void setDisabledSystemUiVisibility(int flags) { 18286 if (mAttachInfo != null) { 18287 if (mAttachInfo.mDisabledSystemUiVisibility != flags) { 18288 mAttachInfo.mDisabledSystemUiVisibility = flags; 18289 if (mParent != null) { 18290 mParent.recomputeViewAttributes(this); 18291 } 18292 } 18293 } 18294 } 18295 18296 /** 18297 * Creates an image that the system displays during the drag and drop 18298 * operation. This is called a "drag shadow". The default implementation 18299 * for a DragShadowBuilder based on a View returns an image that has exactly the same 18300 * appearance as the given View. The default also positions the center of the drag shadow 18301 * directly under the touch point. If no View is provided (the constructor with no parameters 18302 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 18303 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the 18304 * default is an invisible drag shadow. 18305 * <p> 18306 * You are not required to use the View you provide to the constructor as the basis of the 18307 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 18308 * anything you want as the drag shadow. 18309 * </p> 18310 * <p> 18311 * You pass a DragShadowBuilder object to the system when you start the drag. The system 18312 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 18313 * size and position of the drag shadow. It uses this data to construct a 18314 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 18315 * so that your application can draw the shadow image in the Canvas. 18316 * </p> 18317 * 18318 * <div class="special reference"> 18319 * <h3>Developer Guides</h3> 18320 * <p>For a guide to implementing drag and drop features, read the 18321 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 18322 * </div> 18323 */ 18324 public static class DragShadowBuilder { 18325 private final WeakReference<View> mView; 18326 18327 /** 18328 * Constructs a shadow image builder based on a View. By default, the resulting drag 18329 * shadow will have the same appearance and dimensions as the View, with the touch point 18330 * over the center of the View. 18331 * @param view A View. Any View in scope can be used. 18332 */ 18333 public DragShadowBuilder(View view) { 18334 mView = new WeakReference<View>(view); 18335 } 18336 18337 /** 18338 * Construct a shadow builder object with no associated View. This 18339 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 18340 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 18341 * to supply the drag shadow's dimensions and appearance without 18342 * reference to any View object. If they are not overridden, then the result is an 18343 * invisible drag shadow. 18344 */ 18345 public DragShadowBuilder() { 18346 mView = new WeakReference<View>(null); 18347 } 18348 18349 /** 18350 * Returns the View object that had been passed to the 18351 * {@link #View.DragShadowBuilder(View)} 18352 * constructor. If that View parameter was {@code null} or if the 18353 * {@link #View.DragShadowBuilder()} 18354 * constructor was used to instantiate the builder object, this method will return 18355 * null. 18356 * 18357 * @return The View object associate with this builder object. 18358 */ 18359 @SuppressWarnings({"JavadocReference"}) 18360 final public View getView() { 18361 return mView.get(); 18362 } 18363 18364 /** 18365 * Provides the metrics for the shadow image. These include the dimensions of 18366 * the shadow image, and the point within that shadow that should 18367 * be centered under the touch location while dragging. 18368 * <p> 18369 * The default implementation sets the dimensions of the shadow to be the 18370 * same as the dimensions of the View itself and centers the shadow under 18371 * the touch point. 18372 * </p> 18373 * 18374 * @param shadowSize A {@link android.graphics.Point} containing the width and height 18375 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 18376 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 18377 * image. 18378 * 18379 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 18380 * shadow image that should be underneath the touch point during the drag and drop 18381 * operation. Your application must set {@link android.graphics.Point#x} to the 18382 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 18383 */ 18384 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 18385 final View view = mView.get(); 18386 if (view != null) { 18387 shadowSize.set(view.getWidth(), view.getHeight()); 18388 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 18389 } else { 18390 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 18391 } 18392 } 18393 18394 /** 18395 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 18396 * based on the dimensions it received from the 18397 * {@link #onProvideShadowMetrics(Point, Point)} callback. 18398 * 18399 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 18400 */ 18401 public void onDrawShadow(Canvas canvas) { 18402 final View view = mView.get(); 18403 if (view != null) { 18404 view.draw(canvas); 18405 } else { 18406 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 18407 } 18408 } 18409 } 18410 18411 /** 18412 * Starts a drag and drop operation. When your application calls this method, it passes a 18413 * {@link android.view.View.DragShadowBuilder} object to the system. The 18414 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 18415 * to get metrics for the drag shadow, and then calls the object's 18416 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 18417 * <p> 18418 * Once the system has the drag shadow, it begins the drag and drop operation by sending 18419 * drag events to all the View objects in your application that are currently visible. It does 18420 * this either by calling the View object's drag listener (an implementation of 18421 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 18422 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 18423 * Both are passed a {@link android.view.DragEvent} object that has a 18424 * {@link android.view.DragEvent#getAction()} value of 18425 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 18426 * </p> 18427 * <p> 18428 * Your application can invoke startDrag() on any attached View object. The View object does not 18429 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to 18430 * be related to the View the user selected for dragging. 18431 * </p> 18432 * @param data A {@link android.content.ClipData} object pointing to the data to be 18433 * transferred by the drag and drop operation. 18434 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 18435 * drag shadow. 18436 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 18437 * drop operation. This Object is put into every DragEvent object sent by the system during the 18438 * current drag. 18439 * <p> 18440 * myLocalState is a lightweight mechanism for the sending information from the dragged View 18441 * to the target Views. For example, it can contain flags that differentiate between a 18442 * a copy operation and a move operation. 18443 * </p> 18444 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 18445 * so the parameter should be set to 0. 18446 * @return {@code true} if the method completes successfully, or 18447 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 18448 * do a drag, and so no drag operation is in progress. 18449 */ 18450 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 18451 Object myLocalState, int flags) { 18452 if (ViewDebug.DEBUG_DRAG) { 18453 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 18454 } 18455 boolean okay = false; 18456 18457 Point shadowSize = new Point(); 18458 Point shadowTouchPoint = new Point(); 18459 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 18460 18461 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 18462 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 18463 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 18464 } 18465 18466 if (ViewDebug.DEBUG_DRAG) { 18467 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 18468 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 18469 } 18470 Surface surface = new Surface(); 18471 try { 18472 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 18473 flags, shadowSize.x, shadowSize.y, surface); 18474 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 18475 + " surface=" + surface); 18476 if (token != null) { 18477 Canvas canvas = surface.lockCanvas(null); 18478 try { 18479 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 18480 shadowBuilder.onDrawShadow(canvas); 18481 } finally { 18482 surface.unlockCanvasAndPost(canvas); 18483 } 18484 18485 final ViewRootImpl root = getViewRootImpl(); 18486 18487 // Cache the local state object for delivery with DragEvents 18488 root.setLocalDragState(myLocalState); 18489 18490 // repurpose 'shadowSize' for the last touch point 18491 root.getLastTouchPoint(shadowSize); 18492 18493 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 18494 shadowSize.x, shadowSize.y, 18495 shadowTouchPoint.x, shadowTouchPoint.y, data); 18496 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 18497 18498 // Off and running! Release our local surface instance; the drag 18499 // shadow surface is now managed by the system process. 18500 surface.release(); 18501 } 18502 } catch (Exception e) { 18503 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 18504 surface.destroy(); 18505 } 18506 18507 return okay; 18508 } 18509 18510 /** 18511 * Handles drag events sent by the system following a call to 18512 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}. 18513 *<p> 18514 * When the system calls this method, it passes a 18515 * {@link android.view.DragEvent} object. A call to 18516 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 18517 * in DragEvent. The method uses these to determine what is happening in the drag and drop 18518 * operation. 18519 * @param event The {@link android.view.DragEvent} sent by the system. 18520 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 18521 * in DragEvent, indicating the type of drag event represented by this object. 18522 * @return {@code true} if the method was successful, otherwise {@code false}. 18523 * <p> 18524 * The method should return {@code true} in response to an action type of 18525 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 18526 * operation. 18527 * </p> 18528 * <p> 18529 * The method should also return {@code true} in response to an action type of 18530 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 18531 * {@code false} if it didn't. 18532 * </p> 18533 */ 18534 public boolean onDragEvent(DragEvent event) { 18535 return false; 18536 } 18537 18538 /** 18539 * Detects if this View is enabled and has a drag event listener. 18540 * If both are true, then it calls the drag event listener with the 18541 * {@link android.view.DragEvent} it received. If the drag event listener returns 18542 * {@code true}, then dispatchDragEvent() returns {@code true}. 18543 * <p> 18544 * For all other cases, the method calls the 18545 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 18546 * method and returns its result. 18547 * </p> 18548 * <p> 18549 * This ensures that a drag event is always consumed, even if the View does not have a drag 18550 * event listener. However, if the View has a listener and the listener returns true, then 18551 * onDragEvent() is not called. 18552 * </p> 18553 */ 18554 public boolean dispatchDragEvent(DragEvent event) { 18555 ListenerInfo li = mListenerInfo; 18556 //noinspection SimplifiableIfStatement 18557 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 18558 && li.mOnDragListener.onDrag(this, event)) { 18559 return true; 18560 } 18561 return onDragEvent(event); 18562 } 18563 18564 boolean canAcceptDrag() { 18565 return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0; 18566 } 18567 18568 /** 18569 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 18570 * it is ever exposed at all. 18571 * @hide 18572 */ 18573 public void onCloseSystemDialogs(String reason) { 18574 } 18575 18576 /** 18577 * Given a Drawable whose bounds have been set to draw into this view, 18578 * update a Region being computed for 18579 * {@link #gatherTransparentRegion(android.graphics.Region)} so 18580 * that any non-transparent parts of the Drawable are removed from the 18581 * given transparent region. 18582 * 18583 * @param dr The Drawable whose transparency is to be applied to the region. 18584 * @param region A Region holding the current transparency information, 18585 * where any parts of the region that are set are considered to be 18586 * transparent. On return, this region will be modified to have the 18587 * transparency information reduced by the corresponding parts of the 18588 * Drawable that are not transparent. 18589 * {@hide} 18590 */ 18591 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 18592 if (DBG) { 18593 Log.i("View", "Getting transparent region for: " + this); 18594 } 18595 final Region r = dr.getTransparentRegion(); 18596 final Rect db = dr.getBounds(); 18597 final AttachInfo attachInfo = mAttachInfo; 18598 if (r != null && attachInfo != null) { 18599 final int w = getRight()-getLeft(); 18600 final int h = getBottom()-getTop(); 18601 if (db.left > 0) { 18602 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 18603 r.op(0, 0, db.left, h, Region.Op.UNION); 18604 } 18605 if (db.right < w) { 18606 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 18607 r.op(db.right, 0, w, h, Region.Op.UNION); 18608 } 18609 if (db.top > 0) { 18610 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 18611 r.op(0, 0, w, db.top, Region.Op.UNION); 18612 } 18613 if (db.bottom < h) { 18614 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 18615 r.op(0, db.bottom, w, h, Region.Op.UNION); 18616 } 18617 final int[] location = attachInfo.mTransparentLocation; 18618 getLocationInWindow(location); 18619 r.translate(location[0], location[1]); 18620 region.op(r, Region.Op.INTERSECT); 18621 } else { 18622 region.op(db, Region.Op.DIFFERENCE); 18623 } 18624 } 18625 18626 private void checkForLongClick(int delayOffset) { 18627 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 18628 mHasPerformedLongPress = false; 18629 18630 if (mPendingCheckForLongPress == null) { 18631 mPendingCheckForLongPress = new CheckForLongPress(); 18632 } 18633 mPendingCheckForLongPress.rememberWindowAttachCount(); 18634 postDelayed(mPendingCheckForLongPress, 18635 ViewConfiguration.getLongPressTimeout() - delayOffset); 18636 } 18637 } 18638 18639 /** 18640 * Inflate a view from an XML resource. This convenience method wraps the {@link 18641 * LayoutInflater} class, which provides a full range of options for view inflation. 18642 * 18643 * @param context The Context object for your activity or application. 18644 * @param resource The resource ID to inflate 18645 * @param root A view group that will be the parent. Used to properly inflate the 18646 * layout_* parameters. 18647 * @see LayoutInflater 18648 */ 18649 public static View inflate(Context context, int resource, ViewGroup root) { 18650 LayoutInflater factory = LayoutInflater.from(context); 18651 return factory.inflate(resource, root); 18652 } 18653 18654 /** 18655 * Scroll the view with standard behavior for scrolling beyond the normal 18656 * content boundaries. Views that call this method should override 18657 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 18658 * results of an over-scroll operation. 18659 * 18660 * Views can use this method to handle any touch or fling-based scrolling. 18661 * 18662 * @param deltaX Change in X in pixels 18663 * @param deltaY Change in Y in pixels 18664 * @param scrollX Current X scroll value in pixels before applying deltaX 18665 * @param scrollY Current Y scroll value in pixels before applying deltaY 18666 * @param scrollRangeX Maximum content scroll range along the X axis 18667 * @param scrollRangeY Maximum content scroll range along the Y axis 18668 * @param maxOverScrollX Number of pixels to overscroll by in either direction 18669 * along the X axis. 18670 * @param maxOverScrollY Number of pixels to overscroll by in either direction 18671 * along the Y axis. 18672 * @param isTouchEvent true if this scroll operation is the result of a touch event. 18673 * @return true if scrolling was clamped to an over-scroll boundary along either 18674 * axis, false otherwise. 18675 */ 18676 @SuppressWarnings({"UnusedParameters"}) 18677 protected boolean overScrollBy(int deltaX, int deltaY, 18678 int scrollX, int scrollY, 18679 int scrollRangeX, int scrollRangeY, 18680 int maxOverScrollX, int maxOverScrollY, 18681 boolean isTouchEvent) { 18682 final int overScrollMode = mOverScrollMode; 18683 final boolean canScrollHorizontal = 18684 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 18685 final boolean canScrollVertical = 18686 computeVerticalScrollRange() > computeVerticalScrollExtent(); 18687 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 18688 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 18689 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 18690 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 18691 18692 int newScrollX = scrollX + deltaX; 18693 if (!overScrollHorizontal) { 18694 maxOverScrollX = 0; 18695 } 18696 18697 int newScrollY = scrollY + deltaY; 18698 if (!overScrollVertical) { 18699 maxOverScrollY = 0; 18700 } 18701 18702 // Clamp values if at the limits and record 18703 final int left = -maxOverScrollX; 18704 final int right = maxOverScrollX + scrollRangeX; 18705 final int top = -maxOverScrollY; 18706 final int bottom = maxOverScrollY + scrollRangeY; 18707 18708 boolean clampedX = false; 18709 if (newScrollX > right) { 18710 newScrollX = right; 18711 clampedX = true; 18712 } else if (newScrollX < left) { 18713 newScrollX = left; 18714 clampedX = true; 18715 } 18716 18717 boolean clampedY = false; 18718 if (newScrollY > bottom) { 18719 newScrollY = bottom; 18720 clampedY = true; 18721 } else if (newScrollY < top) { 18722 newScrollY = top; 18723 clampedY = true; 18724 } 18725 18726 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 18727 18728 return clampedX || clampedY; 18729 } 18730 18731 /** 18732 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 18733 * respond to the results of an over-scroll operation. 18734 * 18735 * @param scrollX New X scroll value in pixels 18736 * @param scrollY New Y scroll value in pixels 18737 * @param clampedX True if scrollX was clamped to an over-scroll boundary 18738 * @param clampedY True if scrollY was clamped to an over-scroll boundary 18739 */ 18740 protected void onOverScrolled(int scrollX, int scrollY, 18741 boolean clampedX, boolean clampedY) { 18742 // Intentionally empty. 18743 } 18744 18745 /** 18746 * Returns the over-scroll mode for this view. The result will be 18747 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 18748 * (allow over-scrolling only if the view content is larger than the container), 18749 * or {@link #OVER_SCROLL_NEVER}. 18750 * 18751 * @return This view's over-scroll mode. 18752 */ 18753 public int getOverScrollMode() { 18754 return mOverScrollMode; 18755 } 18756 18757 /** 18758 * Set the over-scroll mode for this view. Valid over-scroll modes are 18759 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 18760 * (allow over-scrolling only if the view content is larger than the container), 18761 * or {@link #OVER_SCROLL_NEVER}. 18762 * 18763 * Setting the over-scroll mode of a view will have an effect only if the 18764 * view is capable of scrolling. 18765 * 18766 * @param overScrollMode The new over-scroll mode for this view. 18767 */ 18768 public void setOverScrollMode(int overScrollMode) { 18769 if (overScrollMode != OVER_SCROLL_ALWAYS && 18770 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 18771 overScrollMode != OVER_SCROLL_NEVER) { 18772 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 18773 } 18774 mOverScrollMode = overScrollMode; 18775 } 18776 18777 /** 18778 * Enable or disable nested scrolling for this view. 18779 * 18780 * <p>If this property is set to true the view will be permitted to initiate nested 18781 * scrolling operations with a compatible parent view in the current hierarchy. If this 18782 * view does not implement nested scrolling this will have no effect. Disabling nested scrolling 18783 * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping} 18784 * the nested scroll.</p> 18785 * 18786 * @param enabled true to enable nested scrolling, false to disable 18787 * 18788 * @see #isNestedScrollingEnabled() 18789 */ 18790 public void setNestedScrollingEnabled(boolean enabled) { 18791 if (enabled) { 18792 mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED; 18793 } else { 18794 stopNestedScroll(); 18795 mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED; 18796 } 18797 } 18798 18799 /** 18800 * Returns true if nested scrolling is enabled for this view. 18801 * 18802 * <p>If nested scrolling is enabled and this View class implementation supports it, 18803 * this view will act as a nested scrolling child view when applicable, forwarding data 18804 * about the scroll operation in progress to a compatible and cooperating nested scrolling 18805 * parent.</p> 18806 * 18807 * @return true if nested scrolling is enabled 18808 * 18809 * @see #setNestedScrollingEnabled(boolean) 18810 */ 18811 public boolean isNestedScrollingEnabled() { 18812 return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) == 18813 PFLAG3_NESTED_SCROLLING_ENABLED; 18814 } 18815 18816 /** 18817 * Begin a nestable scroll operation along the given axes. 18818 * 18819 * <p>A view starting a nested scroll promises to abide by the following contract:</p> 18820 * 18821 * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case 18822 * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}. 18823 * In the case of touch scrolling the nested scroll will be terminated automatically in 18824 * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}. 18825 * In the event of programmatic scrolling the caller must explicitly call 18826 * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p> 18827 * 18828 * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found. 18829 * If it returns false the caller may ignore the rest of this contract until the next scroll. 18830 * Calling startNestedScroll while a nested scroll is already in progress will return true.</p> 18831 * 18832 * <p>At each incremental step of the scroll the caller should invoke 18833 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} 18834 * once it has calculated the requested scrolling delta. If it returns true the nested scrolling 18835 * parent at least partially consumed the scroll and the caller should adjust the amount it 18836 * scrolls by.</p> 18837 * 18838 * <p>After applying the remainder of the scroll delta the caller should invoke 18839 * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing 18840 * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat 18841 * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}. 18842 * </p> 18843 * 18844 * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or 18845 * {@link #SCROLL_AXIS_VERTICAL}. 18846 * @return true if a cooperative parent was found and nested scrolling has been enabled for 18847 * the current gesture. 18848 * 18849 * @see #stopNestedScroll() 18850 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 18851 * @see #dispatchNestedScroll(int, int, int, int, int[]) 18852 */ 18853 public boolean startNestedScroll(int axes) { 18854 if (hasNestedScrollingParent()) { 18855 // Already in progress 18856 return true; 18857 } 18858 if (isNestedScrollingEnabled()) { 18859 ViewParent p = getParent(); 18860 View child = this; 18861 while (p != null) { 18862 try { 18863 if (p.onStartNestedScroll(child, this, axes)) { 18864 mNestedScrollingParent = p; 18865 p.onNestedScrollAccepted(child, this, axes); 18866 return true; 18867 } 18868 } catch (AbstractMethodError e) { 18869 Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " + 18870 "method onStartNestedScroll", e); 18871 // Allow the search upward to continue 18872 } 18873 if (p instanceof View) { 18874 child = (View) p; 18875 } 18876 p = p.getParent(); 18877 } 18878 } 18879 return false; 18880 } 18881 18882 /** 18883 * Stop a nested scroll in progress. 18884 * 18885 * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p> 18886 * 18887 * @see #startNestedScroll(int) 18888 */ 18889 public void stopNestedScroll() { 18890 if (mNestedScrollingParent != null) { 18891 mNestedScrollingParent.onStopNestedScroll(this); 18892 mNestedScrollingParent = null; 18893 } 18894 } 18895 18896 /** 18897 * Returns true if this view has a nested scrolling parent. 18898 * 18899 * <p>The presence of a nested scrolling parent indicates that this view has initiated 18900 * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p> 18901 * 18902 * @return whether this view has a nested scrolling parent 18903 */ 18904 public boolean hasNestedScrollingParent() { 18905 return mNestedScrollingParent != null; 18906 } 18907 18908 /** 18909 * Dispatch one step of a nested scroll in progress. 18910 * 18911 * <p>Implementations of views that support nested scrolling should call this to report 18912 * info about a scroll in progress to the current nested scrolling parent. If a nested scroll 18913 * is not currently in progress or nested scrolling is not 18914 * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p> 18915 * 18916 * <p>Compatible View implementations should also call 18917 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before 18918 * consuming a component of the scroll event themselves.</p> 18919 * 18920 * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step 18921 * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step 18922 * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view 18923 * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view 18924 * @param offsetInWindow Optional. If not null, on return this will contain the offset 18925 * in local view coordinates of this view from before this operation 18926 * to after it completes. View implementations may use this to adjust 18927 * expected input coordinate tracking. 18928 * @return true if the event was dispatched, false if it could not be dispatched. 18929 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 18930 */ 18931 public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, 18932 int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow) { 18933 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18934 if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) { 18935 int startX = 0; 18936 int startY = 0; 18937 if (offsetInWindow != null) { 18938 getLocationInWindow(offsetInWindow); 18939 startX = offsetInWindow[0]; 18940 startY = offsetInWindow[1]; 18941 } 18942 18943 mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed, 18944 dxUnconsumed, dyUnconsumed); 18945 18946 if (offsetInWindow != null) { 18947 getLocationInWindow(offsetInWindow); 18948 offsetInWindow[0] -= startX; 18949 offsetInWindow[1] -= startY; 18950 } 18951 return true; 18952 } else if (offsetInWindow != null) { 18953 // No motion, no dispatch. Keep offsetInWindow up to date. 18954 offsetInWindow[0] = 0; 18955 offsetInWindow[1] = 0; 18956 } 18957 } 18958 return false; 18959 } 18960 18961 /** 18962 * Dispatch one step of a nested scroll in progress before this view consumes any portion of it. 18963 * 18964 * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch. 18965 * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested 18966 * scrolling operation to consume some or all of the scroll operation before the child view 18967 * consumes it.</p> 18968 * 18969 * @param dx Horizontal scroll distance in pixels 18970 * @param dy Vertical scroll distance in pixels 18971 * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx 18972 * and consumed[1] the consumed dy. 18973 * @param offsetInWindow Optional. If not null, on return this will contain the offset 18974 * in local view coordinates of this view from before this operation 18975 * to after it completes. View implementations may use this to adjust 18976 * expected input coordinate tracking. 18977 * @return true if the parent consumed some or all of the scroll delta 18978 * @see #dispatchNestedScroll(int, int, int, int, int[]) 18979 */ 18980 public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) { 18981 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18982 if (dx != 0 || dy != 0) { 18983 int startX = 0; 18984 int startY = 0; 18985 if (offsetInWindow != null) { 18986 getLocationInWindow(offsetInWindow); 18987 startX = offsetInWindow[0]; 18988 startY = offsetInWindow[1]; 18989 } 18990 18991 if (consumed == null) { 18992 if (mTempNestedScrollConsumed == null) { 18993 mTempNestedScrollConsumed = new int[2]; 18994 } 18995 consumed = mTempNestedScrollConsumed; 18996 } 18997 consumed[0] = 0; 18998 consumed[1] = 0; 18999 mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed); 19000 19001 if (offsetInWindow != null) { 19002 getLocationInWindow(offsetInWindow); 19003 offsetInWindow[0] -= startX; 19004 offsetInWindow[1] -= startY; 19005 } 19006 return consumed[0] != 0 || consumed[1] != 0; 19007 } else if (offsetInWindow != null) { 19008 offsetInWindow[0] = 0; 19009 offsetInWindow[1] = 0; 19010 } 19011 } 19012 return false; 19013 } 19014 19015 /** 19016 * Dispatch a fling to a nested scrolling parent. 19017 * 19018 * <p>This method should be used to indicate that a nested scrolling child has detected 19019 * suitable conditions for a fling. Generally this means that a touch scroll has ended with a 19020 * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds 19021 * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity} 19022 * along a scrollable axis.</p> 19023 * 19024 * <p>If a nested scrolling child view would normally fling but it is at the edge of 19025 * its own content, it can use this method to delegate the fling to its nested scrolling 19026 * parent instead. The parent may optionally consume the fling or observe a child fling.</p> 19027 * 19028 * @param velocityX Horizontal fling velocity in pixels per second 19029 * @param velocityY Vertical fling velocity in pixels per second 19030 * @param consumed true if the child consumed the fling, false otherwise 19031 * @return true if the nested scrolling parent consumed or otherwise reacted to the fling 19032 */ 19033 public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) { 19034 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 19035 return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed); 19036 } 19037 return false; 19038 } 19039 19040 /** 19041 * Dispatch a fling to a nested scrolling parent before it is processed by this view. 19042 * 19043 * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch 19044 * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code> 19045 * offsets an opportunity for the parent view in a nested fling to fully consume the fling 19046 * before the child view consumes it. If this method returns <code>true</code>, a nested 19047 * parent view consumed the fling and this view should not scroll as a result.</p> 19048 * 19049 * <p>For a better user experience, only one view in a nested scrolling chain should consume 19050 * the fling at a time. If a parent view consumed the fling this method will return false. 19051 * Custom view implementations should account for this in two ways:</p> 19052 * 19053 * <ul> 19054 * <li>If a custom view is paged and needs to settle to a fixed page-point, do not 19055 * call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid 19056 * position regardless.</li> 19057 * <li>If a nested parent does consume the fling, this view should not scroll at all, 19058 * even to settle back to a valid idle position.</li> 19059 * </ul> 19060 * 19061 * <p>Views should also not offer fling velocities to nested parent views along an axis 19062 * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView} 19063 * should not offer a horizontal fling velocity to its parents since scrolling along that 19064 * axis is not permitted and carrying velocity along that motion does not make sense.</p> 19065 * 19066 * @param velocityX Horizontal fling velocity in pixels per second 19067 * @param velocityY Vertical fling velocity in pixels per second 19068 * @return true if a nested scrolling parent consumed the fling 19069 */ 19070 public boolean dispatchNestedPreFling(float velocityX, float velocityY) { 19071 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 19072 return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY); 19073 } 19074 return false; 19075 } 19076 19077 /** 19078 * Gets a scale factor that determines the distance the view should scroll 19079 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 19080 * @return The vertical scroll scale factor. 19081 * @hide 19082 */ 19083 protected float getVerticalScrollFactor() { 19084 if (mVerticalScrollFactor == 0) { 19085 TypedValue outValue = new TypedValue(); 19086 if (!mContext.getTheme().resolveAttribute( 19087 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 19088 throw new IllegalStateException( 19089 "Expected theme to define listPreferredItemHeight."); 19090 } 19091 mVerticalScrollFactor = outValue.getDimension( 19092 mContext.getResources().getDisplayMetrics()); 19093 } 19094 return mVerticalScrollFactor; 19095 } 19096 19097 /** 19098 * Gets a scale factor that determines the distance the view should scroll 19099 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 19100 * @return The horizontal scroll scale factor. 19101 * @hide 19102 */ 19103 protected float getHorizontalScrollFactor() { 19104 // TODO: Should use something else. 19105 return getVerticalScrollFactor(); 19106 } 19107 19108 /** 19109 * Return the value specifying the text direction or policy that was set with 19110 * {@link #setTextDirection(int)}. 19111 * 19112 * @return the defined text direction. It can be one of: 19113 * 19114 * {@link #TEXT_DIRECTION_INHERIT}, 19115 * {@link #TEXT_DIRECTION_FIRST_STRONG} 19116 * {@link #TEXT_DIRECTION_ANY_RTL}, 19117 * {@link #TEXT_DIRECTION_LTR}, 19118 * {@link #TEXT_DIRECTION_RTL}, 19119 * {@link #TEXT_DIRECTION_LOCALE} 19120 * 19121 * @attr ref android.R.styleable#View_textDirection 19122 * 19123 * @hide 19124 */ 19125 @ViewDebug.ExportedProperty(category = "text", mapping = { 19126 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 19127 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 19128 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 19129 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 19130 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 19131 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 19132 }) 19133 public int getRawTextDirection() { 19134 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 19135 } 19136 19137 /** 19138 * Set the text direction. 19139 * 19140 * @param textDirection the direction to set. Should be one of: 19141 * 19142 * {@link #TEXT_DIRECTION_INHERIT}, 19143 * {@link #TEXT_DIRECTION_FIRST_STRONG} 19144 * {@link #TEXT_DIRECTION_ANY_RTL}, 19145 * {@link #TEXT_DIRECTION_LTR}, 19146 * {@link #TEXT_DIRECTION_RTL}, 19147 * {@link #TEXT_DIRECTION_LOCALE} 19148 * 19149 * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution 19150 * proceeds up the parent chain of the view to get the value. If there is no parent, then it will 19151 * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}. 19152 * 19153 * @attr ref android.R.styleable#View_textDirection 19154 */ 19155 public void setTextDirection(int textDirection) { 19156 if (getRawTextDirection() != textDirection) { 19157 // Reset the current text direction and the resolved one 19158 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 19159 resetResolvedTextDirection(); 19160 // Set the new text direction 19161 mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK); 19162 // Do resolution 19163 resolveTextDirection(); 19164 // Notify change 19165 onRtlPropertiesChanged(getLayoutDirection()); 19166 // Refresh 19167 requestLayout(); 19168 invalidate(true); 19169 } 19170 } 19171 19172 /** 19173 * Return the resolved text direction. 19174 * 19175 * @return the resolved text direction. Returns one of: 19176 * 19177 * {@link #TEXT_DIRECTION_FIRST_STRONG} 19178 * {@link #TEXT_DIRECTION_ANY_RTL}, 19179 * {@link #TEXT_DIRECTION_LTR}, 19180 * {@link #TEXT_DIRECTION_RTL}, 19181 * {@link #TEXT_DIRECTION_LOCALE} 19182 * 19183 * @attr ref android.R.styleable#View_textDirection 19184 */ 19185 @ViewDebug.ExportedProperty(category = "text", mapping = { 19186 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 19187 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 19188 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 19189 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 19190 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 19191 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 19192 }) 19193 public int getTextDirection() { 19194 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 19195 } 19196 19197 /** 19198 * Resolve the text direction. 19199 * 19200 * @return true if resolution has been done, false otherwise. 19201 * 19202 * @hide 19203 */ 19204 public boolean resolveTextDirection() { 19205 // Reset any previous text direction resolution 19206 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 19207 19208 if (hasRtlSupport()) { 19209 // Set resolved text direction flag depending on text direction flag 19210 final int textDirection = getRawTextDirection(); 19211 switch(textDirection) { 19212 case TEXT_DIRECTION_INHERIT: 19213 if (!canResolveTextDirection()) { 19214 // We cannot do the resolution if there is no parent, so use the default one 19215 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 19216 // Resolution will need to happen again later 19217 return false; 19218 } 19219 19220 // Parent has not yet resolved, so we still return the default 19221 try { 19222 if (!mParent.isTextDirectionResolved()) { 19223 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 19224 // Resolution will need to happen again later 19225 return false; 19226 } 19227 } catch (AbstractMethodError e) { 19228 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 19229 " does not fully implement ViewParent", e); 19230 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED | 19231 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 19232 return true; 19233 } 19234 19235 // Set current resolved direction to the same value as the parent's one 19236 int parentResolvedDirection; 19237 try { 19238 parentResolvedDirection = mParent.getTextDirection(); 19239 } catch (AbstractMethodError e) { 19240 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 19241 " does not fully implement ViewParent", e); 19242 parentResolvedDirection = TEXT_DIRECTION_LTR; 19243 } 19244 switch (parentResolvedDirection) { 19245 case TEXT_DIRECTION_FIRST_STRONG: 19246 case TEXT_DIRECTION_ANY_RTL: 19247 case TEXT_DIRECTION_LTR: 19248 case TEXT_DIRECTION_RTL: 19249 case TEXT_DIRECTION_LOCALE: 19250 mPrivateFlags2 |= 19251 (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 19252 break; 19253 default: 19254 // Default resolved direction is "first strong" heuristic 19255 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 19256 } 19257 break; 19258 case TEXT_DIRECTION_FIRST_STRONG: 19259 case TEXT_DIRECTION_ANY_RTL: 19260 case TEXT_DIRECTION_LTR: 19261 case TEXT_DIRECTION_RTL: 19262 case TEXT_DIRECTION_LOCALE: 19263 // Resolved direction is the same as text direction 19264 mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 19265 break; 19266 default: 19267 // Default resolved direction is "first strong" heuristic 19268 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 19269 } 19270 } else { 19271 // Default resolved direction is "first strong" heuristic 19272 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 19273 } 19274 19275 // Set to resolved 19276 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED; 19277 return true; 19278 } 19279 19280 /** 19281 * Check if text direction resolution can be done. 19282 * 19283 * @return true if text direction resolution can be done otherwise return false. 19284 */ 19285 public boolean canResolveTextDirection() { 19286 switch (getRawTextDirection()) { 19287 case TEXT_DIRECTION_INHERIT: 19288 if (mParent != null) { 19289 try { 19290 return mParent.canResolveTextDirection(); 19291 } catch (AbstractMethodError e) { 19292 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 19293 " does not fully implement ViewParent", e); 19294 } 19295 } 19296 return false; 19297 19298 default: 19299 return true; 19300 } 19301 } 19302 19303 /** 19304 * Reset resolved text direction. Text direction will be resolved during a call to 19305 * {@link #onMeasure(int, int)}. 19306 * 19307 * @hide 19308 */ 19309 public void resetResolvedTextDirection() { 19310 // Reset any previous text direction resolution 19311 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 19312 // Set to default value 19313 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 19314 } 19315 19316 /** 19317 * @return true if text direction is inherited. 19318 * 19319 * @hide 19320 */ 19321 public boolean isTextDirectionInherited() { 19322 return (getRawTextDirection() == TEXT_DIRECTION_INHERIT); 19323 } 19324 19325 /** 19326 * @return true if text direction is resolved. 19327 */ 19328 public boolean isTextDirectionResolved() { 19329 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED; 19330 } 19331 19332 /** 19333 * Return the value specifying the text alignment or policy that was set with 19334 * {@link #setTextAlignment(int)}. 19335 * 19336 * @return the defined text alignment. It can be one of: 19337 * 19338 * {@link #TEXT_ALIGNMENT_INHERIT}, 19339 * {@link #TEXT_ALIGNMENT_GRAVITY}, 19340 * {@link #TEXT_ALIGNMENT_CENTER}, 19341 * {@link #TEXT_ALIGNMENT_TEXT_START}, 19342 * {@link #TEXT_ALIGNMENT_TEXT_END}, 19343 * {@link #TEXT_ALIGNMENT_VIEW_START}, 19344 * {@link #TEXT_ALIGNMENT_VIEW_END} 19345 * 19346 * @attr ref android.R.styleable#View_textAlignment 19347 * 19348 * @hide 19349 */ 19350 @ViewDebug.ExportedProperty(category = "text", mapping = { 19351 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 19352 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 19353 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 19354 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 19355 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 19356 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 19357 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 19358 }) 19359 @TextAlignment 19360 public int getRawTextAlignment() { 19361 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 19362 } 19363 19364 /** 19365 * Set the text alignment. 19366 * 19367 * @param textAlignment The text alignment to set. Should be one of 19368 * 19369 * {@link #TEXT_ALIGNMENT_INHERIT}, 19370 * {@link #TEXT_ALIGNMENT_GRAVITY}, 19371 * {@link #TEXT_ALIGNMENT_CENTER}, 19372 * {@link #TEXT_ALIGNMENT_TEXT_START}, 19373 * {@link #TEXT_ALIGNMENT_TEXT_END}, 19374 * {@link #TEXT_ALIGNMENT_VIEW_START}, 19375 * {@link #TEXT_ALIGNMENT_VIEW_END} 19376 * 19377 * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution 19378 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 19379 * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}. 19380 * 19381 * @attr ref android.R.styleable#View_textAlignment 19382 */ 19383 public void setTextAlignment(@TextAlignment int textAlignment) { 19384 if (textAlignment != getRawTextAlignment()) { 19385 // Reset the current and resolved text alignment 19386 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 19387 resetResolvedTextAlignment(); 19388 // Set the new text alignment 19389 mPrivateFlags2 |= 19390 ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK); 19391 // Do resolution 19392 resolveTextAlignment(); 19393 // Notify change 19394 onRtlPropertiesChanged(getLayoutDirection()); 19395 // Refresh 19396 requestLayout(); 19397 invalidate(true); 19398 } 19399 } 19400 19401 /** 19402 * Return the resolved text alignment. 19403 * 19404 * @return the resolved text alignment. Returns one of: 19405 * 19406 * {@link #TEXT_ALIGNMENT_GRAVITY}, 19407 * {@link #TEXT_ALIGNMENT_CENTER}, 19408 * {@link #TEXT_ALIGNMENT_TEXT_START}, 19409 * {@link #TEXT_ALIGNMENT_TEXT_END}, 19410 * {@link #TEXT_ALIGNMENT_VIEW_START}, 19411 * {@link #TEXT_ALIGNMENT_VIEW_END} 19412 * 19413 * @attr ref android.R.styleable#View_textAlignment 19414 */ 19415 @ViewDebug.ExportedProperty(category = "text", mapping = { 19416 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 19417 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 19418 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 19419 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 19420 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 19421 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 19422 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 19423 }) 19424 @TextAlignment 19425 public int getTextAlignment() { 19426 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >> 19427 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 19428 } 19429 19430 /** 19431 * Resolve the text alignment. 19432 * 19433 * @return true if resolution has been done, false otherwise. 19434 * 19435 * @hide 19436 */ 19437 public boolean resolveTextAlignment() { 19438 // Reset any previous text alignment resolution 19439 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 19440 19441 if (hasRtlSupport()) { 19442 // Set resolved text alignment flag depending on text alignment flag 19443 final int textAlignment = getRawTextAlignment(); 19444 switch (textAlignment) { 19445 case TEXT_ALIGNMENT_INHERIT: 19446 // Check if we can resolve the text alignment 19447 if (!canResolveTextAlignment()) { 19448 // We cannot do the resolution if there is no parent so use the default 19449 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 19450 // Resolution will need to happen again later 19451 return false; 19452 } 19453 19454 // Parent has not yet resolved, so we still return the default 19455 try { 19456 if (!mParent.isTextAlignmentResolved()) { 19457 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 19458 // Resolution will need to happen again later 19459 return false; 19460 } 19461 } catch (AbstractMethodError e) { 19462 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 19463 " does not fully implement ViewParent", e); 19464 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED | 19465 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 19466 return true; 19467 } 19468 19469 int parentResolvedTextAlignment; 19470 try { 19471 parentResolvedTextAlignment = mParent.getTextAlignment(); 19472 } catch (AbstractMethodError e) { 19473 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 19474 " does not fully implement ViewParent", e); 19475 parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY; 19476 } 19477 switch (parentResolvedTextAlignment) { 19478 case TEXT_ALIGNMENT_GRAVITY: 19479 case TEXT_ALIGNMENT_TEXT_START: 19480 case TEXT_ALIGNMENT_TEXT_END: 19481 case TEXT_ALIGNMENT_CENTER: 19482 case TEXT_ALIGNMENT_VIEW_START: 19483 case TEXT_ALIGNMENT_VIEW_END: 19484 // Resolved text alignment is the same as the parent resolved 19485 // text alignment 19486 mPrivateFlags2 |= 19487 (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 19488 break; 19489 default: 19490 // Use default resolved text alignment 19491 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 19492 } 19493 break; 19494 case TEXT_ALIGNMENT_GRAVITY: 19495 case TEXT_ALIGNMENT_TEXT_START: 19496 case TEXT_ALIGNMENT_TEXT_END: 19497 case TEXT_ALIGNMENT_CENTER: 19498 case TEXT_ALIGNMENT_VIEW_START: 19499 case TEXT_ALIGNMENT_VIEW_END: 19500 // Resolved text alignment is the same as text alignment 19501 mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 19502 break; 19503 default: 19504 // Use default resolved text alignment 19505 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 19506 } 19507 } else { 19508 // Use default resolved text alignment 19509 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 19510 } 19511 19512 // Set the resolved 19513 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED; 19514 return true; 19515 } 19516 19517 /** 19518 * Check if text alignment resolution can be done. 19519 * 19520 * @return true if text alignment resolution can be done otherwise return false. 19521 */ 19522 public boolean canResolveTextAlignment() { 19523 switch (getRawTextAlignment()) { 19524 case TEXT_DIRECTION_INHERIT: 19525 if (mParent != null) { 19526 try { 19527 return mParent.canResolveTextAlignment(); 19528 } catch (AbstractMethodError e) { 19529 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 19530 " does not fully implement ViewParent", e); 19531 } 19532 } 19533 return false; 19534 19535 default: 19536 return true; 19537 } 19538 } 19539 19540 /** 19541 * Reset resolved text alignment. Text alignment will be resolved during a call to 19542 * {@link #onMeasure(int, int)}. 19543 * 19544 * @hide 19545 */ 19546 public void resetResolvedTextAlignment() { 19547 // Reset any previous text alignment resolution 19548 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 19549 // Set to default 19550 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 19551 } 19552 19553 /** 19554 * @return true if text alignment is inherited. 19555 * 19556 * @hide 19557 */ 19558 public boolean isTextAlignmentInherited() { 19559 return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT); 19560 } 19561 19562 /** 19563 * @return true if text alignment is resolved. 19564 */ 19565 public boolean isTextAlignmentResolved() { 19566 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED; 19567 } 19568 19569 /** 19570 * Generate a value suitable for use in {@link #setId(int)}. 19571 * This value will not collide with ID values generated at build time by aapt for R.id. 19572 * 19573 * @return a generated ID value 19574 */ 19575 public static int generateViewId() { 19576 for (;;) { 19577 final int result = sNextGeneratedId.get(); 19578 // aapt-generated IDs have the high byte nonzero; clamp to the range under that. 19579 int newValue = result + 1; 19580 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. 19581 if (sNextGeneratedId.compareAndSet(result, newValue)) { 19582 return result; 19583 } 19584 } 19585 } 19586 19587 /** 19588 * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions. 19589 * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and 19590 * a normal View or a ViewGroup with 19591 * {@link android.view.ViewGroup#isTransitionGroup()} true. 19592 * @hide 19593 */ 19594 public void captureTransitioningViews(List<View> transitioningViews) { 19595 if (getVisibility() == View.VISIBLE) { 19596 transitioningViews.add(this); 19597 } 19598 } 19599 19600 /** 19601 * Adds all Views that have {@link #getTransitionName()} non-null to namedElements. 19602 * @param namedElements Will contain all Views in the hierarchy having a transitionName. 19603 * @hide 19604 */ 19605 public void findNamedViews(Map<String, View> namedElements) { 19606 if (getVisibility() == VISIBLE || mGhostView != null) { 19607 String transitionName = getTransitionName(); 19608 if (transitionName != null) { 19609 namedElements.put(transitionName, this); 19610 } 19611 } 19612 } 19613 19614 // 19615 // Properties 19616 // 19617 /** 19618 * A Property wrapper around the <code>alpha</code> functionality handled by the 19619 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 19620 */ 19621 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 19622 @Override 19623 public void setValue(View object, float value) { 19624 object.setAlpha(value); 19625 } 19626 19627 @Override 19628 public Float get(View object) { 19629 return object.getAlpha(); 19630 } 19631 }; 19632 19633 /** 19634 * A Property wrapper around the <code>translationX</code> functionality handled by the 19635 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 19636 */ 19637 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 19638 @Override 19639 public void setValue(View object, float value) { 19640 object.setTranslationX(value); 19641 } 19642 19643 @Override 19644 public Float get(View object) { 19645 return object.getTranslationX(); 19646 } 19647 }; 19648 19649 /** 19650 * A Property wrapper around the <code>translationY</code> functionality handled by the 19651 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 19652 */ 19653 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 19654 @Override 19655 public void setValue(View object, float value) { 19656 object.setTranslationY(value); 19657 } 19658 19659 @Override 19660 public Float get(View object) { 19661 return object.getTranslationY(); 19662 } 19663 }; 19664 19665 /** 19666 * A Property wrapper around the <code>translationZ</code> functionality handled by the 19667 * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods. 19668 */ 19669 public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") { 19670 @Override 19671 public void setValue(View object, float value) { 19672 object.setTranslationZ(value); 19673 } 19674 19675 @Override 19676 public Float get(View object) { 19677 return object.getTranslationZ(); 19678 } 19679 }; 19680 19681 /** 19682 * A Property wrapper around the <code>x</code> functionality handled by the 19683 * {@link View#setX(float)} and {@link View#getX()} methods. 19684 */ 19685 public static final Property<View, Float> X = new FloatProperty<View>("x") { 19686 @Override 19687 public void setValue(View object, float value) { 19688 object.setX(value); 19689 } 19690 19691 @Override 19692 public Float get(View object) { 19693 return object.getX(); 19694 } 19695 }; 19696 19697 /** 19698 * A Property wrapper around the <code>y</code> functionality handled by the 19699 * {@link View#setY(float)} and {@link View#getY()} methods. 19700 */ 19701 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 19702 @Override 19703 public void setValue(View object, float value) { 19704 object.setY(value); 19705 } 19706 19707 @Override 19708 public Float get(View object) { 19709 return object.getY(); 19710 } 19711 }; 19712 19713 /** 19714 * A Property wrapper around the <code>z</code> functionality handled by the 19715 * {@link View#setZ(float)} and {@link View#getZ()} methods. 19716 */ 19717 public static final Property<View, Float> Z = new FloatProperty<View>("z") { 19718 @Override 19719 public void setValue(View object, float value) { 19720 object.setZ(value); 19721 } 19722 19723 @Override 19724 public Float get(View object) { 19725 return object.getZ(); 19726 } 19727 }; 19728 19729 /** 19730 * A Property wrapper around the <code>rotation</code> functionality handled by the 19731 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 19732 */ 19733 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 19734 @Override 19735 public void setValue(View object, float value) { 19736 object.setRotation(value); 19737 } 19738 19739 @Override 19740 public Float get(View object) { 19741 return object.getRotation(); 19742 } 19743 }; 19744 19745 /** 19746 * A Property wrapper around the <code>rotationX</code> functionality handled by the 19747 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 19748 */ 19749 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 19750 @Override 19751 public void setValue(View object, float value) { 19752 object.setRotationX(value); 19753 } 19754 19755 @Override 19756 public Float get(View object) { 19757 return object.getRotationX(); 19758 } 19759 }; 19760 19761 /** 19762 * A Property wrapper around the <code>rotationY</code> functionality handled by the 19763 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 19764 */ 19765 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 19766 @Override 19767 public void setValue(View object, float value) { 19768 object.setRotationY(value); 19769 } 19770 19771 @Override 19772 public Float get(View object) { 19773 return object.getRotationY(); 19774 } 19775 }; 19776 19777 /** 19778 * A Property wrapper around the <code>scaleX</code> functionality handled by the 19779 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 19780 */ 19781 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 19782 @Override 19783 public void setValue(View object, float value) { 19784 object.setScaleX(value); 19785 } 19786 19787 @Override 19788 public Float get(View object) { 19789 return object.getScaleX(); 19790 } 19791 }; 19792 19793 /** 19794 * A Property wrapper around the <code>scaleY</code> functionality handled by the 19795 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 19796 */ 19797 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 19798 @Override 19799 public void setValue(View object, float value) { 19800 object.setScaleY(value); 19801 } 19802 19803 @Override 19804 public Float get(View object) { 19805 return object.getScaleY(); 19806 } 19807 }; 19808 19809 /** 19810 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 19811 * Each MeasureSpec represents a requirement for either the width or the height. 19812 * A MeasureSpec is comprised of a size and a mode. There are three possible 19813 * modes: 19814 * <dl> 19815 * <dt>UNSPECIFIED</dt> 19816 * <dd> 19817 * The parent has not imposed any constraint on the child. It can be whatever size 19818 * it wants. 19819 * </dd> 19820 * 19821 * <dt>EXACTLY</dt> 19822 * <dd> 19823 * The parent has determined an exact size for the child. The child is going to be 19824 * given those bounds regardless of how big it wants to be. 19825 * </dd> 19826 * 19827 * <dt>AT_MOST</dt> 19828 * <dd> 19829 * The child can be as large as it wants up to the specified size. 19830 * </dd> 19831 * </dl> 19832 * 19833 * MeasureSpecs are implemented as ints to reduce object allocation. This class 19834 * is provided to pack and unpack the <size, mode> tuple into the int. 19835 */ 19836 public static class MeasureSpec { 19837 private static final int MODE_SHIFT = 30; 19838 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 19839 19840 /** 19841 * Measure specification mode: The parent has not imposed any constraint 19842 * on the child. It can be whatever size it wants. 19843 */ 19844 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 19845 19846 /** 19847 * Measure specification mode: The parent has determined an exact size 19848 * for the child. The child is going to be given those bounds regardless 19849 * of how big it wants to be. 19850 */ 19851 public static final int EXACTLY = 1 << MODE_SHIFT; 19852 19853 /** 19854 * Measure specification mode: The child can be as large as it wants up 19855 * to the specified size. 19856 */ 19857 public static final int AT_MOST = 2 << MODE_SHIFT; 19858 19859 /** 19860 * Creates a measure specification based on the supplied size and mode. 19861 * 19862 * The mode must always be one of the following: 19863 * <ul> 19864 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 19865 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 19866 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 19867 * </ul> 19868 * 19869 * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's 19870 * implementation was such that the order of arguments did not matter 19871 * and overflow in either value could impact the resulting MeasureSpec. 19872 * {@link android.widget.RelativeLayout} was affected by this bug. 19873 * Apps targeting API levels greater than 17 will get the fixed, more strict 19874 * behavior.</p> 19875 * 19876 * @param size the size of the measure specification 19877 * @param mode the mode of the measure specification 19878 * @return the measure specification based on size and mode 19879 */ 19880 public static int makeMeasureSpec(int size, int mode) { 19881 if (sUseBrokenMakeMeasureSpec) { 19882 return size + mode; 19883 } else { 19884 return (size & ~MODE_MASK) | (mode & MODE_MASK); 19885 } 19886 } 19887 19888 /** 19889 * Extracts the mode from the supplied measure specification. 19890 * 19891 * @param measureSpec the measure specification to extract the mode from 19892 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 19893 * {@link android.view.View.MeasureSpec#AT_MOST} or 19894 * {@link android.view.View.MeasureSpec#EXACTLY} 19895 */ 19896 public static int getMode(int measureSpec) { 19897 return (measureSpec & MODE_MASK); 19898 } 19899 19900 /** 19901 * Extracts the size from the supplied measure specification. 19902 * 19903 * @param measureSpec the measure specification to extract the size from 19904 * @return the size in pixels defined in the supplied measure specification 19905 */ 19906 public static int getSize(int measureSpec) { 19907 return (measureSpec & ~MODE_MASK); 19908 } 19909 19910 static int adjust(int measureSpec, int delta) { 19911 final int mode = getMode(measureSpec); 19912 if (mode == UNSPECIFIED) { 19913 // No need to adjust size for UNSPECIFIED mode. 19914 return makeMeasureSpec(0, UNSPECIFIED); 19915 } 19916 int size = getSize(measureSpec) + delta; 19917 if (size < 0) { 19918 Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size + 19919 ") spec: " + toString(measureSpec) + " delta: " + delta); 19920 size = 0; 19921 } 19922 return makeMeasureSpec(size, mode); 19923 } 19924 19925 /** 19926 * Returns a String representation of the specified measure 19927 * specification. 19928 * 19929 * @param measureSpec the measure specification to convert to a String 19930 * @return a String with the following format: "MeasureSpec: MODE SIZE" 19931 */ 19932 public static String toString(int measureSpec) { 19933 int mode = getMode(measureSpec); 19934 int size = getSize(measureSpec); 19935 19936 StringBuilder sb = new StringBuilder("MeasureSpec: "); 19937 19938 if (mode == UNSPECIFIED) 19939 sb.append("UNSPECIFIED "); 19940 else if (mode == EXACTLY) 19941 sb.append("EXACTLY "); 19942 else if (mode == AT_MOST) 19943 sb.append("AT_MOST "); 19944 else 19945 sb.append(mode).append(" "); 19946 19947 sb.append(size); 19948 return sb.toString(); 19949 } 19950 } 19951 19952 private final class CheckForLongPress implements Runnable { 19953 private int mOriginalWindowAttachCount; 19954 19955 @Override 19956 public void run() { 19957 if (isPressed() && (mParent != null) 19958 && mOriginalWindowAttachCount == mWindowAttachCount) { 19959 if (performLongClick()) { 19960 mHasPerformedLongPress = true; 19961 } 19962 } 19963 } 19964 19965 public void rememberWindowAttachCount() { 19966 mOriginalWindowAttachCount = mWindowAttachCount; 19967 } 19968 } 19969 19970 private final class CheckForTap implements Runnable { 19971 public float x; 19972 public float y; 19973 19974 @Override 19975 public void run() { 19976 mPrivateFlags &= ~PFLAG_PREPRESSED; 19977 setPressed(true, x, y); 19978 checkForLongClick(ViewConfiguration.getTapTimeout()); 19979 } 19980 } 19981 19982 private final class PerformClick implements Runnable { 19983 @Override 19984 public void run() { 19985 performClick(); 19986 } 19987 } 19988 19989 /** @hide */ 19990 public void hackTurnOffWindowResizeAnim(boolean off) { 19991 mAttachInfo.mTurnOffWindowResizeAnim = off; 19992 } 19993 19994 /** 19995 * This method returns a ViewPropertyAnimator object, which can be used to animate 19996 * specific properties on this View. 19997 * 19998 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 19999 */ 20000 public ViewPropertyAnimator animate() { 20001 if (mAnimator == null) { 20002 mAnimator = new ViewPropertyAnimator(this); 20003 } 20004 return mAnimator; 20005 } 20006 20007 /** 20008 * Sets the name of the View to be used to identify Views in Transitions. 20009 * Names should be unique in the View hierarchy. 20010 * 20011 * @param transitionName The name of the View to uniquely identify it for Transitions. 20012 */ 20013 public final void setTransitionName(String transitionName) { 20014 mTransitionName = transitionName; 20015 } 20016 20017 /** 20018 * Returns the name of the View to be used to identify Views in Transitions. 20019 * Names should be unique in the View hierarchy. 20020 * 20021 * <p>This returns null if the View has not been given a name.</p> 20022 * 20023 * @return The name used of the View to be used to identify Views in Transitions or null 20024 * if no name has been given. 20025 */ 20026 @ViewDebug.ExportedProperty 20027 public String getTransitionName() { 20028 return mTransitionName; 20029 } 20030 20031 /** 20032 * Interface definition for a callback to be invoked when a hardware key event is 20033 * dispatched to this view. The callback will be invoked before the key event is 20034 * given to the view. This is only useful for hardware keyboards; a software input 20035 * method has no obligation to trigger this listener. 20036 */ 20037 public interface OnKeyListener { 20038 /** 20039 * Called when a hardware key is dispatched to a view. This allows listeners to 20040 * get a chance to respond before the target view. 20041 * <p>Key presses in software keyboards will generally NOT trigger this method, 20042 * although some may elect to do so in some situations. Do not assume a 20043 * software input method has to be key-based; even if it is, it may use key presses 20044 * in a different way than you expect, so there is no way to reliably catch soft 20045 * input key presses. 20046 * 20047 * @param v The view the key has been dispatched to. 20048 * @param keyCode The code for the physical key that was pressed 20049 * @param event The KeyEvent object containing full information about 20050 * the event. 20051 * @return True if the listener has consumed the event, false otherwise. 20052 */ 20053 boolean onKey(View v, int keyCode, KeyEvent event); 20054 } 20055 20056 /** 20057 * Interface definition for a callback to be invoked when a touch event is 20058 * dispatched to this view. The callback will be invoked before the touch 20059 * event is given to the view. 20060 */ 20061 public interface OnTouchListener { 20062 /** 20063 * Called when a touch event is dispatched to a view. This allows listeners to 20064 * get a chance to respond before the target view. 20065 * 20066 * @param v The view the touch event has been dispatched to. 20067 * @param event The MotionEvent object containing full information about 20068 * the event. 20069 * @return True if the listener has consumed the event, false otherwise. 20070 */ 20071 boolean onTouch(View v, MotionEvent event); 20072 } 20073 20074 /** 20075 * Interface definition for a callback to be invoked when a hover event is 20076 * dispatched to this view. The callback will be invoked before the hover 20077 * event is given to the view. 20078 */ 20079 public interface OnHoverListener { 20080 /** 20081 * Called when a hover event is dispatched to a view. This allows listeners to 20082 * get a chance to respond before the target view. 20083 * 20084 * @param v The view the hover event has been dispatched to. 20085 * @param event The MotionEvent object containing full information about 20086 * the event. 20087 * @return True if the listener has consumed the event, false otherwise. 20088 */ 20089 boolean onHover(View v, MotionEvent event); 20090 } 20091 20092 /** 20093 * Interface definition for a callback to be invoked when a generic motion event is 20094 * dispatched to this view. The callback will be invoked before the generic motion 20095 * event is given to the view. 20096 */ 20097 public interface OnGenericMotionListener { 20098 /** 20099 * Called when a generic motion event is dispatched to a view. This allows listeners to 20100 * get a chance to respond before the target view. 20101 * 20102 * @param v The view the generic motion event has been dispatched to. 20103 * @param event The MotionEvent object containing full information about 20104 * the event. 20105 * @return True if the listener has consumed the event, false otherwise. 20106 */ 20107 boolean onGenericMotion(View v, MotionEvent event); 20108 } 20109 20110 /** 20111 * Interface definition for a callback to be invoked when a view has been clicked and held. 20112 */ 20113 public interface OnLongClickListener { 20114 /** 20115 * Called when a view has been clicked and held. 20116 * 20117 * @param v The view that was clicked and held. 20118 * 20119 * @return true if the callback consumed the long click, false otherwise. 20120 */ 20121 boolean onLongClick(View v); 20122 } 20123 20124 /** 20125 * Interface definition for a callback to be invoked when a drag is being dispatched 20126 * to this view. The callback will be invoked before the hosting view's own 20127 * onDrag(event) method. If the listener wants to fall back to the hosting view's 20128 * onDrag(event) behavior, it should return 'false' from this callback. 20129 * 20130 * <div class="special reference"> 20131 * <h3>Developer Guides</h3> 20132 * <p>For a guide to implementing drag and drop features, read the 20133 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 20134 * </div> 20135 */ 20136 public interface OnDragListener { 20137 /** 20138 * Called when a drag event is dispatched to a view. This allows listeners 20139 * to get a chance to override base View behavior. 20140 * 20141 * @param v The View that received the drag event. 20142 * @param event The {@link android.view.DragEvent} object for the drag event. 20143 * @return {@code true} if the drag event was handled successfully, or {@code false} 20144 * if the drag event was not handled. Note that {@code false} will trigger the View 20145 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 20146 */ 20147 boolean onDrag(View v, DragEvent event); 20148 } 20149 20150 /** 20151 * Interface definition for a callback to be invoked when the focus state of 20152 * a view changed. 20153 */ 20154 public interface OnFocusChangeListener { 20155 /** 20156 * Called when the focus state of a view has changed. 20157 * 20158 * @param v The view whose state has changed. 20159 * @param hasFocus The new focus state of v. 20160 */ 20161 void onFocusChange(View v, boolean hasFocus); 20162 } 20163 20164 /** 20165 * Interface definition for a callback to be invoked when a view is clicked. 20166 */ 20167 public interface OnClickListener { 20168 /** 20169 * Called when a view has been clicked. 20170 * 20171 * @param v The view that was clicked. 20172 */ 20173 void onClick(View v); 20174 } 20175 20176 /** 20177 * Interface definition for a callback to be invoked when the context menu 20178 * for this view is being built. 20179 */ 20180 public interface OnCreateContextMenuListener { 20181 /** 20182 * Called when the context menu for this view is being built. It is not 20183 * safe to hold onto the menu after this method returns. 20184 * 20185 * @param menu The context menu that is being built 20186 * @param v The view for which the context menu is being built 20187 * @param menuInfo Extra information about the item for which the 20188 * context menu should be shown. This information will vary 20189 * depending on the class of v. 20190 */ 20191 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 20192 } 20193 20194 /** 20195 * Interface definition for a callback to be invoked when the status bar changes 20196 * visibility. This reports <strong>global</strong> changes to the system UI 20197 * state, not what the application is requesting. 20198 * 20199 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 20200 */ 20201 public interface OnSystemUiVisibilityChangeListener { 20202 /** 20203 * Called when the status bar changes visibility because of a call to 20204 * {@link View#setSystemUiVisibility(int)}. 20205 * 20206 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 20207 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}. 20208 * This tells you the <strong>global</strong> state of these UI visibility 20209 * flags, not what your app is currently applying. 20210 */ 20211 public void onSystemUiVisibilityChange(int visibility); 20212 } 20213 20214 /** 20215 * Interface definition for a callback to be invoked when this view is attached 20216 * or detached from its window. 20217 */ 20218 public interface OnAttachStateChangeListener { 20219 /** 20220 * Called when the view is attached to a window. 20221 * @param v The view that was attached 20222 */ 20223 public void onViewAttachedToWindow(View v); 20224 /** 20225 * Called when the view is detached from a window. 20226 * @param v The view that was detached 20227 */ 20228 public void onViewDetachedFromWindow(View v); 20229 } 20230 20231 /** 20232 * Listener for applying window insets on a view in a custom way. 20233 * 20234 * <p>Apps may choose to implement this interface if they want to apply custom policy 20235 * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener 20236 * is set, its 20237 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 20238 * method will be called instead of the View's own 20239 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener 20240 * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply 20241 * the View's normal behavior as part of its own.</p> 20242 */ 20243 public interface OnApplyWindowInsetsListener { 20244 /** 20245 * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set} 20246 * on a View, this listener method will be called instead of the view's own 20247 * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 20248 * 20249 * @param v The view applying window insets 20250 * @param insets The insets to apply 20251 * @return The insets supplied, minus any insets that were consumed 20252 */ 20253 public WindowInsets onApplyWindowInsets(View v, WindowInsets insets); 20254 } 20255 20256 private final class UnsetPressedState implements Runnable { 20257 @Override 20258 public void run() { 20259 setPressed(false); 20260 } 20261 } 20262 20263 /** 20264 * Base class for derived classes that want to save and restore their own 20265 * state in {@link android.view.View#onSaveInstanceState()}. 20266 */ 20267 public static class BaseSavedState extends AbsSavedState { 20268 /** 20269 * Constructor used when reading from a parcel. Reads the state of the superclass. 20270 * 20271 * @param source 20272 */ 20273 public BaseSavedState(Parcel source) { 20274 super(source); 20275 } 20276 20277 /** 20278 * Constructor called by derived classes when creating their SavedState objects 20279 * 20280 * @param superState The state of the superclass of this view 20281 */ 20282 public BaseSavedState(Parcelable superState) { 20283 super(superState); 20284 } 20285 20286 public static final Parcelable.Creator<BaseSavedState> CREATOR = 20287 new Parcelable.Creator<BaseSavedState>() { 20288 public BaseSavedState createFromParcel(Parcel in) { 20289 return new BaseSavedState(in); 20290 } 20291 20292 public BaseSavedState[] newArray(int size) { 20293 return new BaseSavedState[size]; 20294 } 20295 }; 20296 } 20297 20298 /** 20299 * A set of information given to a view when it is attached to its parent 20300 * window. 20301 */ 20302 final static class AttachInfo { 20303 interface Callbacks { 20304 void playSoundEffect(int effectId); 20305 boolean performHapticFeedback(int effectId, boolean always); 20306 } 20307 20308 /** 20309 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 20310 * to a Handler. This class contains the target (View) to invalidate and 20311 * the coordinates of the dirty rectangle. 20312 * 20313 * For performance purposes, this class also implements a pool of up to 20314 * POOL_LIMIT objects that get reused. This reduces memory allocations 20315 * whenever possible. 20316 */ 20317 static class InvalidateInfo { 20318 private static final int POOL_LIMIT = 10; 20319 20320 private static final SynchronizedPool<InvalidateInfo> sPool = 20321 new SynchronizedPool<InvalidateInfo>(POOL_LIMIT); 20322 20323 View target; 20324 20325 int left; 20326 int top; 20327 int right; 20328 int bottom; 20329 20330 public static InvalidateInfo obtain() { 20331 InvalidateInfo instance = sPool.acquire(); 20332 return (instance != null) ? instance : new InvalidateInfo(); 20333 } 20334 20335 public void recycle() { 20336 target = null; 20337 sPool.release(this); 20338 } 20339 } 20340 20341 final IWindowSession mSession; 20342 20343 final IWindow mWindow; 20344 20345 final IBinder mWindowToken; 20346 20347 final Display mDisplay; 20348 20349 final Callbacks mRootCallbacks; 20350 20351 IWindowId mIWindowId; 20352 WindowId mWindowId; 20353 20354 /** 20355 * The top view of the hierarchy. 20356 */ 20357 View mRootView; 20358 20359 IBinder mPanelParentWindowToken; 20360 20361 boolean mHardwareAccelerated; 20362 boolean mHardwareAccelerationRequested; 20363 HardwareRenderer mHardwareRenderer; 20364 List<RenderNode> mPendingAnimatingRenderNodes; 20365 20366 /** 20367 * The state of the display to which the window is attached, as reported 20368 * by {@link Display#getState()}. Note that the display state constants 20369 * declared by {@link Display} do not exactly line up with the screen state 20370 * constants declared by {@link View} (there are more display states than 20371 * screen states). 20372 */ 20373 int mDisplayState = Display.STATE_UNKNOWN; 20374 20375 /** 20376 * Scale factor used by the compatibility mode 20377 */ 20378 float mApplicationScale; 20379 20380 /** 20381 * Indicates whether the application is in compatibility mode 20382 */ 20383 boolean mScalingRequired; 20384 20385 /** 20386 * If set, ViewRootImpl doesn't use its lame animation for when the window resizes. 20387 */ 20388 boolean mTurnOffWindowResizeAnim; 20389 20390 /** 20391 * Left position of this view's window 20392 */ 20393 int mWindowLeft; 20394 20395 /** 20396 * Top position of this view's window 20397 */ 20398 int mWindowTop; 20399 20400 /** 20401 * Indicates whether views need to use 32-bit drawing caches 20402 */ 20403 boolean mUse32BitDrawingCache; 20404 20405 /** 20406 * For windows that are full-screen but using insets to layout inside 20407 * of the screen areas, these are the current insets to appear inside 20408 * the overscan area of the display. 20409 */ 20410 final Rect mOverscanInsets = new Rect(); 20411 20412 /** 20413 * For windows that are full-screen but using insets to layout inside 20414 * of the screen decorations, these are the current insets for the 20415 * content of the window. 20416 */ 20417 final Rect mContentInsets = new Rect(); 20418 20419 /** 20420 * For windows that are full-screen but using insets to layout inside 20421 * of the screen decorations, these are the current insets for the 20422 * actual visible parts of the window. 20423 */ 20424 final Rect mVisibleInsets = new Rect(); 20425 20426 /** 20427 * For windows that are full-screen but using insets to layout inside 20428 * of the screen decorations, these are the current insets for the 20429 * stable system windows. 20430 */ 20431 final Rect mStableInsets = new Rect(); 20432 20433 /** 20434 * The internal insets given by this window. This value is 20435 * supplied by the client (through 20436 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 20437 * be given to the window manager when changed to be used in laying 20438 * out windows behind it. 20439 */ 20440 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 20441 = new ViewTreeObserver.InternalInsetsInfo(); 20442 20443 /** 20444 * Set to true when mGivenInternalInsets is non-empty. 20445 */ 20446 boolean mHasNonEmptyGivenInternalInsets; 20447 20448 /** 20449 * All views in the window's hierarchy that serve as scroll containers, 20450 * used to determine if the window can be resized or must be panned 20451 * to adjust for a soft input area. 20452 */ 20453 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 20454 20455 final KeyEvent.DispatcherState mKeyDispatchState 20456 = new KeyEvent.DispatcherState(); 20457 20458 /** 20459 * Indicates whether the view's window currently has the focus. 20460 */ 20461 boolean mHasWindowFocus; 20462 20463 /** 20464 * The current visibility of the window. 20465 */ 20466 int mWindowVisibility; 20467 20468 /** 20469 * Indicates the time at which drawing started to occur. 20470 */ 20471 long mDrawingTime; 20472 20473 /** 20474 * Indicates whether or not ignoring the DIRTY_MASK flags. 20475 */ 20476 boolean mIgnoreDirtyState; 20477 20478 /** 20479 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 20480 * to avoid clearing that flag prematurely. 20481 */ 20482 boolean mSetIgnoreDirtyState = false; 20483 20484 /** 20485 * Indicates whether the view's window is currently in touch mode. 20486 */ 20487 boolean mInTouchMode; 20488 20489 /** 20490 * Indicates whether the view has requested unbuffered input dispatching for the current 20491 * event stream. 20492 */ 20493 boolean mUnbufferedDispatchRequested; 20494 20495 /** 20496 * Indicates that ViewAncestor should trigger a global layout change 20497 * the next time it performs a traversal 20498 */ 20499 boolean mRecomputeGlobalAttributes; 20500 20501 /** 20502 * Always report new attributes at next traversal. 20503 */ 20504 boolean mForceReportNewAttributes; 20505 20506 /** 20507 * Set during a traveral if any views want to keep the screen on. 20508 */ 20509 boolean mKeepScreenOn; 20510 20511 /** 20512 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 20513 */ 20514 int mSystemUiVisibility; 20515 20516 /** 20517 * Hack to force certain system UI visibility flags to be cleared. 20518 */ 20519 int mDisabledSystemUiVisibility; 20520 20521 /** 20522 * Last global system UI visibility reported by the window manager. 20523 */ 20524 int mGlobalSystemUiVisibility; 20525 20526 /** 20527 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 20528 * attached. 20529 */ 20530 boolean mHasSystemUiListeners; 20531 20532 /** 20533 * Set if the window has requested to extend into the overscan region 20534 * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN. 20535 */ 20536 boolean mOverscanRequested; 20537 20538 /** 20539 * Set if the visibility of any views has changed. 20540 */ 20541 boolean mViewVisibilityChanged; 20542 20543 /** 20544 * Set to true if a view has been scrolled. 20545 */ 20546 boolean mViewScrollChanged; 20547 20548 /** 20549 * Set to true if high contrast mode enabled 20550 */ 20551 boolean mHighContrastText; 20552 20553 /** 20554 * Global to the view hierarchy used as a temporary for dealing with 20555 * x/y points in the transparent region computations. 20556 */ 20557 final int[] mTransparentLocation = new int[2]; 20558 20559 /** 20560 * Global to the view hierarchy used as a temporary for dealing with 20561 * x/y points in the ViewGroup.invalidateChild implementation. 20562 */ 20563 final int[] mInvalidateChildLocation = new int[2]; 20564 20565 /** 20566 * Global to the view hierarchy used as a temporary for dealng with 20567 * computing absolute on-screen location. 20568 */ 20569 final int[] mTmpLocation = new int[2]; 20570 20571 /** 20572 * Global to the view hierarchy used as a temporary for dealing with 20573 * x/y location when view is transformed. 20574 */ 20575 final float[] mTmpTransformLocation = new float[2]; 20576 20577 /** 20578 * The view tree observer used to dispatch global events like 20579 * layout, pre-draw, touch mode change, etc. 20580 */ 20581 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 20582 20583 /** 20584 * A Canvas used by the view hierarchy to perform bitmap caching. 20585 */ 20586 Canvas mCanvas; 20587 20588 /** 20589 * The view root impl. 20590 */ 20591 final ViewRootImpl mViewRootImpl; 20592 20593 /** 20594 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 20595 * handler can be used to pump events in the UI events queue. 20596 */ 20597 final Handler mHandler; 20598 20599 /** 20600 * Temporary for use in computing invalidate rectangles while 20601 * calling up the hierarchy. 20602 */ 20603 final Rect mTmpInvalRect = new Rect(); 20604 20605 /** 20606 * Temporary for use in computing hit areas with transformed views 20607 */ 20608 final RectF mTmpTransformRect = new RectF(); 20609 20610 /** 20611 * Temporary for use in computing hit areas with transformed views 20612 */ 20613 final RectF mTmpTransformRect1 = new RectF(); 20614 20615 /** 20616 * Temporary list of rectanges. 20617 */ 20618 final List<RectF> mTmpRectList = new ArrayList<>(); 20619 20620 /** 20621 * Temporary for use in transforming invalidation rect 20622 */ 20623 final Matrix mTmpMatrix = new Matrix(); 20624 20625 /** 20626 * Temporary for use in transforming invalidation rect 20627 */ 20628 final Transformation mTmpTransformation = new Transformation(); 20629 20630 /** 20631 * Temporary for use in querying outlines from OutlineProviders 20632 */ 20633 final Outline mTmpOutline = new Outline(); 20634 20635 /** 20636 * Temporary list for use in collecting focusable descendents of a view. 20637 */ 20638 final ArrayList<View> mTempArrayList = new ArrayList<View>(24); 20639 20640 /** 20641 * The id of the window for accessibility purposes. 20642 */ 20643 int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 20644 20645 /** 20646 * Flags related to accessibility processing. 20647 * 20648 * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS 20649 * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS 20650 */ 20651 int mAccessibilityFetchFlags; 20652 20653 /** 20654 * The drawable for highlighting accessibility focus. 20655 */ 20656 Drawable mAccessibilityFocusDrawable; 20657 20658 /** 20659 * Show where the margins, bounds and layout bounds are for each view. 20660 */ 20661 boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false); 20662 20663 /** 20664 * Point used to compute visible regions. 20665 */ 20666 final Point mPoint = new Point(); 20667 20668 /** 20669 * Used to track which View originated a requestLayout() call, used when 20670 * requestLayout() is called during layout. 20671 */ 20672 View mViewRequestingLayout; 20673 20674 /** 20675 * Creates a new set of attachment information with the specified 20676 * events handler and thread. 20677 * 20678 * @param handler the events handler the view must use 20679 */ 20680 AttachInfo(IWindowSession session, IWindow window, Display display, 20681 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) { 20682 mSession = session; 20683 mWindow = window; 20684 mWindowToken = window.asBinder(); 20685 mDisplay = display; 20686 mViewRootImpl = viewRootImpl; 20687 mHandler = handler; 20688 mRootCallbacks = effectPlayer; 20689 } 20690 } 20691 20692 /** 20693 * <p>ScrollabilityCache holds various fields used by a View when scrolling 20694 * is supported. This avoids keeping too many unused fields in most 20695 * instances of View.</p> 20696 */ 20697 private static class ScrollabilityCache implements Runnable { 20698 20699 /** 20700 * Scrollbars are not visible 20701 */ 20702 public static final int OFF = 0; 20703 20704 /** 20705 * Scrollbars are visible 20706 */ 20707 public static final int ON = 1; 20708 20709 /** 20710 * Scrollbars are fading away 20711 */ 20712 public static final int FADING = 2; 20713 20714 public boolean fadeScrollBars; 20715 20716 public int fadingEdgeLength; 20717 public int scrollBarDefaultDelayBeforeFade; 20718 public int scrollBarFadeDuration; 20719 20720 public int scrollBarSize; 20721 public ScrollBarDrawable scrollBar; 20722 public float[] interpolatorValues; 20723 public View host; 20724 20725 public final Paint paint; 20726 public final Matrix matrix; 20727 public Shader shader; 20728 20729 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 20730 20731 private static final float[] OPAQUE = { 255 }; 20732 private static final float[] TRANSPARENT = { 0.0f }; 20733 20734 /** 20735 * When fading should start. This time moves into the future every time 20736 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 20737 */ 20738 public long fadeStartTime; 20739 20740 20741 /** 20742 * The current state of the scrollbars: ON, OFF, or FADING 20743 */ 20744 public int state = OFF; 20745 20746 private int mLastColor; 20747 20748 public ScrollabilityCache(ViewConfiguration configuration, View host) { 20749 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 20750 scrollBarSize = configuration.getScaledScrollBarSize(); 20751 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 20752 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 20753 20754 paint = new Paint(); 20755 matrix = new Matrix(); 20756 // use use a height of 1, and then wack the matrix each time we 20757 // actually use it. 20758 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 20759 paint.setShader(shader); 20760 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 20761 20762 this.host = host; 20763 } 20764 20765 public void setFadeColor(int color) { 20766 if (color != mLastColor) { 20767 mLastColor = color; 20768 20769 if (color != 0) { 20770 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 20771 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 20772 paint.setShader(shader); 20773 // Restore the default transfer mode (src_over) 20774 paint.setXfermode(null); 20775 } else { 20776 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 20777 paint.setShader(shader); 20778 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 20779 } 20780 } 20781 } 20782 20783 public void run() { 20784 long now = AnimationUtils.currentAnimationTimeMillis(); 20785 if (now >= fadeStartTime) { 20786 20787 // the animation fades the scrollbars out by changing 20788 // the opacity (alpha) from fully opaque to fully 20789 // transparent 20790 int nextFrame = (int) now; 20791 int framesCount = 0; 20792 20793 Interpolator interpolator = scrollBarInterpolator; 20794 20795 // Start opaque 20796 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 20797 20798 // End transparent 20799 nextFrame += scrollBarFadeDuration; 20800 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 20801 20802 state = FADING; 20803 20804 // Kick off the fade animation 20805 host.invalidate(true); 20806 } 20807 } 20808 } 20809 20810 /** 20811 * Resuable callback for sending 20812 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 20813 */ 20814 private class SendViewScrolledAccessibilityEvent implements Runnable { 20815 public volatile boolean mIsPending; 20816 20817 public void run() { 20818 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 20819 mIsPending = false; 20820 } 20821 } 20822 20823 /** 20824 * <p> 20825 * This class represents a delegate that can be registered in a {@link View} 20826 * to enhance accessibility support via composition rather via inheritance. 20827 * It is specifically targeted to widget developers that extend basic View 20828 * classes i.e. classes in package android.view, that would like their 20829 * applications to be backwards compatible. 20830 * </p> 20831 * <div class="special reference"> 20832 * <h3>Developer Guides</h3> 20833 * <p>For more information about making applications accessible, read the 20834 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a> 20835 * developer guide.</p> 20836 * </div> 20837 * <p> 20838 * A scenario in which a developer would like to use an accessibility delegate 20839 * is overriding a method introduced in a later API version then the minimal API 20840 * version supported by the application. For example, the method 20841 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 20842 * in API version 4 when the accessibility APIs were first introduced. If a 20843 * developer would like his application to run on API version 4 devices (assuming 20844 * all other APIs used by the application are version 4 or lower) and take advantage 20845 * of this method, instead of overriding the method which would break the application's 20846 * backwards compatibility, he can override the corresponding method in this 20847 * delegate and register the delegate in the target View if the API version of 20848 * the system is high enough i.e. the API version is same or higher to the API 20849 * version that introduced 20850 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 20851 * </p> 20852 * <p> 20853 * Here is an example implementation: 20854 * </p> 20855 * <code><pre><p> 20856 * if (Build.VERSION.SDK_INT >= 14) { 20857 * // If the API version is equal of higher than the version in 20858 * // which onInitializeAccessibilityNodeInfo was introduced we 20859 * // register a delegate with a customized implementation. 20860 * View view = findViewById(R.id.view_id); 20861 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 20862 * public void onInitializeAccessibilityNodeInfo(View host, 20863 * AccessibilityNodeInfo info) { 20864 * // Let the default implementation populate the info. 20865 * super.onInitializeAccessibilityNodeInfo(host, info); 20866 * // Set some other information. 20867 * info.setEnabled(host.isEnabled()); 20868 * } 20869 * }); 20870 * } 20871 * </code></pre></p> 20872 * <p> 20873 * This delegate contains methods that correspond to the accessibility methods 20874 * in View. If a delegate has been specified the implementation in View hands 20875 * off handling to the corresponding method in this delegate. The default 20876 * implementation the delegate methods behaves exactly as the corresponding 20877 * method in View for the case of no accessibility delegate been set. Hence, 20878 * to customize the behavior of a View method, clients can override only the 20879 * corresponding delegate method without altering the behavior of the rest 20880 * accessibility related methods of the host view. 20881 * </p> 20882 */ 20883 public static class AccessibilityDelegate { 20884 20885 /** 20886 * Sends an accessibility event of the given type. If accessibility is not 20887 * enabled this method has no effect. 20888 * <p> 20889 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 20890 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 20891 * been set. 20892 * </p> 20893 * 20894 * @param host The View hosting the delegate. 20895 * @param eventType The type of the event to send. 20896 * 20897 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 20898 */ 20899 public void sendAccessibilityEvent(View host, int eventType) { 20900 host.sendAccessibilityEventInternal(eventType); 20901 } 20902 20903 /** 20904 * Performs the specified accessibility action on the view. For 20905 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 20906 * <p> 20907 * The default implementation behaves as 20908 * {@link View#performAccessibilityAction(int, Bundle) 20909 * View#performAccessibilityAction(int, Bundle)} for the case of 20910 * no accessibility delegate been set. 20911 * </p> 20912 * 20913 * @param action The action to perform. 20914 * @return Whether the action was performed. 20915 * 20916 * @see View#performAccessibilityAction(int, Bundle) 20917 * View#performAccessibilityAction(int, Bundle) 20918 */ 20919 public boolean performAccessibilityAction(View host, int action, Bundle args) { 20920 return host.performAccessibilityActionInternal(action, args); 20921 } 20922 20923 /** 20924 * Sends an accessibility event. This method behaves exactly as 20925 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 20926 * empty {@link AccessibilityEvent} and does not perform a check whether 20927 * accessibility is enabled. 20928 * <p> 20929 * The default implementation behaves as 20930 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20931 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 20932 * the case of no accessibility delegate been set. 20933 * </p> 20934 * 20935 * @param host The View hosting the delegate. 20936 * @param event The event to send. 20937 * 20938 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20939 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20940 */ 20941 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 20942 host.sendAccessibilityEventUncheckedInternal(event); 20943 } 20944 20945 /** 20946 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 20947 * to its children for adding their text content to the event. 20948 * <p> 20949 * The default implementation behaves as 20950 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20951 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 20952 * the case of no accessibility delegate been set. 20953 * </p> 20954 * 20955 * @param host The View hosting the delegate. 20956 * @param event The event. 20957 * @return True if the event population was completed. 20958 * 20959 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20960 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20961 */ 20962 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 20963 return host.dispatchPopulateAccessibilityEventInternal(event); 20964 } 20965 20966 /** 20967 * Gives a chance to the host View to populate the accessibility event with its 20968 * text content. 20969 * <p> 20970 * The default implementation behaves as 20971 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 20972 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 20973 * the case of no accessibility delegate been set. 20974 * </p> 20975 * 20976 * @param host The View hosting the delegate. 20977 * @param event The accessibility event which to populate. 20978 * 20979 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 20980 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 20981 */ 20982 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 20983 host.onPopulateAccessibilityEventInternal(event); 20984 } 20985 20986 /** 20987 * Initializes an {@link AccessibilityEvent} with information about the 20988 * the host View which is the event source. 20989 * <p> 20990 * The default implementation behaves as 20991 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 20992 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 20993 * the case of no accessibility delegate been set. 20994 * </p> 20995 * 20996 * @param host The View hosting the delegate. 20997 * @param event The event to initialize. 20998 * 20999 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 21000 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 21001 */ 21002 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 21003 host.onInitializeAccessibilityEventInternal(event); 21004 } 21005 21006 /** 21007 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 21008 * <p> 21009 * The default implementation behaves as 21010 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 21011 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 21012 * the case of no accessibility delegate been set. 21013 * </p> 21014 * 21015 * @param host The View hosting the delegate. 21016 * @param info The instance to initialize. 21017 * 21018 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 21019 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 21020 */ 21021 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 21022 host.onInitializeAccessibilityNodeInfoInternal(info); 21023 } 21024 21025 /** 21026 * Called when a child of the host View has requested sending an 21027 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 21028 * to augment the event. 21029 * <p> 21030 * The default implementation behaves as 21031 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 21032 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 21033 * the case of no accessibility delegate been set. 21034 * </p> 21035 * 21036 * @param host The View hosting the delegate. 21037 * @param child The child which requests sending the event. 21038 * @param event The event to be sent. 21039 * @return True if the event should be sent 21040 * 21041 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 21042 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 21043 */ 21044 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 21045 AccessibilityEvent event) { 21046 return host.onRequestSendAccessibilityEventInternal(child, event); 21047 } 21048 21049 /** 21050 * Gets the provider for managing a virtual view hierarchy rooted at this View 21051 * and reported to {@link android.accessibilityservice.AccessibilityService}s 21052 * that explore the window content. 21053 * <p> 21054 * The default implementation behaves as 21055 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 21056 * the case of no accessibility delegate been set. 21057 * </p> 21058 * 21059 * @return The provider. 21060 * 21061 * @see AccessibilityNodeProvider 21062 */ 21063 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 21064 return null; 21065 } 21066 21067 /** 21068 * Returns an {@link AccessibilityNodeInfo} representing the host view from the 21069 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 21070 * This method is responsible for obtaining an accessibility node info from a 21071 * pool of reusable instances and calling 21072 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host 21073 * view to initialize the former. 21074 * <p> 21075 * <strong>Note:</strong> The client is responsible for recycling the obtained 21076 * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object 21077 * creation. 21078 * </p> 21079 * <p> 21080 * The default implementation behaves as 21081 * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for 21082 * the case of no accessibility delegate been set. 21083 * </p> 21084 * @return A populated {@link AccessibilityNodeInfo}. 21085 * 21086 * @see AccessibilityNodeInfo 21087 * 21088 * @hide 21089 */ 21090 public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) { 21091 return host.createAccessibilityNodeInfoInternal(); 21092 } 21093 } 21094 21095 private class MatchIdPredicate implements Predicate<View> { 21096 public int mId; 21097 21098 @Override 21099 public boolean apply(View view) { 21100 return (view.mID == mId); 21101 } 21102 } 21103 21104 private class MatchLabelForPredicate implements Predicate<View> { 21105 private int mLabeledId; 21106 21107 @Override 21108 public boolean apply(View view) { 21109 return (view.mLabelForId == mLabeledId); 21110 } 21111 } 21112 21113 private class SendViewStateChangedAccessibilityEvent implements Runnable { 21114 private int mChangeTypes = 0; 21115 private boolean mPosted; 21116 private boolean mPostedWithDelay; 21117 private long mLastEventTimeMillis; 21118 21119 @Override 21120 public void run() { 21121 mPosted = false; 21122 mPostedWithDelay = false; 21123 mLastEventTimeMillis = SystemClock.uptimeMillis(); 21124 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 21125 final AccessibilityEvent event = AccessibilityEvent.obtain(); 21126 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 21127 event.setContentChangeTypes(mChangeTypes); 21128 sendAccessibilityEventUnchecked(event); 21129 } 21130 mChangeTypes = 0; 21131 } 21132 21133 public void runOrPost(int changeType) { 21134 mChangeTypes |= changeType; 21135 21136 // If this is a live region or the child of a live region, collect 21137 // all events from this frame and send them on the next frame. 21138 if (inLiveRegion()) { 21139 // If we're already posted with a delay, remove that. 21140 if (mPostedWithDelay) { 21141 removeCallbacks(this); 21142 mPostedWithDelay = false; 21143 } 21144 // Only post if we're not already posted. 21145 if (!mPosted) { 21146 post(this); 21147 mPosted = true; 21148 } 21149 return; 21150 } 21151 21152 if (mPosted) { 21153 return; 21154 } 21155 21156 final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis; 21157 final long minEventIntevalMillis = 21158 ViewConfiguration.getSendRecurringAccessibilityEventsInterval(); 21159 if (timeSinceLastMillis >= minEventIntevalMillis) { 21160 removeCallbacks(this); 21161 run(); 21162 } else { 21163 postDelayed(this, minEventIntevalMillis - timeSinceLastMillis); 21164 mPostedWithDelay = true; 21165 } 21166 } 21167 } 21168 21169 private boolean inLiveRegion() { 21170 if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) { 21171 return true; 21172 } 21173 21174 ViewParent parent = getParent(); 21175 while (parent instanceof View) { 21176 if (((View) parent).getAccessibilityLiveRegion() 21177 != View.ACCESSIBILITY_LIVE_REGION_NONE) { 21178 return true; 21179 } 21180 parent = parent.getParent(); 21181 } 21182 21183 return false; 21184 } 21185 21186 /** 21187 * Dump all private flags in readable format, useful for documentation and 21188 * sanity checking. 21189 */ 21190 private static void dumpFlags() { 21191 final HashMap<String, String> found = Maps.newHashMap(); 21192 try { 21193 for (Field field : View.class.getDeclaredFields()) { 21194 final int modifiers = field.getModifiers(); 21195 if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { 21196 if (field.getType().equals(int.class)) { 21197 final int value = field.getInt(null); 21198 dumpFlag(found, field.getName(), value); 21199 } else if (field.getType().equals(int[].class)) { 21200 final int[] values = (int[]) field.get(null); 21201 for (int i = 0; i < values.length; i++) { 21202 dumpFlag(found, field.getName() + "[" + i + "]", values[i]); 21203 } 21204 } 21205 } 21206 } 21207 } catch (IllegalAccessException e) { 21208 throw new RuntimeException(e); 21209 } 21210 21211 final ArrayList<String> keys = Lists.newArrayList(); 21212 keys.addAll(found.keySet()); 21213 Collections.sort(keys); 21214 for (String key : keys) { 21215 Log.d(VIEW_LOG_TAG, found.get(key)); 21216 } 21217 } 21218 21219 private static void dumpFlag(HashMap<String, String> found, String name, int value) { 21220 // Sort flags by prefix, then by bits, always keeping unique keys 21221 final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' '); 21222 final int prefix = name.indexOf('_'); 21223 final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name; 21224 final String output = bits + " " + name; 21225 found.put(key, output); 21226 } 21227} 21228