View.java revision d72068b38ec4e5732dde6093e39b2602babc27a3
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.text.TextUtils; 60import android.util.AttributeSet; 61import android.util.FloatProperty; 62import android.util.LayoutDirection; 63import android.util.Log; 64import android.util.LongSparseLongArray; 65import android.util.Pools.SynchronizedPool; 66import android.util.Property; 67import android.util.SparseArray; 68import android.util.SuperNotCalledException; 69import android.util.TypedValue; 70import android.view.ContextMenu.ContextMenuInfo; 71import android.view.AccessibilityIterators.TextSegmentIterator; 72import android.view.AccessibilityIterators.CharacterTextSegmentIterator; 73import android.view.AccessibilityIterators.WordTextSegmentIterator; 74import android.view.AccessibilityIterators.ParagraphTextSegmentIterator; 75import android.view.accessibility.AccessibilityEvent; 76import android.view.accessibility.AccessibilityEventSource; 77import android.view.accessibility.AccessibilityManager; 78import android.view.accessibility.AccessibilityNodeInfo; 79import android.view.accessibility.AccessibilityNodeProvider; 80import android.view.animation.Animation; 81import android.view.animation.AnimationUtils; 82import android.view.animation.Transformation; 83import android.view.inputmethod.EditorInfo; 84import android.view.inputmethod.InputConnection; 85import android.view.inputmethod.InputMethodManager; 86import android.widget.ScrollBarDrawable; 87 88import static android.os.Build.VERSION_CODES.*; 89import static java.lang.Math.max; 90 91import com.android.internal.R; 92import com.android.internal.util.Predicate; 93import com.android.internal.view.menu.MenuBuilder; 94import com.google.android.collect.Lists; 95import com.google.android.collect.Maps; 96 97import java.lang.annotation.Retention; 98import java.lang.annotation.RetentionPolicy; 99import java.lang.ref.WeakReference; 100import java.lang.reflect.Field; 101import java.lang.reflect.InvocationTargetException; 102import java.lang.reflect.Method; 103import java.lang.reflect.Modifier; 104import java.util.ArrayList; 105import java.util.Arrays; 106import java.util.Collections; 107import java.util.HashMap; 108import java.util.List; 109import java.util.Locale; 110import java.util.Map; 111import java.util.concurrent.CopyOnWriteArrayList; 112import java.util.concurrent.atomic.AtomicInteger; 113 114/** 115 * <p> 116 * This class represents the basic building block for user interface components. A View 117 * occupies a rectangular area on the screen and is responsible for drawing and 118 * event handling. View is the base class for <em>widgets</em>, which are 119 * used to create interactive UI components (buttons, text fields, etc.). The 120 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which 121 * are invisible containers that hold other Views (or other ViewGroups) and define 122 * their layout properties. 123 * </p> 124 * 125 * <div class="special reference"> 126 * <h3>Developer Guides</h3> 127 * <p>For information about using this class to develop your application's user interface, 128 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide. 129 * </div> 130 * 131 * <a name="Using"></a> 132 * <h3>Using Views</h3> 133 * <p> 134 * All of the views in a window are arranged in a single tree. You can add views 135 * either from code or by specifying a tree of views in one or more XML layout 136 * files. There are many specialized subclasses of views that act as controls or 137 * are capable of displaying text, images, or other content. 138 * </p> 139 * <p> 140 * Once you have created a tree of views, there are typically a few types of 141 * common operations you may wish to perform: 142 * <ul> 143 * <li><strong>Set properties:</strong> for example setting the text of a 144 * {@link android.widget.TextView}. The available properties and the methods 145 * that set them will vary among the different subclasses of views. Note that 146 * properties that are known at build time can be set in the XML layout 147 * files.</li> 148 * <li><strong>Set focus:</strong> The framework will handled moving focus in 149 * response to user input. To force focus to a specific view, call 150 * {@link #requestFocus}.</li> 151 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 152 * that will be notified when something interesting happens to the view. For 153 * example, all views will let you set a listener to be notified when the view 154 * gains or loses focus. You can register such a listener using 155 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}. 156 * Other view subclasses offer more specialized listeners. For example, a Button 157 * exposes a listener to notify clients when the button is clicked.</li> 158 * <li><strong>Set visibility:</strong> You can hide or show views using 159 * {@link #setVisibility(int)}.</li> 160 * </ul> 161 * </p> 162 * <p><em> 163 * Note: The Android framework is responsible for measuring, laying out and 164 * drawing views. You should not call methods that perform these actions on 165 * views yourself unless you are actually implementing a 166 * {@link android.view.ViewGroup}. 167 * </em></p> 168 * 169 * <a name="Lifecycle"></a> 170 * <h3>Implementing a Custom View</h3> 171 * 172 * <p> 173 * To implement a custom view, you will usually begin by providing overrides for 174 * some of the standard methods that the framework calls on all views. You do 175 * not need to override all of these methods. In fact, you can start by just 176 * overriding {@link #onDraw(android.graphics.Canvas)}. 177 * <table border="2" width="85%" align="center" cellpadding="5"> 178 * <thead> 179 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 180 * </thead> 181 * 182 * <tbody> 183 * <tr> 184 * <td rowspan="2">Creation</td> 185 * <td>Constructors</td> 186 * <td>There is a form of the constructor that are called when the view 187 * is created from code and a form that is called when the view is 188 * inflated from a layout file. The second form should parse and apply 189 * any attributes defined in the layout file. 190 * </td> 191 * </tr> 192 * <tr> 193 * <td><code>{@link #onFinishInflate()}</code></td> 194 * <td>Called after a view and all of its children has been inflated 195 * from XML.</td> 196 * </tr> 197 * 198 * <tr> 199 * <td rowspan="3">Layout</td> 200 * <td><code>{@link #onMeasure(int, int)}</code></td> 201 * <td>Called to determine the size requirements for this view and all 202 * of its children. 203 * </td> 204 * </tr> 205 * <tr> 206 * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td> 207 * <td>Called when this view should assign a size and position to all 208 * of its children. 209 * </td> 210 * </tr> 211 * <tr> 212 * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td> 213 * <td>Called when the size of this view has changed. 214 * </td> 215 * </tr> 216 * 217 * <tr> 218 * <td>Drawing</td> 219 * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td> 220 * <td>Called when the view should render its content. 221 * </td> 222 * </tr> 223 * 224 * <tr> 225 * <td rowspan="4">Event processing</td> 226 * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td> 227 * <td>Called when a new hardware key event occurs. 228 * </td> 229 * </tr> 230 * <tr> 231 * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td> 232 * <td>Called when a hardware key up event occurs. 233 * </td> 234 * </tr> 235 * <tr> 236 * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td> 237 * <td>Called when a trackball motion event occurs. 238 * </td> 239 * </tr> 240 * <tr> 241 * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td> 242 * <td>Called when a touch screen motion event occurs. 243 * </td> 244 * </tr> 245 * 246 * <tr> 247 * <td rowspan="2">Focus</td> 248 * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td> 249 * <td>Called when the view gains or loses focus. 250 * </td> 251 * </tr> 252 * 253 * <tr> 254 * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td> 255 * <td>Called when the window containing the view gains or loses focus. 256 * </td> 257 * </tr> 258 * 259 * <tr> 260 * <td rowspan="3">Attaching</td> 261 * <td><code>{@link #onAttachedToWindow()}</code></td> 262 * <td>Called when the view is attached to a window. 263 * </td> 264 * </tr> 265 * 266 * <tr> 267 * <td><code>{@link #onDetachedFromWindow}</code></td> 268 * <td>Called when the view is detached from its window. 269 * </td> 270 * </tr> 271 * 272 * <tr> 273 * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td> 274 * <td>Called when the visibility of the window containing the view 275 * has changed. 276 * </td> 277 * </tr> 278 * </tbody> 279 * 280 * </table> 281 * </p> 282 * 283 * <a name="IDs"></a> 284 * <h3>IDs</h3> 285 * Views may have an integer id associated with them. These ids are typically 286 * assigned in the layout XML files, and are used to find specific views within 287 * the view tree. A common pattern is to: 288 * <ul> 289 * <li>Define a Button in the layout file and assign it a unique ID. 290 * <pre> 291 * <Button 292 * android:id="@+id/my_button" 293 * android:layout_width="wrap_content" 294 * android:layout_height="wrap_content" 295 * android:text="@string/my_button_text"/> 296 * </pre></li> 297 * <li>From the onCreate method of an Activity, find the Button 298 * <pre class="prettyprint"> 299 * Button myButton = (Button) findViewById(R.id.my_button); 300 * </pre></li> 301 * </ul> 302 * <p> 303 * View IDs need not be unique throughout the tree, but it is good practice to 304 * ensure that they are at least unique within the part of the tree you are 305 * searching. 306 * </p> 307 * 308 * <a name="Position"></a> 309 * <h3>Position</h3> 310 * <p> 311 * The geometry of a view is that of a rectangle. A view has a location, 312 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 313 * two dimensions, expressed as a width and a height. The unit for location 314 * and dimensions is the pixel. 315 * </p> 316 * 317 * <p> 318 * It is possible to retrieve the location of a view by invoking the methods 319 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 320 * coordinate of the rectangle representing the view. The latter returns the 321 * top, or Y, coordinate of the rectangle representing the view. These methods 322 * both return the location of the view relative to its parent. For instance, 323 * when getLeft() returns 20, that means the view is located 20 pixels to the 324 * right of the left edge of its direct parent. 325 * </p> 326 * 327 * <p> 328 * In addition, several convenience methods are offered to avoid unnecessary 329 * computations, namely {@link #getRight()} and {@link #getBottom()}. 330 * These methods return the coordinates of the right and bottom edges of the 331 * rectangle representing the view. For instance, calling {@link #getRight()} 332 * is similar to the following computation: <code>getLeft() + getWidth()</code> 333 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 334 * </p> 335 * 336 * <a name="SizePaddingMargins"></a> 337 * <h3>Size, padding and margins</h3> 338 * <p> 339 * The size of a view is expressed with a width and a height. A view actually 340 * possess two pairs of width and height values. 341 * </p> 342 * 343 * <p> 344 * The first pair is known as <em>measured width</em> and 345 * <em>measured height</em>. These dimensions define how big a view wants to be 346 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 347 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 348 * and {@link #getMeasuredHeight()}. 349 * </p> 350 * 351 * <p> 352 * The second pair is simply known as <em>width</em> and <em>height</em>, or 353 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 354 * dimensions define the actual size of the view on screen, at drawing time and 355 * after layout. These values may, but do not have to, be different from the 356 * measured width and height. The width and height can be obtained by calling 357 * {@link #getWidth()} and {@link #getHeight()}. 358 * </p> 359 * 360 * <p> 361 * To measure its dimensions, a view takes into account its padding. The padding 362 * is expressed in pixels for the left, top, right and bottom parts of the view. 363 * Padding can be used to offset the content of the view by a specific amount of 364 * pixels. For instance, a left padding of 2 will push the view's content by 365 * 2 pixels to the right of the left edge. Padding can be set using the 366 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)} 367 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 368 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()}, 369 * {@link #getPaddingEnd()}. 370 * </p> 371 * 372 * <p> 373 * Even though a view can define a padding, it does not provide any support for 374 * margins. However, view groups provide such a support. Refer to 375 * {@link android.view.ViewGroup} and 376 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 377 * </p> 378 * 379 * <a name="Layout"></a> 380 * <h3>Layout</h3> 381 * <p> 382 * Layout is a two pass process: a measure pass and a layout pass. The measuring 383 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 384 * of the view tree. Each view pushes dimension specifications down the tree 385 * during the recursion. At the end of the measure pass, every view has stored 386 * its measurements. The second pass happens in 387 * {@link #layout(int,int,int,int)} and is also top-down. During 388 * this pass each parent is responsible for positioning all of its children 389 * using the sizes computed in the measure pass. 390 * </p> 391 * 392 * <p> 393 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 394 * {@link #getMeasuredHeight()} values must be set, along with those for all of 395 * that view's descendants. A view's measured width and measured height values 396 * must respect the constraints imposed by the view's parents. This guarantees 397 * that at the end of the measure pass, all parents accept all of their 398 * children's measurements. A parent view may call measure() more than once on 399 * its children. For example, the parent may measure each child once with 400 * unspecified dimensions to find out how big they want to be, then call 401 * measure() on them again with actual numbers if the sum of all the children's 402 * unconstrained sizes is too big or too small. 403 * </p> 404 * 405 * <p> 406 * The measure pass uses two classes to communicate dimensions. The 407 * {@link MeasureSpec} class is used by views to tell their parents how they 408 * want to be measured and positioned. The base LayoutParams class just 409 * describes how big the view wants to be for both width and height. For each 410 * dimension, it can specify one of: 411 * <ul> 412 * <li> an exact number 413 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 414 * (minus padding) 415 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 416 * enclose its content (plus padding). 417 * </ul> 418 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 419 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 420 * an X and Y value. 421 * </p> 422 * 423 * <p> 424 * MeasureSpecs are used to push requirements down the tree from parent to 425 * child. A MeasureSpec can be in one of three modes: 426 * <ul> 427 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 428 * of a child view. For example, a LinearLayout may call measure() on its child 429 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 430 * tall the child view wants to be given a width of 240 pixels. 431 * <li>EXACTLY: This is used by the parent to impose an exact size on the 432 * child. The child must use this size, and guarantee that all of its 433 * descendants will fit within this size. 434 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 435 * child. The child must guarantee that it and all of its descendants will fit 436 * within this size. 437 * </ul> 438 * </p> 439 * 440 * <p> 441 * To intiate a layout, call {@link #requestLayout}. This method is typically 442 * called by a view on itself when it believes that is can no longer fit within 443 * its current bounds. 444 * </p> 445 * 446 * <a name="Drawing"></a> 447 * <h3>Drawing</h3> 448 * <p> 449 * Drawing is handled by walking the tree and recording the drawing commands of 450 * any View that needs to update. After this, the drawing commands of the 451 * entire tree are issued to screen, clipped to the newly damaged area. 452 * </p> 453 * 454 * <p> 455 * The tree is largely recorded and drawn in order, with parents drawn before 456 * (i.e., behind) their children, with siblings drawn in the order they appear 457 * in the tree. If you set a background drawable for a View, then the View will 458 * draw it before calling back to its <code>onDraw()</code> method. The child 459 * drawing order can be overridden with 460 * {@link ViewGroup#setChildrenDrawingOrderEnabled(boolean) custom child drawing order} 461 * in a ViewGroup, and with {@link #setZ(float)} custom Z values} set on Views. 462 * </p> 463 * 464 * <p> 465 * To force a view to draw, call {@link #invalidate()}. 466 * </p> 467 * 468 * <a name="EventHandlingThreading"></a> 469 * <h3>Event Handling and Threading</h3> 470 * <p> 471 * The basic cycle of a view is as follows: 472 * <ol> 473 * <li>An event comes in and is dispatched to the appropriate view. The view 474 * handles the event and notifies any listeners.</li> 475 * <li>If in the course of processing the event, the view's bounds may need 476 * to be changed, the view will call {@link #requestLayout()}.</li> 477 * <li>Similarly, if in the course of processing the event the view's appearance 478 * may need to be changed, the view will call {@link #invalidate()}.</li> 479 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 480 * the framework will take care of measuring, laying out, and drawing the tree 481 * as appropriate.</li> 482 * </ol> 483 * </p> 484 * 485 * <p><em>Note: The entire view tree is single threaded. You must always be on 486 * the UI thread when calling any method on any view.</em> 487 * If you are doing work on other threads and want to update the state of a view 488 * from that thread, you should use a {@link Handler}. 489 * </p> 490 * 491 * <a name="FocusHandling"></a> 492 * <h3>Focus Handling</h3> 493 * <p> 494 * The framework will handle routine focus movement in response to user input. 495 * This includes changing the focus as views are removed or hidden, or as new 496 * views become available. Views indicate their willingness to take focus 497 * through the {@link #isFocusable} method. To change whether a view can take 498 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 499 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 500 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 501 * </p> 502 * <p> 503 * Focus movement is based on an algorithm which finds the nearest neighbor in a 504 * given direction. In rare cases, the default algorithm may not match the 505 * intended behavior of the developer. In these situations, you can provide 506 * explicit overrides by using these XML attributes in the layout file: 507 * <pre> 508 * nextFocusDown 509 * nextFocusLeft 510 * nextFocusRight 511 * nextFocusUp 512 * </pre> 513 * </p> 514 * 515 * 516 * <p> 517 * To get a particular view to take focus, call {@link #requestFocus()}. 518 * </p> 519 * 520 * <a name="TouchMode"></a> 521 * <h3>Touch Mode</h3> 522 * <p> 523 * When a user is navigating a user interface via directional keys such as a D-pad, it is 524 * necessary to give focus to actionable items such as buttons so the user can see 525 * what will take input. If the device has touch capabilities, however, and the user 526 * begins interacting with the interface by touching it, it is no longer necessary to 527 * always highlight, or give focus to, a particular view. This motivates a mode 528 * for interaction named 'touch mode'. 529 * </p> 530 * <p> 531 * For a touch capable device, once the user touches the screen, the device 532 * will enter touch mode. From this point onward, only views for which 533 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 534 * Other views that are touchable, like buttons, will not take focus when touched; they will 535 * only fire the on click listeners. 536 * </p> 537 * <p> 538 * Any time a user hits a directional key, such as a D-pad direction, the view device will 539 * exit touch mode, and find a view to take focus, so that the user may resume interacting 540 * with the user interface without touching the screen again. 541 * </p> 542 * <p> 543 * The touch mode state is maintained across {@link android.app.Activity}s. Call 544 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 545 * </p> 546 * 547 * <a name="Scrolling"></a> 548 * <h3>Scrolling</h3> 549 * <p> 550 * The framework provides basic support for views that wish to internally 551 * scroll their content. This includes keeping track of the X and Y scroll 552 * offset as well as mechanisms for drawing scrollbars. See 553 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 554 * {@link #awakenScrollBars()} for more details. 555 * </p> 556 * 557 * <a name="Tags"></a> 558 * <h3>Tags</h3> 559 * <p> 560 * Unlike IDs, tags are not used to identify views. Tags are essentially an 561 * extra piece of information that can be associated with a view. They are most 562 * often used as a convenience to store data related to views in the views 563 * themselves rather than by putting them in a separate structure. 564 * </p> 565 * 566 * <a name="Properties"></a> 567 * <h3>Properties</h3> 568 * <p> 569 * The View class exposes an {@link #ALPHA} property, as well as several transform-related 570 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are 571 * available both in the {@link Property} form as well as in similarly-named setter/getter 572 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can 573 * be used to set persistent state associated with these rendering-related properties on the view. 574 * The properties and methods can also be used in conjunction with 575 * {@link android.animation.Animator Animator}-based animations, described more in the 576 * <a href="#Animation">Animation</a> section. 577 * </p> 578 * 579 * <a name="Animation"></a> 580 * <h3>Animation</h3> 581 * <p> 582 * Starting with Android 3.0, the preferred way of animating views is to use the 583 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based 584 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and 585 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0 586 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only 587 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class 588 * makes animating these View properties particularly easy and efficient. 589 * </p> 590 * <p> 591 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered. 592 * You can attach an {@link Animation} object to a view using 593 * {@link #setAnimation(Animation)} or 594 * {@link #startAnimation(Animation)}. The animation can alter the scale, 595 * rotation, translation and alpha of a view over time. If the animation is 596 * attached to a view that has children, the animation will affect the entire 597 * subtree rooted by that node. When an animation is started, the framework will 598 * take care of redrawing the appropriate views until the animation completes. 599 * </p> 600 * 601 * <a name="Security"></a> 602 * <h3>Security</h3> 603 * <p> 604 * Sometimes it is essential that an application be able to verify that an action 605 * is being performed with the full knowledge and consent of the user, such as 606 * granting a permission request, making a purchase or clicking on an advertisement. 607 * Unfortunately, a malicious application could try to spoof the user into 608 * performing these actions, unaware, by concealing the intended purpose of the view. 609 * As a remedy, the framework offers a touch filtering mechanism that can be used to 610 * improve the security of views that provide access to sensitive functionality. 611 * </p><p> 612 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 613 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 614 * will discard touches that are received whenever the view's window is obscured by 615 * another visible window. As a result, the view will not receive touches whenever a 616 * toast, dialog or other window appears above the view's window. 617 * </p><p> 618 * For more fine-grained control over security, consider overriding the 619 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 620 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 621 * </p> 622 * 623 * @attr ref android.R.styleable#View_alpha 624 * @attr ref android.R.styleable#View_background 625 * @attr ref android.R.styleable#View_clickable 626 * @attr ref android.R.styleable#View_contentDescription 627 * @attr ref android.R.styleable#View_drawingCacheQuality 628 * @attr ref android.R.styleable#View_duplicateParentState 629 * @attr ref android.R.styleable#View_id 630 * @attr ref android.R.styleable#View_requiresFadingEdge 631 * @attr ref android.R.styleable#View_fadeScrollbars 632 * @attr ref android.R.styleable#View_fadingEdgeLength 633 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 634 * @attr ref android.R.styleable#View_fitsSystemWindows 635 * @attr ref android.R.styleable#View_isScrollContainer 636 * @attr ref android.R.styleable#View_focusable 637 * @attr ref android.R.styleable#View_focusableInTouchMode 638 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 639 * @attr ref android.R.styleable#View_keepScreenOn 640 * @attr ref android.R.styleable#View_layerType 641 * @attr ref android.R.styleable#View_layoutDirection 642 * @attr ref android.R.styleable#View_longClickable 643 * @attr ref android.R.styleable#View_minHeight 644 * @attr ref android.R.styleable#View_minWidth 645 * @attr ref android.R.styleable#View_nextFocusDown 646 * @attr ref android.R.styleable#View_nextFocusLeft 647 * @attr ref android.R.styleable#View_nextFocusRight 648 * @attr ref android.R.styleable#View_nextFocusUp 649 * @attr ref android.R.styleable#View_onClick 650 * @attr ref android.R.styleable#View_padding 651 * @attr ref android.R.styleable#View_paddingBottom 652 * @attr ref android.R.styleable#View_paddingLeft 653 * @attr ref android.R.styleable#View_paddingRight 654 * @attr ref android.R.styleable#View_paddingTop 655 * @attr ref android.R.styleable#View_paddingStart 656 * @attr ref android.R.styleable#View_paddingEnd 657 * @attr ref android.R.styleable#View_saveEnabled 658 * @attr ref android.R.styleable#View_rotation 659 * @attr ref android.R.styleable#View_rotationX 660 * @attr ref android.R.styleable#View_rotationY 661 * @attr ref android.R.styleable#View_scaleX 662 * @attr ref android.R.styleable#View_scaleY 663 * @attr ref android.R.styleable#View_scrollX 664 * @attr ref android.R.styleable#View_scrollY 665 * @attr ref android.R.styleable#View_scrollbarSize 666 * @attr ref android.R.styleable#View_scrollbarStyle 667 * @attr ref android.R.styleable#View_scrollbars 668 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 669 * @attr ref android.R.styleable#View_scrollbarFadeDuration 670 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 671 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 672 * @attr ref android.R.styleable#View_scrollbarThumbVertical 673 * @attr ref android.R.styleable#View_scrollbarTrackVertical 674 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 675 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 676 * @attr ref android.R.styleable#View_stateListAnimator 677 * @attr ref android.R.styleable#View_transitionName 678 * @attr ref android.R.styleable#View_soundEffectsEnabled 679 * @attr ref android.R.styleable#View_tag 680 * @attr ref android.R.styleable#View_textAlignment 681 * @attr ref android.R.styleable#View_textDirection 682 * @attr ref android.R.styleable#View_transformPivotX 683 * @attr ref android.R.styleable#View_transformPivotY 684 * @attr ref android.R.styleable#View_translationX 685 * @attr ref android.R.styleable#View_translationY 686 * @attr ref android.R.styleable#View_translationZ 687 * @attr ref android.R.styleable#View_visibility 688 * 689 * @see android.view.ViewGroup 690 */ 691public class View implements Drawable.Callback, KeyEvent.Callback, 692 AccessibilityEventSource { 693 private static final boolean DBG = false; 694 695 /** 696 * The logging tag used by this class with android.util.Log. 697 */ 698 protected static final String VIEW_LOG_TAG = "View"; 699 700 /** 701 * When set to true, apps will draw debugging information about their layouts. 702 * 703 * @hide 704 */ 705 public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout"; 706 707 /** 708 * When set to true, this view will save its attribute data. 709 * 710 * @hide 711 */ 712 public static boolean mDebugViewAttributes = false; 713 714 /** 715 * Used to mark a View that has no ID. 716 */ 717 public static final int NO_ID = -1; 718 719 /** 720 * Signals that compatibility booleans have been initialized according to 721 * target SDK versions. 722 */ 723 private static boolean sCompatibilityDone = false; 724 725 /** 726 * Use the old (broken) way of building MeasureSpecs. 727 */ 728 private static boolean sUseBrokenMakeMeasureSpec = false; 729 730 /** 731 * Ignore any optimizations using the measure cache. 732 */ 733 private static boolean sIgnoreMeasureCache = false; 734 735 /** 736 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 737 * calling setFlags. 738 */ 739 private static final int NOT_FOCUSABLE = 0x00000000; 740 741 /** 742 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 743 * setFlags. 744 */ 745 private static final int FOCUSABLE = 0x00000001; 746 747 /** 748 * Mask for use with setFlags indicating bits used for focus. 749 */ 750 private static final int FOCUSABLE_MASK = 0x00000001; 751 752 /** 753 * This view will adjust its padding to fit sytem windows (e.g. status bar) 754 */ 755 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 756 757 /** @hide */ 758 @IntDef({VISIBLE, INVISIBLE, GONE}) 759 @Retention(RetentionPolicy.SOURCE) 760 public @interface Visibility {} 761 762 /** 763 * This view is visible. 764 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 765 * android:visibility}. 766 */ 767 public static final int VISIBLE = 0x00000000; 768 769 /** 770 * This view is invisible, but it still takes up space for layout purposes. 771 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 772 * android:visibility}. 773 */ 774 public static final int INVISIBLE = 0x00000004; 775 776 /** 777 * This view is invisible, and it doesn't take any space for layout 778 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 779 * android:visibility}. 780 */ 781 public static final int GONE = 0x00000008; 782 783 /** 784 * Mask for use with setFlags indicating bits used for visibility. 785 * {@hide} 786 */ 787 static final int VISIBILITY_MASK = 0x0000000C; 788 789 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 790 791 /** 792 * This view is enabled. Interpretation varies by subclass. 793 * Use with ENABLED_MASK when calling setFlags. 794 * {@hide} 795 */ 796 static final int ENABLED = 0x00000000; 797 798 /** 799 * This view is disabled. Interpretation varies by subclass. 800 * Use with ENABLED_MASK when calling setFlags. 801 * {@hide} 802 */ 803 static final int DISABLED = 0x00000020; 804 805 /** 806 * Mask for use with setFlags indicating bits used for indicating whether 807 * this view is enabled 808 * {@hide} 809 */ 810 static final int ENABLED_MASK = 0x00000020; 811 812 /** 813 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 814 * called and further optimizations will be performed. It is okay to have 815 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 816 * {@hide} 817 */ 818 static final int WILL_NOT_DRAW = 0x00000080; 819 820 /** 821 * Mask for use with setFlags indicating bits used for indicating whether 822 * this view is will draw 823 * {@hide} 824 */ 825 static final int DRAW_MASK = 0x00000080; 826 827 /** 828 * <p>This view doesn't show scrollbars.</p> 829 * {@hide} 830 */ 831 static final int SCROLLBARS_NONE = 0x00000000; 832 833 /** 834 * <p>This view shows horizontal scrollbars.</p> 835 * {@hide} 836 */ 837 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 838 839 /** 840 * <p>This view shows vertical scrollbars.</p> 841 * {@hide} 842 */ 843 static final int SCROLLBARS_VERTICAL = 0x00000200; 844 845 /** 846 * <p>Mask for use with setFlags indicating bits used for indicating which 847 * scrollbars are enabled.</p> 848 * {@hide} 849 */ 850 static final int SCROLLBARS_MASK = 0x00000300; 851 852 /** 853 * Indicates that the view should filter touches when its window is obscured. 854 * Refer to the class comments for more information about this security feature. 855 * {@hide} 856 */ 857 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 858 859 /** 860 * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate 861 * that they are optional and should be skipped if the window has 862 * requested system UI flags that ignore those insets for layout. 863 */ 864 static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800; 865 866 /** 867 * <p>This view doesn't show fading edges.</p> 868 * {@hide} 869 */ 870 static final int FADING_EDGE_NONE = 0x00000000; 871 872 /** 873 * <p>This view shows horizontal fading edges.</p> 874 * {@hide} 875 */ 876 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 877 878 /** 879 * <p>This view shows vertical fading edges.</p> 880 * {@hide} 881 */ 882 static final int FADING_EDGE_VERTICAL = 0x00002000; 883 884 /** 885 * <p>Mask for use with setFlags indicating bits used for indicating which 886 * fading edges are enabled.</p> 887 * {@hide} 888 */ 889 static final int FADING_EDGE_MASK = 0x00003000; 890 891 /** 892 * <p>Indicates this view can be clicked. When clickable, a View reacts 893 * to clicks by notifying the OnClickListener.<p> 894 * {@hide} 895 */ 896 static final int CLICKABLE = 0x00004000; 897 898 /** 899 * <p>Indicates this view is caching its drawing into a bitmap.</p> 900 * {@hide} 901 */ 902 static final int DRAWING_CACHE_ENABLED = 0x00008000; 903 904 /** 905 * <p>Indicates that no icicle should be saved for this view.<p> 906 * {@hide} 907 */ 908 static final int SAVE_DISABLED = 0x000010000; 909 910 /** 911 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 912 * property.</p> 913 * {@hide} 914 */ 915 static final int SAVE_DISABLED_MASK = 0x000010000; 916 917 /** 918 * <p>Indicates that no drawing cache should ever be created for this view.<p> 919 * {@hide} 920 */ 921 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 922 923 /** 924 * <p>Indicates this view can take / keep focus when int touch mode.</p> 925 * {@hide} 926 */ 927 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 928 929 /** @hide */ 930 @Retention(RetentionPolicy.SOURCE) 931 @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO}) 932 public @interface DrawingCacheQuality {} 933 934 /** 935 * <p>Enables low quality mode for the drawing cache.</p> 936 */ 937 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 938 939 /** 940 * <p>Enables high quality mode for the drawing cache.</p> 941 */ 942 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 943 944 /** 945 * <p>Enables automatic quality mode for the drawing cache.</p> 946 */ 947 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 948 949 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 950 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 951 }; 952 953 /** 954 * <p>Mask for use with setFlags indicating bits used for the cache 955 * quality property.</p> 956 * {@hide} 957 */ 958 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 959 960 /** 961 * <p> 962 * Indicates this view can be long clicked. When long clickable, a View 963 * reacts to long clicks by notifying the OnLongClickListener or showing a 964 * context menu. 965 * </p> 966 * {@hide} 967 */ 968 static final int LONG_CLICKABLE = 0x00200000; 969 970 /** 971 * <p>Indicates that this view gets its drawable states from its direct parent 972 * and ignores its original internal states.</p> 973 * 974 * @hide 975 */ 976 static final int DUPLICATE_PARENT_STATE = 0x00400000; 977 978 /** @hide */ 979 @IntDef({ 980 SCROLLBARS_INSIDE_OVERLAY, 981 SCROLLBARS_INSIDE_INSET, 982 SCROLLBARS_OUTSIDE_OVERLAY, 983 SCROLLBARS_OUTSIDE_INSET 984 }) 985 @Retention(RetentionPolicy.SOURCE) 986 public @interface ScrollBarStyle {} 987 988 /** 989 * The scrollbar style to display the scrollbars inside the content area, 990 * without increasing the padding. The scrollbars will be overlaid with 991 * translucency on the view's content. 992 */ 993 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 994 995 /** 996 * The scrollbar style to display the scrollbars inside the padded area, 997 * increasing the padding of the view. The scrollbars will not overlap the 998 * content area of the view. 999 */ 1000 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 1001 1002 /** 1003 * The scrollbar style to display the scrollbars at the edge of the view, 1004 * without increasing the padding. The scrollbars will be overlaid with 1005 * translucency. 1006 */ 1007 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 1008 1009 /** 1010 * The scrollbar style to display the scrollbars at the edge of the view, 1011 * increasing the padding of the view. The scrollbars will only overlap the 1012 * background, if any. 1013 */ 1014 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 1015 1016 /** 1017 * Mask to check if the scrollbar style is overlay or inset. 1018 * {@hide} 1019 */ 1020 static final int SCROLLBARS_INSET_MASK = 0x01000000; 1021 1022 /** 1023 * Mask to check if the scrollbar style is inside or outside. 1024 * {@hide} 1025 */ 1026 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 1027 1028 /** 1029 * Mask for scrollbar style. 1030 * {@hide} 1031 */ 1032 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 1033 1034 /** 1035 * View flag indicating that the screen should remain on while the 1036 * window containing this view is visible to the user. This effectively 1037 * takes care of automatically setting the WindowManager's 1038 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 1039 */ 1040 public static final int KEEP_SCREEN_ON = 0x04000000; 1041 1042 /** 1043 * View flag indicating whether this view should have sound effects enabled 1044 * for events such as clicking and touching. 1045 */ 1046 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 1047 1048 /** 1049 * View flag indicating whether this view should have haptic feedback 1050 * enabled for events such as long presses. 1051 */ 1052 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 1053 1054 /** 1055 * <p>Indicates that the view hierarchy should stop saving state when 1056 * it reaches this view. If state saving is initiated immediately at 1057 * the view, it will be allowed. 1058 * {@hide} 1059 */ 1060 static final int PARENT_SAVE_DISABLED = 0x20000000; 1061 1062 /** 1063 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 1064 * {@hide} 1065 */ 1066 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 1067 1068 /** @hide */ 1069 @IntDef(flag = true, 1070 value = { 1071 FOCUSABLES_ALL, 1072 FOCUSABLES_TOUCH_MODE 1073 }) 1074 @Retention(RetentionPolicy.SOURCE) 1075 public @interface FocusableMode {} 1076 1077 /** 1078 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1079 * should add all focusable Views regardless if they are focusable in touch mode. 1080 */ 1081 public static final int FOCUSABLES_ALL = 0x00000000; 1082 1083 /** 1084 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1085 * should add only Views focusable in touch mode. 1086 */ 1087 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 1088 1089 /** @hide */ 1090 @IntDef({ 1091 FOCUS_BACKWARD, 1092 FOCUS_FORWARD, 1093 FOCUS_LEFT, 1094 FOCUS_UP, 1095 FOCUS_RIGHT, 1096 FOCUS_DOWN 1097 }) 1098 @Retention(RetentionPolicy.SOURCE) 1099 public @interface FocusDirection {} 1100 1101 /** @hide */ 1102 @IntDef({ 1103 FOCUS_LEFT, 1104 FOCUS_UP, 1105 FOCUS_RIGHT, 1106 FOCUS_DOWN 1107 }) 1108 @Retention(RetentionPolicy.SOURCE) 1109 public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward 1110 1111 /** 1112 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 1113 * item. 1114 */ 1115 public static final int FOCUS_BACKWARD = 0x00000001; 1116 1117 /** 1118 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 1119 * item. 1120 */ 1121 public static final int FOCUS_FORWARD = 0x00000002; 1122 1123 /** 1124 * Use with {@link #focusSearch(int)}. Move focus to the left. 1125 */ 1126 public static final int FOCUS_LEFT = 0x00000011; 1127 1128 /** 1129 * Use with {@link #focusSearch(int)}. Move focus up. 1130 */ 1131 public static final int FOCUS_UP = 0x00000021; 1132 1133 /** 1134 * Use with {@link #focusSearch(int)}. Move focus to the right. 1135 */ 1136 public static final int FOCUS_RIGHT = 0x00000042; 1137 1138 /** 1139 * Use with {@link #focusSearch(int)}. Move focus down. 1140 */ 1141 public static final int FOCUS_DOWN = 0x00000082; 1142 1143 /** 1144 * Bits of {@link #getMeasuredWidthAndState()} and 1145 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1146 */ 1147 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1148 1149 /** 1150 * Bits of {@link #getMeasuredWidthAndState()} and 1151 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1152 */ 1153 public static final int MEASURED_STATE_MASK = 0xff000000; 1154 1155 /** 1156 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1157 * for functions that combine both width and height into a single int, 1158 * such as {@link #getMeasuredState()} and the childState argument of 1159 * {@link #resolveSizeAndState(int, int, int)}. 1160 */ 1161 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1162 1163 /** 1164 * Bit of {@link #getMeasuredWidthAndState()} and 1165 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1166 * is smaller that the space the view would like to have. 1167 */ 1168 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1169 1170 /** 1171 * Base View state sets 1172 */ 1173 // Singles 1174 /** 1175 * Indicates the view has no states set. States are used with 1176 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1177 * view depending on its state. 1178 * 1179 * @see android.graphics.drawable.Drawable 1180 * @see #getDrawableState() 1181 */ 1182 protected static final int[] EMPTY_STATE_SET; 1183 /** 1184 * Indicates the view is enabled. States are used with 1185 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1186 * view depending on its state. 1187 * 1188 * @see android.graphics.drawable.Drawable 1189 * @see #getDrawableState() 1190 */ 1191 protected static final int[] ENABLED_STATE_SET; 1192 /** 1193 * Indicates the view is focused. States are used with 1194 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1195 * view depending on its state. 1196 * 1197 * @see android.graphics.drawable.Drawable 1198 * @see #getDrawableState() 1199 */ 1200 protected static final int[] FOCUSED_STATE_SET; 1201 /** 1202 * Indicates the view is selected. States are used with 1203 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1204 * view depending on its state. 1205 * 1206 * @see android.graphics.drawable.Drawable 1207 * @see #getDrawableState() 1208 */ 1209 protected static final int[] SELECTED_STATE_SET; 1210 /** 1211 * Indicates the view is pressed. States are used with 1212 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1213 * view depending on its state. 1214 * 1215 * @see android.graphics.drawable.Drawable 1216 * @see #getDrawableState() 1217 */ 1218 protected static final int[] PRESSED_STATE_SET; 1219 /** 1220 * Indicates the view's window has focus. States are used with 1221 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1222 * view depending on its state. 1223 * 1224 * @see android.graphics.drawable.Drawable 1225 * @see #getDrawableState() 1226 */ 1227 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1228 // Doubles 1229 /** 1230 * Indicates the view is enabled and has the focus. 1231 * 1232 * @see #ENABLED_STATE_SET 1233 * @see #FOCUSED_STATE_SET 1234 */ 1235 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1236 /** 1237 * Indicates the view is enabled and selected. 1238 * 1239 * @see #ENABLED_STATE_SET 1240 * @see #SELECTED_STATE_SET 1241 */ 1242 protected static final int[] ENABLED_SELECTED_STATE_SET; 1243 /** 1244 * Indicates the view is enabled and that its window has focus. 1245 * 1246 * @see #ENABLED_STATE_SET 1247 * @see #WINDOW_FOCUSED_STATE_SET 1248 */ 1249 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1250 /** 1251 * Indicates the view is focused and selected. 1252 * 1253 * @see #FOCUSED_STATE_SET 1254 * @see #SELECTED_STATE_SET 1255 */ 1256 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1257 /** 1258 * Indicates the view has the focus and that its window has the focus. 1259 * 1260 * @see #FOCUSED_STATE_SET 1261 * @see #WINDOW_FOCUSED_STATE_SET 1262 */ 1263 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1264 /** 1265 * Indicates the view is selected and that its window has the focus. 1266 * 1267 * @see #SELECTED_STATE_SET 1268 * @see #WINDOW_FOCUSED_STATE_SET 1269 */ 1270 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1271 // Triples 1272 /** 1273 * Indicates the view is enabled, focused and selected. 1274 * 1275 * @see #ENABLED_STATE_SET 1276 * @see #FOCUSED_STATE_SET 1277 * @see #SELECTED_STATE_SET 1278 */ 1279 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1280 /** 1281 * Indicates the view is enabled, focused and its window has the focus. 1282 * 1283 * @see #ENABLED_STATE_SET 1284 * @see #FOCUSED_STATE_SET 1285 * @see #WINDOW_FOCUSED_STATE_SET 1286 */ 1287 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1288 /** 1289 * Indicates the view is enabled, selected and its window has the focus. 1290 * 1291 * @see #ENABLED_STATE_SET 1292 * @see #SELECTED_STATE_SET 1293 * @see #WINDOW_FOCUSED_STATE_SET 1294 */ 1295 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1296 /** 1297 * Indicates the view is focused, selected and its window has the focus. 1298 * 1299 * @see #FOCUSED_STATE_SET 1300 * @see #SELECTED_STATE_SET 1301 * @see #WINDOW_FOCUSED_STATE_SET 1302 */ 1303 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1304 /** 1305 * Indicates the view is enabled, focused, selected and its window 1306 * has the focus. 1307 * 1308 * @see #ENABLED_STATE_SET 1309 * @see #FOCUSED_STATE_SET 1310 * @see #SELECTED_STATE_SET 1311 * @see #WINDOW_FOCUSED_STATE_SET 1312 */ 1313 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1314 /** 1315 * Indicates the view is pressed and its window has the focus. 1316 * 1317 * @see #PRESSED_STATE_SET 1318 * @see #WINDOW_FOCUSED_STATE_SET 1319 */ 1320 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1321 /** 1322 * Indicates the view is pressed and selected. 1323 * 1324 * @see #PRESSED_STATE_SET 1325 * @see #SELECTED_STATE_SET 1326 */ 1327 protected static final int[] PRESSED_SELECTED_STATE_SET; 1328 /** 1329 * Indicates the view is pressed, selected and its window has the focus. 1330 * 1331 * @see #PRESSED_STATE_SET 1332 * @see #SELECTED_STATE_SET 1333 * @see #WINDOW_FOCUSED_STATE_SET 1334 */ 1335 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1336 /** 1337 * Indicates the view is pressed and focused. 1338 * 1339 * @see #PRESSED_STATE_SET 1340 * @see #FOCUSED_STATE_SET 1341 */ 1342 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1343 /** 1344 * Indicates the view is pressed, focused and its window has the focus. 1345 * 1346 * @see #PRESSED_STATE_SET 1347 * @see #FOCUSED_STATE_SET 1348 * @see #WINDOW_FOCUSED_STATE_SET 1349 */ 1350 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1351 /** 1352 * Indicates the view is pressed, focused and selected. 1353 * 1354 * @see #PRESSED_STATE_SET 1355 * @see #SELECTED_STATE_SET 1356 * @see #FOCUSED_STATE_SET 1357 */ 1358 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1359 /** 1360 * Indicates the view is pressed, focused, selected and its window has the focus. 1361 * 1362 * @see #PRESSED_STATE_SET 1363 * @see #FOCUSED_STATE_SET 1364 * @see #SELECTED_STATE_SET 1365 * @see #WINDOW_FOCUSED_STATE_SET 1366 */ 1367 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1368 /** 1369 * Indicates the view is pressed and enabled. 1370 * 1371 * @see #PRESSED_STATE_SET 1372 * @see #ENABLED_STATE_SET 1373 */ 1374 protected static final int[] PRESSED_ENABLED_STATE_SET; 1375 /** 1376 * Indicates the view is pressed, enabled and its window has the focus. 1377 * 1378 * @see #PRESSED_STATE_SET 1379 * @see #ENABLED_STATE_SET 1380 * @see #WINDOW_FOCUSED_STATE_SET 1381 */ 1382 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1383 /** 1384 * Indicates the view is pressed, enabled and selected. 1385 * 1386 * @see #PRESSED_STATE_SET 1387 * @see #ENABLED_STATE_SET 1388 * @see #SELECTED_STATE_SET 1389 */ 1390 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1391 /** 1392 * Indicates the view is pressed, enabled, selected and its window has the 1393 * focus. 1394 * 1395 * @see #PRESSED_STATE_SET 1396 * @see #ENABLED_STATE_SET 1397 * @see #SELECTED_STATE_SET 1398 * @see #WINDOW_FOCUSED_STATE_SET 1399 */ 1400 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1401 /** 1402 * Indicates the view is pressed, enabled and focused. 1403 * 1404 * @see #PRESSED_STATE_SET 1405 * @see #ENABLED_STATE_SET 1406 * @see #FOCUSED_STATE_SET 1407 */ 1408 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1409 /** 1410 * Indicates the view is pressed, enabled, focused and its window has the 1411 * focus. 1412 * 1413 * @see #PRESSED_STATE_SET 1414 * @see #ENABLED_STATE_SET 1415 * @see #FOCUSED_STATE_SET 1416 * @see #WINDOW_FOCUSED_STATE_SET 1417 */ 1418 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1419 /** 1420 * Indicates the view is pressed, enabled, focused and selected. 1421 * 1422 * @see #PRESSED_STATE_SET 1423 * @see #ENABLED_STATE_SET 1424 * @see #SELECTED_STATE_SET 1425 * @see #FOCUSED_STATE_SET 1426 */ 1427 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1428 /** 1429 * Indicates the view is pressed, enabled, focused, selected and its window 1430 * has the focus. 1431 * 1432 * @see #PRESSED_STATE_SET 1433 * @see #ENABLED_STATE_SET 1434 * @see #SELECTED_STATE_SET 1435 * @see #FOCUSED_STATE_SET 1436 * @see #WINDOW_FOCUSED_STATE_SET 1437 */ 1438 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1439 1440 /** 1441 * The order here is very important to {@link #getDrawableState()} 1442 */ 1443 private static final int[][] VIEW_STATE_SETS; 1444 1445 static final int VIEW_STATE_WINDOW_FOCUSED = 1; 1446 static final int VIEW_STATE_SELECTED = 1 << 1; 1447 static final int VIEW_STATE_FOCUSED = 1 << 2; 1448 static final int VIEW_STATE_ENABLED = 1 << 3; 1449 static final int VIEW_STATE_PRESSED = 1 << 4; 1450 static final int VIEW_STATE_ACTIVATED = 1 << 5; 1451 static final int VIEW_STATE_ACCELERATED = 1 << 6; 1452 static final int VIEW_STATE_HOVERED = 1 << 7; 1453 static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8; 1454 static final int VIEW_STATE_DRAG_HOVERED = 1 << 9; 1455 1456 static final int[] VIEW_STATE_IDS = new int[] { 1457 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED, 1458 R.attr.state_selected, VIEW_STATE_SELECTED, 1459 R.attr.state_focused, VIEW_STATE_FOCUSED, 1460 R.attr.state_enabled, VIEW_STATE_ENABLED, 1461 R.attr.state_pressed, VIEW_STATE_PRESSED, 1462 R.attr.state_activated, VIEW_STATE_ACTIVATED, 1463 R.attr.state_accelerated, VIEW_STATE_ACCELERATED, 1464 R.attr.state_hovered, VIEW_STATE_HOVERED, 1465 R.attr.state_drag_can_accept, VIEW_STATE_DRAG_CAN_ACCEPT, 1466 R.attr.state_drag_hovered, VIEW_STATE_DRAG_HOVERED 1467 }; 1468 1469 static { 1470 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) { 1471 throw new IllegalStateException( 1472 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array"); 1473 } 1474 int[] orderedIds = new int[VIEW_STATE_IDS.length]; 1475 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) { 1476 int viewState = R.styleable.ViewDrawableStates[i]; 1477 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) { 1478 if (VIEW_STATE_IDS[j] == viewState) { 1479 orderedIds[i * 2] = viewState; 1480 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1]; 1481 } 1482 } 1483 } 1484 final int NUM_BITS = VIEW_STATE_IDS.length / 2; 1485 VIEW_STATE_SETS = new int[1 << NUM_BITS][]; 1486 for (int i = 0; i < VIEW_STATE_SETS.length; i++) { 1487 int numBits = Integer.bitCount(i); 1488 int[] set = new int[numBits]; 1489 int pos = 0; 1490 for (int j = 0; j < orderedIds.length; j += 2) { 1491 if ((i & orderedIds[j+1]) != 0) { 1492 set[pos++] = orderedIds[j]; 1493 } 1494 } 1495 VIEW_STATE_SETS[i] = set; 1496 } 1497 1498 EMPTY_STATE_SET = VIEW_STATE_SETS[0]; 1499 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED]; 1500 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED]; 1501 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1502 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED]; 1503 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED]; 1504 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1505 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED]; 1506 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1507 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED]; 1508 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1509 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1510 | VIEW_STATE_FOCUSED]; 1511 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED]; 1512 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1513 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED]; 1514 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1515 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED]; 1516 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1517 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1518 | VIEW_STATE_ENABLED]; 1519 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1520 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED]; 1521 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1522 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1523 | VIEW_STATE_ENABLED]; 1524 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1525 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1526 | VIEW_STATE_ENABLED]; 1527 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1528 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1529 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED]; 1530 1531 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED]; 1532 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1533 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED]; 1534 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1535 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED]; 1536 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1537 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1538 | VIEW_STATE_PRESSED]; 1539 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1540 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1541 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1542 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1543 | VIEW_STATE_PRESSED]; 1544 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1545 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1546 | VIEW_STATE_PRESSED]; 1547 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1548 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1549 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1550 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[ 1551 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1552 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1553 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED 1554 | VIEW_STATE_PRESSED]; 1555 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1556 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED 1557 | VIEW_STATE_PRESSED]; 1558 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1559 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1560 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1561 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1562 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED 1563 | VIEW_STATE_PRESSED]; 1564 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1565 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1566 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1567 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1568 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1569 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1570 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1571 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1572 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED 1573 | VIEW_STATE_PRESSED]; 1574 } 1575 1576 /** 1577 * Accessibility event types that are dispatched for text population. 1578 */ 1579 private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES = 1580 AccessibilityEvent.TYPE_VIEW_CLICKED 1581 | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED 1582 | AccessibilityEvent.TYPE_VIEW_SELECTED 1583 | AccessibilityEvent.TYPE_VIEW_FOCUSED 1584 | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED 1585 | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER 1586 | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT 1587 | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED 1588 | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED 1589 | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED 1590 | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY; 1591 1592 /** 1593 * Temporary Rect currently for use in setBackground(). This will probably 1594 * be extended in the future to hold our own class with more than just 1595 * a Rect. :) 1596 */ 1597 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1598 1599 /** 1600 * Map used to store views' tags. 1601 */ 1602 private SparseArray<Object> mKeyedTags; 1603 1604 /** 1605 * The next available accessibility id. 1606 */ 1607 private static int sNextAccessibilityViewId; 1608 1609 /** 1610 * The animation currently associated with this view. 1611 * @hide 1612 */ 1613 protected Animation mCurrentAnimation = null; 1614 1615 /** 1616 * Width as measured during measure pass. 1617 * {@hide} 1618 */ 1619 @ViewDebug.ExportedProperty(category = "measurement") 1620 int mMeasuredWidth; 1621 1622 /** 1623 * Height as measured during measure pass. 1624 * {@hide} 1625 */ 1626 @ViewDebug.ExportedProperty(category = "measurement") 1627 int mMeasuredHeight; 1628 1629 /** 1630 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1631 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1632 * its display list. This flag, used only when hw accelerated, allows us to clear the 1633 * flag while retaining this information until it's needed (at getDisplayList() time and 1634 * in drawChild(), when we decide to draw a view's children's display lists into our own). 1635 * 1636 * {@hide} 1637 */ 1638 boolean mRecreateDisplayList = false; 1639 1640 /** 1641 * The view's identifier. 1642 * {@hide} 1643 * 1644 * @see #setId(int) 1645 * @see #getId() 1646 */ 1647 @ViewDebug.ExportedProperty(resolveId = true) 1648 int mID = NO_ID; 1649 1650 /** 1651 * The stable ID of this view for accessibility purposes. 1652 */ 1653 int mAccessibilityViewId = NO_ID; 1654 1655 private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 1656 1657 SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent; 1658 1659 /** 1660 * The view's tag. 1661 * {@hide} 1662 * 1663 * @see #setTag(Object) 1664 * @see #getTag() 1665 */ 1666 protected Object mTag = null; 1667 1668 // for mPrivateFlags: 1669 /** {@hide} */ 1670 static final int PFLAG_WANTS_FOCUS = 0x00000001; 1671 /** {@hide} */ 1672 static final int PFLAG_FOCUSED = 0x00000002; 1673 /** {@hide} */ 1674 static final int PFLAG_SELECTED = 0x00000004; 1675 /** {@hide} */ 1676 static final int PFLAG_IS_ROOT_NAMESPACE = 0x00000008; 1677 /** {@hide} */ 1678 static final int PFLAG_HAS_BOUNDS = 0x00000010; 1679 /** {@hide} */ 1680 static final int PFLAG_DRAWN = 0x00000020; 1681 /** 1682 * When this flag is set, this view is running an animation on behalf of its 1683 * children and should therefore not cancel invalidate requests, even if they 1684 * lie outside of this view's bounds. 1685 * 1686 * {@hide} 1687 */ 1688 static final int PFLAG_DRAW_ANIMATION = 0x00000040; 1689 /** {@hide} */ 1690 static final int PFLAG_SKIP_DRAW = 0x00000080; 1691 /** {@hide} */ 1692 static final int PFLAG_ONLY_DRAWS_BACKGROUND = 0x00000100; 1693 /** {@hide} */ 1694 static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1695 /** {@hide} */ 1696 static final int PFLAG_DRAWABLE_STATE_DIRTY = 0x00000400; 1697 /** {@hide} */ 1698 static final int PFLAG_MEASURED_DIMENSION_SET = 0x00000800; 1699 /** {@hide} */ 1700 static final int PFLAG_FORCE_LAYOUT = 0x00001000; 1701 /** {@hide} */ 1702 static final int PFLAG_LAYOUT_REQUIRED = 0x00002000; 1703 1704 private static final int PFLAG_PRESSED = 0x00004000; 1705 1706 /** {@hide} */ 1707 static final int PFLAG_DRAWING_CACHE_VALID = 0x00008000; 1708 /** 1709 * Flag used to indicate that this view should be drawn once more (and only once 1710 * more) after its animation has completed. 1711 * {@hide} 1712 */ 1713 static final int PFLAG_ANIMATION_STARTED = 0x00010000; 1714 1715 private static final int PFLAG_SAVE_STATE_CALLED = 0x00020000; 1716 1717 /** 1718 * Indicates that the View returned true when onSetAlpha() was called and that 1719 * the alpha must be restored. 1720 * {@hide} 1721 */ 1722 static final int PFLAG_ALPHA_SET = 0x00040000; 1723 1724 /** 1725 * Set by {@link #setScrollContainer(boolean)}. 1726 */ 1727 static final int PFLAG_SCROLL_CONTAINER = 0x00080000; 1728 1729 /** 1730 * Set by {@link #setScrollContainer(boolean)}. 1731 */ 1732 static final int PFLAG_SCROLL_CONTAINER_ADDED = 0x00100000; 1733 1734 /** 1735 * View flag indicating whether this view was invalidated (fully or partially.) 1736 * 1737 * @hide 1738 */ 1739 static final int PFLAG_DIRTY = 0x00200000; 1740 1741 /** 1742 * View flag indicating whether this view was invalidated by an opaque 1743 * invalidate request. 1744 * 1745 * @hide 1746 */ 1747 static final int PFLAG_DIRTY_OPAQUE = 0x00400000; 1748 1749 /** 1750 * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}. 1751 * 1752 * @hide 1753 */ 1754 static final int PFLAG_DIRTY_MASK = 0x00600000; 1755 1756 /** 1757 * Indicates whether the background is opaque. 1758 * 1759 * @hide 1760 */ 1761 static final int PFLAG_OPAQUE_BACKGROUND = 0x00800000; 1762 1763 /** 1764 * Indicates whether the scrollbars are opaque. 1765 * 1766 * @hide 1767 */ 1768 static final int PFLAG_OPAQUE_SCROLLBARS = 0x01000000; 1769 1770 /** 1771 * Indicates whether the view is opaque. 1772 * 1773 * @hide 1774 */ 1775 static final int PFLAG_OPAQUE_MASK = 0x01800000; 1776 1777 /** 1778 * Indicates a prepressed state; 1779 * the short time between ACTION_DOWN and recognizing 1780 * a 'real' press. Prepressed is used to recognize quick taps 1781 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1782 * 1783 * @hide 1784 */ 1785 private static final int PFLAG_PREPRESSED = 0x02000000; 1786 1787 /** 1788 * Indicates whether the view is temporarily detached. 1789 * 1790 * @hide 1791 */ 1792 static final int PFLAG_CANCEL_NEXT_UP_EVENT = 0x04000000; 1793 1794 /** 1795 * Indicates that we should awaken scroll bars once attached 1796 * 1797 * @hide 1798 */ 1799 private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1800 1801 /** 1802 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 1803 * @hide 1804 */ 1805 private static final int PFLAG_HOVERED = 0x10000000; 1806 1807 /** 1808 * no longer needed, should be reused 1809 */ 1810 private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000; 1811 1812 /** {@hide} */ 1813 static final int PFLAG_ACTIVATED = 0x40000000; 1814 1815 /** 1816 * Indicates that this view was specifically invalidated, not just dirtied because some 1817 * child view was invalidated. The flag is used to determine when we need to recreate 1818 * a view's display list (as opposed to just returning a reference to its existing 1819 * display list). 1820 * 1821 * @hide 1822 */ 1823 static final int PFLAG_INVALIDATED = 0x80000000; 1824 1825 /** 1826 * Masks for mPrivateFlags2, as generated by dumpFlags(): 1827 * 1828 * |-------|-------|-------|-------| 1829 * 1 PFLAG2_DRAG_CAN_ACCEPT 1830 * 1 PFLAG2_DRAG_HOVERED 1831 * 11 PFLAG2_LAYOUT_DIRECTION_MASK 1832 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL 1833 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED 1834 * 11 PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK 1835 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[1] 1836 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[2] 1837 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[3] 1838 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[4] 1839 * 1 1 PFLAG2_TEXT_DIRECTION_FLAGS[5] 1840 * 111 PFLAG2_TEXT_DIRECTION_MASK 1841 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED 1842 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT 1843 * 111 PFLAG2_TEXT_DIRECTION_RESOLVED_MASK 1844 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[1] 1845 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[2] 1846 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[3] 1847 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[4] 1848 * 1 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[5] 1849 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[6] 1850 * 111 PFLAG2_TEXT_ALIGNMENT_MASK 1851 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED 1852 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT 1853 * 111 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK 1854 * 111 PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK 1855 * 11 PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK 1856 * 1 PFLAG2_ACCESSIBILITY_FOCUSED 1857 * 1 PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED 1858 * 1 PFLAG2_VIEW_QUICK_REJECTED 1859 * 1 PFLAG2_PADDING_RESOLVED 1860 * 1 PFLAG2_DRAWABLE_RESOLVED 1861 * 1 PFLAG2_HAS_TRANSIENT_STATE 1862 * |-------|-------|-------|-------| 1863 */ 1864 1865 /** 1866 * Indicates that this view has reported that it can accept the current drag's content. 1867 * Cleared when the drag operation concludes. 1868 * @hide 1869 */ 1870 static final int PFLAG2_DRAG_CAN_ACCEPT = 0x00000001; 1871 1872 /** 1873 * Indicates that this view is currently directly under the drag location in a 1874 * drag-and-drop operation involving content that it can accept. Cleared when 1875 * the drag exits the view, or when the drag operation concludes. 1876 * @hide 1877 */ 1878 static final int PFLAG2_DRAG_HOVERED = 0x00000002; 1879 1880 /** @hide */ 1881 @IntDef({ 1882 LAYOUT_DIRECTION_LTR, 1883 LAYOUT_DIRECTION_RTL, 1884 LAYOUT_DIRECTION_INHERIT, 1885 LAYOUT_DIRECTION_LOCALE 1886 }) 1887 @Retention(RetentionPolicy.SOURCE) 1888 // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection 1889 public @interface LayoutDir {} 1890 1891 /** @hide */ 1892 @IntDef({ 1893 LAYOUT_DIRECTION_LTR, 1894 LAYOUT_DIRECTION_RTL 1895 }) 1896 @Retention(RetentionPolicy.SOURCE) 1897 public @interface ResolvedLayoutDir {} 1898 1899 /** 1900 * Horizontal layout direction of this view is from Left to Right. 1901 * Use with {@link #setLayoutDirection}. 1902 */ 1903 public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR; 1904 1905 /** 1906 * Horizontal layout direction of this view is from Right to Left. 1907 * Use with {@link #setLayoutDirection}. 1908 */ 1909 public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL; 1910 1911 /** 1912 * Horizontal layout direction of this view is inherited from its parent. 1913 * Use with {@link #setLayoutDirection}. 1914 */ 1915 public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT; 1916 1917 /** 1918 * Horizontal layout direction of this view is from deduced from the default language 1919 * script for the locale. Use with {@link #setLayoutDirection}. 1920 */ 1921 public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE; 1922 1923 /** 1924 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 1925 * @hide 1926 */ 1927 static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2; 1928 1929 /** 1930 * Mask for use with private flags indicating bits used for horizontal layout direction. 1931 * @hide 1932 */ 1933 static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1934 1935 /** 1936 * Indicates whether the view horizontal layout direction has been resolved and drawn to the 1937 * right-to-left direction. 1938 * @hide 1939 */ 1940 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1941 1942 /** 1943 * Indicates whether the view horizontal layout direction has been resolved. 1944 * @hide 1945 */ 1946 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1947 1948 /** 1949 * Mask for use with private flags indicating bits used for resolved horizontal layout direction. 1950 * @hide 1951 */ 1952 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C 1953 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1954 1955 /* 1956 * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct 1957 * flag value. 1958 * @hide 1959 */ 1960 private static final int[] LAYOUT_DIRECTION_FLAGS = { 1961 LAYOUT_DIRECTION_LTR, 1962 LAYOUT_DIRECTION_RTL, 1963 LAYOUT_DIRECTION_INHERIT, 1964 LAYOUT_DIRECTION_LOCALE 1965 }; 1966 1967 /** 1968 * Default horizontal layout direction. 1969 */ 1970 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 1971 1972 /** 1973 * Default horizontal layout direction. 1974 * @hide 1975 */ 1976 static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR; 1977 1978 /** 1979 * Text direction is inherited thru {@link ViewGroup} 1980 */ 1981 public static final int TEXT_DIRECTION_INHERIT = 0; 1982 1983 /** 1984 * Text direction is using "first strong algorithm". The first strong directional character 1985 * determines the paragraph direction. If there is no strong directional character, the 1986 * paragraph direction is the view's resolved layout direction. 1987 */ 1988 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 1989 1990 /** 1991 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 1992 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 1993 * If there are neither, the paragraph direction is the view's resolved layout direction. 1994 */ 1995 public static final int TEXT_DIRECTION_ANY_RTL = 2; 1996 1997 /** 1998 * Text direction is forced to LTR. 1999 */ 2000 public static final int TEXT_DIRECTION_LTR = 3; 2001 2002 /** 2003 * Text direction is forced to RTL. 2004 */ 2005 public static final int TEXT_DIRECTION_RTL = 4; 2006 2007 /** 2008 * Text direction is coming from the system Locale. 2009 */ 2010 public static final int TEXT_DIRECTION_LOCALE = 5; 2011 2012 /** 2013 * Default text direction is inherited 2014 */ 2015 private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT; 2016 2017 /** 2018 * Default resolved text direction 2019 * @hide 2020 */ 2021 static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG; 2022 2023 /** 2024 * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED) 2025 * @hide 2026 */ 2027 static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6; 2028 2029 /** 2030 * Mask for use with private flags indicating bits used for text direction. 2031 * @hide 2032 */ 2033 static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007 2034 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2035 2036 /** 2037 * Array of text direction flags for mapping attribute "textDirection" to correct 2038 * flag value. 2039 * @hide 2040 */ 2041 private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = { 2042 TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2043 TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2044 TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2045 TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2046 TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2047 TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT 2048 }; 2049 2050 /** 2051 * Indicates whether the view text direction has been resolved. 2052 * @hide 2053 */ 2054 static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008 2055 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2056 2057 /** 2058 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2059 * @hide 2060 */ 2061 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10; 2062 2063 /** 2064 * Mask for use with private flags indicating bits used for resolved text direction. 2065 * @hide 2066 */ 2067 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 2068 << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2069 2070 /** 2071 * Indicates whether the view text direction has been resolved to the "first strong" heuristic. 2072 * @hide 2073 */ 2074 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT = 2075 TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2076 2077 /** @hide */ 2078 @IntDef({ 2079 TEXT_ALIGNMENT_INHERIT, 2080 TEXT_ALIGNMENT_GRAVITY, 2081 TEXT_ALIGNMENT_CENTER, 2082 TEXT_ALIGNMENT_TEXT_START, 2083 TEXT_ALIGNMENT_TEXT_END, 2084 TEXT_ALIGNMENT_VIEW_START, 2085 TEXT_ALIGNMENT_VIEW_END 2086 }) 2087 @Retention(RetentionPolicy.SOURCE) 2088 public @interface TextAlignment {} 2089 2090 /** 2091 * Default text alignment. The text alignment of this View is inherited from its parent. 2092 * Use with {@link #setTextAlignment(int)} 2093 */ 2094 public static final int TEXT_ALIGNMENT_INHERIT = 0; 2095 2096 /** 2097 * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL, 2098 * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction. 2099 * 2100 * Use with {@link #setTextAlignment(int)} 2101 */ 2102 public static final int TEXT_ALIGNMENT_GRAVITY = 1; 2103 2104 /** 2105 * Align to the start of the paragraph, e.g. ALIGN_NORMAL. 2106 * 2107 * Use with {@link #setTextAlignment(int)} 2108 */ 2109 public static final int TEXT_ALIGNMENT_TEXT_START = 2; 2110 2111 /** 2112 * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE. 2113 * 2114 * Use with {@link #setTextAlignment(int)} 2115 */ 2116 public static final int TEXT_ALIGNMENT_TEXT_END = 3; 2117 2118 /** 2119 * Center the paragraph, e.g. ALIGN_CENTER. 2120 * 2121 * Use with {@link #setTextAlignment(int)} 2122 */ 2123 public static final int TEXT_ALIGNMENT_CENTER = 4; 2124 2125 /** 2126 * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved 2127 * layoutDirection is LTR, and ALIGN_RIGHT otherwise. 2128 * 2129 * Use with {@link #setTextAlignment(int)} 2130 */ 2131 public static final int TEXT_ALIGNMENT_VIEW_START = 5; 2132 2133 /** 2134 * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved 2135 * layoutDirection is LTR, and ALIGN_LEFT otherwise. 2136 * 2137 * Use with {@link #setTextAlignment(int)} 2138 */ 2139 public static final int TEXT_ALIGNMENT_VIEW_END = 6; 2140 2141 /** 2142 * Default text alignment is inherited 2143 */ 2144 private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2145 2146 /** 2147 * Default resolved text alignment 2148 * @hide 2149 */ 2150 static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2151 2152 /** 2153 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2154 * @hide 2155 */ 2156 static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13; 2157 2158 /** 2159 * Mask for use with private flags indicating bits used for text alignment. 2160 * @hide 2161 */ 2162 static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2163 2164 /** 2165 * Array of text direction flags for mapping attribute "textAlignment" to correct 2166 * flag value. 2167 * @hide 2168 */ 2169 private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = { 2170 TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2171 TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2172 TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2173 TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2174 TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2175 TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2176 TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT 2177 }; 2178 2179 /** 2180 * Indicates whether the view text alignment has been resolved. 2181 * @hide 2182 */ 2183 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2184 2185 /** 2186 * Bit shift to get the resolved text alignment. 2187 * @hide 2188 */ 2189 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17; 2190 2191 /** 2192 * Mask for use with private flags indicating bits used for text alignment. 2193 * @hide 2194 */ 2195 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 2196 << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2197 2198 /** 2199 * Indicates whether if the view text alignment has been resolved to gravity 2200 */ 2201 private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT = 2202 TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2203 2204 // Accessiblity constants for mPrivateFlags2 2205 2206 /** 2207 * Shift for the bits in {@link #mPrivateFlags2} related to the 2208 * "importantForAccessibility" attribute. 2209 */ 2210 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20; 2211 2212 /** 2213 * Automatically determine whether a view is important for accessibility. 2214 */ 2215 public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000; 2216 2217 /** 2218 * The view is important for accessibility. 2219 */ 2220 public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001; 2221 2222 /** 2223 * The view is not important for accessibility. 2224 */ 2225 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002; 2226 2227 /** 2228 * The view is not important for accessibility, nor are any of its 2229 * descendant views. 2230 */ 2231 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004; 2232 2233 /** 2234 * The default whether the view is important for accessibility. 2235 */ 2236 static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO; 2237 2238 /** 2239 * Mask for obtainig the bits which specify how to determine 2240 * whether a view is important for accessibility. 2241 */ 2242 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO 2243 | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO 2244 | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) 2245 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2246 2247 /** 2248 * Shift for the bits in {@link #mPrivateFlags2} related to the 2249 * "accessibilityLiveRegion" attribute. 2250 */ 2251 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23; 2252 2253 /** 2254 * Live region mode specifying that accessibility services should not 2255 * automatically announce changes to this view. This is the default live 2256 * region mode for most views. 2257 * <p> 2258 * Use with {@link #setAccessibilityLiveRegion(int)}. 2259 */ 2260 public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000; 2261 2262 /** 2263 * Live region mode specifying that accessibility services should announce 2264 * changes to this view. 2265 * <p> 2266 * Use with {@link #setAccessibilityLiveRegion(int)}. 2267 */ 2268 public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001; 2269 2270 /** 2271 * Live region mode specifying that accessibility services should interrupt 2272 * ongoing speech to immediately announce changes to this view. 2273 * <p> 2274 * Use with {@link #setAccessibilityLiveRegion(int)}. 2275 */ 2276 public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002; 2277 2278 /** 2279 * The default whether the view is important for accessibility. 2280 */ 2281 static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE; 2282 2283 /** 2284 * Mask for obtaining the bits which specify a view's accessibility live 2285 * region mode. 2286 */ 2287 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE 2288 | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE) 2289 << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 2290 2291 /** 2292 * Flag indicating whether a view has accessibility focus. 2293 */ 2294 static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000; 2295 2296 /** 2297 * Flag whether the accessibility state of the subtree rooted at this view changed. 2298 */ 2299 static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000; 2300 2301 /** 2302 * Flag indicating whether a view failed the quickReject() check in draw(). This condition 2303 * is used to check whether later changes to the view's transform should invalidate the 2304 * view to force the quickReject test to run again. 2305 */ 2306 static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000; 2307 2308 /** 2309 * Flag indicating that start/end padding has been resolved into left/right padding 2310 * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()} 2311 * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved 2312 * during measurement. In some special cases this is required such as when an adapter-based 2313 * view measures prospective children without attaching them to a window. 2314 */ 2315 static final int PFLAG2_PADDING_RESOLVED = 0x20000000; 2316 2317 /** 2318 * Flag indicating that the start/end drawables has been resolved into left/right ones. 2319 */ 2320 static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000; 2321 2322 /** 2323 * Indicates that the view is tracking some sort of transient state 2324 * that the app should not need to be aware of, but that the framework 2325 * should take special care to preserve. 2326 */ 2327 static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000; 2328 2329 /** 2330 * Group of bits indicating that RTL properties resolution is done. 2331 */ 2332 static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED | 2333 PFLAG2_TEXT_DIRECTION_RESOLVED | 2334 PFLAG2_TEXT_ALIGNMENT_RESOLVED | 2335 PFLAG2_PADDING_RESOLVED | 2336 PFLAG2_DRAWABLE_RESOLVED; 2337 2338 // There are a couple of flags left in mPrivateFlags2 2339 2340 /* End of masks for mPrivateFlags2 */ 2341 2342 /** 2343 * Masks for mPrivateFlags3, as generated by dumpFlags(): 2344 * 2345 * |-------|-------|-------|-------| 2346 * 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM 2347 * 1 PFLAG3_VIEW_IS_ANIMATING_ALPHA 2348 * 1 PFLAG3_IS_LAID_OUT 2349 * 1 PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT 2350 * 1 PFLAG3_CALLED_SUPER 2351 * |-------|-------|-------|-------| 2352 */ 2353 2354 /** 2355 * Flag indicating that view has a transform animation set on it. This is used to track whether 2356 * an animation is cleared between successive frames, in order to tell the associated 2357 * DisplayList to clear its animation matrix. 2358 */ 2359 static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1; 2360 2361 /** 2362 * Flag indicating that view has an alpha animation set on it. This is used to track whether an 2363 * animation is cleared between successive frames, in order to tell the associated 2364 * DisplayList to restore its alpha value. 2365 */ 2366 static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2; 2367 2368 /** 2369 * Flag indicating that the view has been through at least one layout since it 2370 * was last attached to a window. 2371 */ 2372 static final int PFLAG3_IS_LAID_OUT = 0x4; 2373 2374 /** 2375 * Flag indicating that a call to measure() was skipped and should be done 2376 * instead when layout() is invoked. 2377 */ 2378 static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8; 2379 2380 /** 2381 * Flag indicating that an overridden method correctly called down to 2382 * the superclass implementation as required by the API spec. 2383 */ 2384 static final int PFLAG3_CALLED_SUPER = 0x10; 2385 2386 /** 2387 * Flag indicating that we're in the process of applying window insets. 2388 */ 2389 static final int PFLAG3_APPLYING_INSETS = 0x20; 2390 2391 /** 2392 * Flag indicating that we're in the process of fitting system windows using the old method. 2393 */ 2394 static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40; 2395 2396 /** 2397 * Flag indicating that nested scrolling is enabled for this view. 2398 * The view will optionally cooperate with views up its parent chain to allow for 2399 * integrated nested scrolling along the same axis. 2400 */ 2401 static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80; 2402 2403 /* End of masks for mPrivateFlags3 */ 2404 2405 static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED; 2406 2407 /** 2408 * Always allow a user to over-scroll this view, provided it is a 2409 * view that can scroll. 2410 * 2411 * @see #getOverScrollMode() 2412 * @see #setOverScrollMode(int) 2413 */ 2414 public static final int OVER_SCROLL_ALWAYS = 0; 2415 2416 /** 2417 * Allow a user to over-scroll this view only if the content is large 2418 * enough to meaningfully scroll, provided it is a view that can scroll. 2419 * 2420 * @see #getOverScrollMode() 2421 * @see #setOverScrollMode(int) 2422 */ 2423 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 2424 2425 /** 2426 * Never allow a user to over-scroll this view. 2427 * 2428 * @see #getOverScrollMode() 2429 * @see #setOverScrollMode(int) 2430 */ 2431 public static final int OVER_SCROLL_NEVER = 2; 2432 2433 /** 2434 * Special constant for {@link #setSystemUiVisibility(int)}: View has 2435 * requested the system UI (status bar) to be visible (the default). 2436 * 2437 * @see #setSystemUiVisibility(int) 2438 */ 2439 public static final int SYSTEM_UI_FLAG_VISIBLE = 0; 2440 2441 /** 2442 * Flag for {@link #setSystemUiVisibility(int)}: View has requested the 2443 * system UI to enter an unobtrusive "low profile" mode. 2444 * 2445 * <p>This is for use in games, book readers, video players, or any other 2446 * "immersive" application where the usual system chrome is deemed too distracting. 2447 * 2448 * <p>In low profile mode, the status bar and/or navigation icons may dim. 2449 * 2450 * @see #setSystemUiVisibility(int) 2451 */ 2452 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001; 2453 2454 /** 2455 * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the 2456 * system navigation be temporarily hidden. 2457 * 2458 * <p>This is an even less obtrusive state than that called for by 2459 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls 2460 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause 2461 * those to disappear. This is useful (in conjunction with the 2462 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and 2463 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN} 2464 * window flags) for displaying content using every last pixel on the display. 2465 * 2466 * <p>There is a limitation: because navigation controls are so important, the least user 2467 * interaction will cause them to reappear immediately. When this happens, both 2468 * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically, 2469 * so that both elements reappear at the same time. 2470 * 2471 * @see #setSystemUiVisibility(int) 2472 */ 2473 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002; 2474 2475 /** 2476 * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go 2477 * into the normal fullscreen mode so that its content can take over the screen 2478 * while still allowing the user to interact with the application. 2479 * 2480 * <p>This has the same visual effect as 2481 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN 2482 * WindowManager.LayoutParams.FLAG_FULLSCREEN}, 2483 * meaning that non-critical screen decorations (such as the status bar) will be 2484 * hidden while the user is in the View's window, focusing the experience on 2485 * that content. Unlike the window flag, if you are using ActionBar in 2486 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2487 * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also 2488 * hide the action bar. 2489 * 2490 * <p>This approach to going fullscreen is best used over the window flag when 2491 * it is a transient state -- that is, the application does this at certain 2492 * points in its user interaction where it wants to allow the user to focus 2493 * on content, but not as a continuous state. For situations where the application 2494 * would like to simply stay full screen the entire time (such as a game that 2495 * wants to take over the screen), the 2496 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag} 2497 * is usually a better approach. The state set here will be removed by the system 2498 * in various situations (such as the user moving to another application) like 2499 * the other system UI states. 2500 * 2501 * <p>When using this flag, the application should provide some easy facility 2502 * for the user to go out of it. A common example would be in an e-book 2503 * reader, where tapping on the screen brings back whatever screen and UI 2504 * decorations that had been hidden while the user was immersed in reading 2505 * the book. 2506 * 2507 * @see #setSystemUiVisibility(int) 2508 */ 2509 public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004; 2510 2511 /** 2512 * Flag for {@link #setSystemUiVisibility(int)}: When using other layout 2513 * flags, we would like a stable view of the content insets given to 2514 * {@link #fitSystemWindows(Rect)}. This means that the insets seen there 2515 * will always represent the worst case that the application can expect 2516 * as a continuous state. In the stock Android UI this is the space for 2517 * the system bar, nav bar, and status bar, but not more transient elements 2518 * such as an input method. 2519 * 2520 * The stable layout your UI sees is based on the system UI modes you can 2521 * switch to. That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 2522 * then you will get a stable layout for changes of the 2523 * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify 2524 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and 2525 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition 2526 * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} 2527 * with a stable layout. (Note that you should avoid using 2528 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.) 2529 * 2530 * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN} 2531 * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}), 2532 * then a hidden status bar will be considered a "stable" state for purposes 2533 * here. This allows your UI to continually hide the status bar, while still 2534 * using the system UI flags to hide the action bar while still retaining 2535 * a stable layout. Note that changing the window fullscreen flag will never 2536 * provide a stable layout for a clean transition. 2537 * 2538 * <p>If you are using ActionBar in 2539 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2540 * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the 2541 * insets it adds to those given to the application. 2542 */ 2543 public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100; 2544 2545 /** 2546 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2547 * to be layed out as if it has requested 2548 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't. This 2549 * allows it to avoid artifacts when switching in and out of that mode, at 2550 * the expense that some of its user interface may be covered by screen 2551 * decorations when they are shown. You can perform layout of your inner 2552 * UI elements to account for the navigation system UI through the 2553 * {@link #fitSystemWindows(Rect)} method. 2554 */ 2555 public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200; 2556 2557 /** 2558 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2559 * to be layed out as if it has requested 2560 * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't. This 2561 * allows it to avoid artifacts when switching in and out of that mode, at 2562 * the expense that some of its user interface may be covered by screen 2563 * decorations when they are shown. You can perform layout of your inner 2564 * UI elements to account for non-fullscreen system UI through the 2565 * {@link #fitSystemWindows(Rect)} method. 2566 */ 2567 public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400; 2568 2569 /** 2570 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2571 * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. If this flag is 2572 * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any 2573 * user interaction. 2574 * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only 2575 * has an effect when used in combination with that flag.</p> 2576 */ 2577 public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800; 2578 2579 /** 2580 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2581 * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation 2582 * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. Use this flag to create an immersive 2583 * experience while also hiding the system bars. If this flag is not set, 2584 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user 2585 * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system 2586 * if the user swipes from the top of the screen. 2587 * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with 2588 * system gestures, such as swiping from the top of the screen. These transient system bars 2589 * will overlay app’s content, may have some degree of transparency, and will automatically 2590 * hide after a short timeout. 2591 * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and 2592 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination 2593 * with one or both of those flags.</p> 2594 */ 2595 public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000; 2596 2597 /** 2598 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead. 2599 */ 2600 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE; 2601 2602 /** 2603 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead. 2604 */ 2605 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE; 2606 2607 /** 2608 * @hide 2609 * 2610 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2611 * out of the public fields to keep the undefined bits out of the developer's way. 2612 * 2613 * Flag to make the status bar not expandable. Unless you also 2614 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 2615 */ 2616 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 2617 2618 /** 2619 * @hide 2620 * 2621 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2622 * out of the public fields to keep the undefined bits out of the developer's way. 2623 * 2624 * Flag to hide notification icons and scrolling ticker text. 2625 */ 2626 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 2627 2628 /** 2629 * @hide 2630 * 2631 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2632 * out of the public fields to keep the undefined bits out of the developer's way. 2633 * 2634 * Flag to disable incoming notification alerts. This will not block 2635 * icons, but it will block sound, vibrating and other visual or aural notifications. 2636 */ 2637 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 2638 2639 /** 2640 * @hide 2641 * 2642 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2643 * out of the public fields to keep the undefined bits out of the developer's way. 2644 * 2645 * Flag to hide only the scrolling ticker. Note that 2646 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 2647 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 2648 */ 2649 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 2650 2651 /** 2652 * @hide 2653 * 2654 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2655 * out of the public fields to keep the undefined bits out of the developer's way. 2656 * 2657 * Flag to hide the center system info area. 2658 */ 2659 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 2660 2661 /** 2662 * @hide 2663 * 2664 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2665 * out of the public fields to keep the undefined bits out of the developer's way. 2666 * 2667 * Flag to hide only the home button. Don't use this 2668 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2669 */ 2670 public static final int STATUS_BAR_DISABLE_HOME = 0x00200000; 2671 2672 /** 2673 * @hide 2674 * 2675 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2676 * out of the public fields to keep the undefined bits out of the developer's way. 2677 * 2678 * Flag to hide only the back button. Don't use this 2679 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2680 */ 2681 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 2682 2683 /** 2684 * @hide 2685 * 2686 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2687 * out of the public fields to keep the undefined bits out of the developer's way. 2688 * 2689 * Flag to hide only the clock. You might use this if your activity has 2690 * its own clock making the status bar's clock redundant. 2691 */ 2692 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 2693 2694 /** 2695 * @hide 2696 * 2697 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2698 * out of the public fields to keep the undefined bits out of the developer's way. 2699 * 2700 * Flag to hide only the recent apps button. Don't use this 2701 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2702 */ 2703 public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000; 2704 2705 /** 2706 * @hide 2707 * 2708 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2709 * out of the public fields to keep the undefined bits out of the developer's way. 2710 * 2711 * Flag to disable the global search gesture. Don't use this 2712 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2713 */ 2714 public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000; 2715 2716 /** 2717 * @hide 2718 * 2719 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2720 * out of the public fields to keep the undefined bits out of the developer's way. 2721 * 2722 * Flag to specify that the status bar is displayed in transient mode. 2723 */ 2724 public static final int STATUS_BAR_TRANSIENT = 0x04000000; 2725 2726 /** 2727 * @hide 2728 * 2729 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2730 * out of the public fields to keep the undefined bits out of the developer's way. 2731 * 2732 * Flag to specify that the navigation bar is displayed in transient mode. 2733 */ 2734 public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000; 2735 2736 /** 2737 * @hide 2738 * 2739 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2740 * out of the public fields to keep the undefined bits out of the developer's way. 2741 * 2742 * Flag to specify that the hidden status bar would like to be shown. 2743 */ 2744 public static final int STATUS_BAR_UNHIDE = 0x10000000; 2745 2746 /** 2747 * @hide 2748 * 2749 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2750 * out of the public fields to keep the undefined bits out of the developer's way. 2751 * 2752 * Flag to specify that the hidden navigation bar would like to be shown. 2753 */ 2754 public static final int NAVIGATION_BAR_UNHIDE = 0x20000000; 2755 2756 /** 2757 * @hide 2758 * 2759 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2760 * out of the public fields to keep the undefined bits out of the developer's way. 2761 * 2762 * Flag to specify that the status bar is displayed in translucent mode. 2763 */ 2764 public static final int STATUS_BAR_TRANSLUCENT = 0x40000000; 2765 2766 /** 2767 * @hide 2768 * 2769 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2770 * out of the public fields to keep the undefined bits out of the developer's way. 2771 * 2772 * Flag to specify that the navigation bar is displayed in translucent mode. 2773 */ 2774 public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000; 2775 2776 /** 2777 * @hide 2778 * 2779 * Whether Recents is visible or not. 2780 */ 2781 public static final int RECENT_APPS_VISIBLE = 0x00004000; 2782 2783 /** 2784 * @hide 2785 * 2786 * Makes system ui transparent. 2787 */ 2788 public static final int SYSTEM_UI_TRANSPARENT = 0x00008000; 2789 2790 /** 2791 * @hide 2792 */ 2793 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FFF; 2794 2795 /** 2796 * These are the system UI flags that can be cleared by events outside 2797 * of an application. Currently this is just the ability to tap on the 2798 * screen while hiding the navigation bar to have it return. 2799 * @hide 2800 */ 2801 public static final int SYSTEM_UI_CLEARABLE_FLAGS = 2802 SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION 2803 | SYSTEM_UI_FLAG_FULLSCREEN; 2804 2805 /** 2806 * Flags that can impact the layout in relation to system UI. 2807 */ 2808 public static final int SYSTEM_UI_LAYOUT_FLAGS = 2809 SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 2810 | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; 2811 2812 /** @hide */ 2813 @IntDef(flag = true, 2814 value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION }) 2815 @Retention(RetentionPolicy.SOURCE) 2816 public @interface FindViewFlags {} 2817 2818 /** 2819 * Find views that render the specified text. 2820 * 2821 * @see #findViewsWithText(ArrayList, CharSequence, int) 2822 */ 2823 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001; 2824 2825 /** 2826 * Find find views that contain the specified content description. 2827 * 2828 * @see #findViewsWithText(ArrayList, CharSequence, int) 2829 */ 2830 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002; 2831 2832 /** 2833 * Find views that contain {@link AccessibilityNodeProvider}. Such 2834 * a View is a root of virtual view hierarchy and may contain the searched 2835 * text. If this flag is set Views with providers are automatically 2836 * added and it is a responsibility of the client to call the APIs of 2837 * the provider to determine whether the virtual tree rooted at this View 2838 * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s 2839 * representing the virtual views with this text. 2840 * 2841 * @see #findViewsWithText(ArrayList, CharSequence, int) 2842 * 2843 * @hide 2844 */ 2845 public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004; 2846 2847 /** 2848 * The undefined cursor position. 2849 * 2850 * @hide 2851 */ 2852 public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1; 2853 2854 /** 2855 * Indicates that the screen has changed state and is now off. 2856 * 2857 * @see #onScreenStateChanged(int) 2858 */ 2859 public static final int SCREEN_STATE_OFF = 0x0; 2860 2861 /** 2862 * Indicates that the screen has changed state and is now on. 2863 * 2864 * @see #onScreenStateChanged(int) 2865 */ 2866 public static final int SCREEN_STATE_ON = 0x1; 2867 2868 /** 2869 * Indicates no axis of view scrolling. 2870 */ 2871 public static final int SCROLL_AXIS_NONE = 0; 2872 2873 /** 2874 * Indicates scrolling along the horizontal axis. 2875 */ 2876 public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0; 2877 2878 /** 2879 * Indicates scrolling along the vertical axis. 2880 */ 2881 public static final int SCROLL_AXIS_VERTICAL = 1 << 1; 2882 2883 /** 2884 * Controls the over-scroll mode for this view. 2885 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 2886 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 2887 * and {@link #OVER_SCROLL_NEVER}. 2888 */ 2889 private int mOverScrollMode; 2890 2891 /** 2892 * The parent this view is attached to. 2893 * {@hide} 2894 * 2895 * @see #getParent() 2896 */ 2897 protected ViewParent mParent; 2898 2899 /** 2900 * {@hide} 2901 */ 2902 AttachInfo mAttachInfo; 2903 2904 /** 2905 * {@hide} 2906 */ 2907 @ViewDebug.ExportedProperty(flagMapping = { 2908 @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT, 2909 name = "FORCE_LAYOUT"), 2910 @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED, 2911 name = "LAYOUT_REQUIRED"), 2912 @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID, 2913 name = "DRAWING_CACHE_INVALID", outputIf = false), 2914 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true), 2915 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false), 2916 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 2917 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY") 2918 }, formatToHexString = true) 2919 int mPrivateFlags; 2920 int mPrivateFlags2; 2921 int mPrivateFlags3; 2922 2923 /** 2924 * This view's request for the visibility of the status bar. 2925 * @hide 2926 */ 2927 @ViewDebug.ExportedProperty(flagMapping = { 2928 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 2929 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 2930 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 2931 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2932 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2933 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 2934 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 2935 equals = SYSTEM_UI_FLAG_VISIBLE, 2936 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 2937 }, formatToHexString = true) 2938 int mSystemUiVisibility; 2939 2940 /** 2941 * Reference count for transient state. 2942 * @see #setHasTransientState(boolean) 2943 */ 2944 int mTransientStateCount = 0; 2945 2946 /** 2947 * Count of how many windows this view has been attached to. 2948 */ 2949 int mWindowAttachCount; 2950 2951 /** 2952 * The layout parameters associated with this view and used by the parent 2953 * {@link android.view.ViewGroup} to determine how this view should be 2954 * laid out. 2955 * {@hide} 2956 */ 2957 protected ViewGroup.LayoutParams mLayoutParams; 2958 2959 /** 2960 * The view flags hold various views states. 2961 * {@hide} 2962 */ 2963 @ViewDebug.ExportedProperty(formatToHexString = true) 2964 int mViewFlags; 2965 2966 static class TransformationInfo { 2967 /** 2968 * The transform matrix for the View. This transform is calculated internally 2969 * based on the translation, rotation, and scale properties. 2970 * 2971 * Do *not* use this variable directly; instead call getMatrix(), which will 2972 * load the value from the View's RenderNode. 2973 */ 2974 private final Matrix mMatrix = new Matrix(); 2975 2976 /** 2977 * The inverse transform matrix for the View. This transform is calculated 2978 * internally based on the translation, rotation, and scale properties. 2979 * 2980 * Do *not* use this variable directly; instead call getInverseMatrix(), 2981 * which will load the value from the View's RenderNode. 2982 */ 2983 private Matrix mInverseMatrix; 2984 2985 /** 2986 * The opacity of the View. This is a value from 0 to 1, where 0 means 2987 * completely transparent and 1 means completely opaque. 2988 */ 2989 @ViewDebug.ExportedProperty 2990 float mAlpha = 1f; 2991 2992 /** 2993 * The opacity of the view as manipulated by the Fade transition. This is a hidden 2994 * property only used by transitions, which is composited with the other alpha 2995 * values to calculate the final visual alpha value. 2996 */ 2997 float mTransitionAlpha = 1f; 2998 } 2999 3000 TransformationInfo mTransformationInfo; 3001 3002 /** 3003 * Current clip bounds. to which all drawing of this view are constrained. 3004 */ 3005 Rect mClipBounds = null; 3006 3007 private boolean mLastIsOpaque; 3008 3009 /** 3010 * The distance in pixels from the left edge of this view's parent 3011 * to the left edge of this view. 3012 * {@hide} 3013 */ 3014 @ViewDebug.ExportedProperty(category = "layout") 3015 protected int mLeft; 3016 /** 3017 * The distance in pixels from the left edge of this view's parent 3018 * to the right edge of this view. 3019 * {@hide} 3020 */ 3021 @ViewDebug.ExportedProperty(category = "layout") 3022 protected int mRight; 3023 /** 3024 * The distance in pixels from the top edge of this view's parent 3025 * to the top edge of this view. 3026 * {@hide} 3027 */ 3028 @ViewDebug.ExportedProperty(category = "layout") 3029 protected int mTop; 3030 /** 3031 * The distance in pixels from the top edge of this view's parent 3032 * to the bottom edge of this view. 3033 * {@hide} 3034 */ 3035 @ViewDebug.ExportedProperty(category = "layout") 3036 protected int mBottom; 3037 3038 /** 3039 * The offset, in pixels, by which the content of this view is scrolled 3040 * horizontally. 3041 * {@hide} 3042 */ 3043 @ViewDebug.ExportedProperty(category = "scrolling") 3044 protected int mScrollX; 3045 /** 3046 * The offset, in pixels, by which the content of this view is scrolled 3047 * vertically. 3048 * {@hide} 3049 */ 3050 @ViewDebug.ExportedProperty(category = "scrolling") 3051 protected int mScrollY; 3052 3053 /** 3054 * The left padding in pixels, that is the distance in pixels between the 3055 * left edge of this view and the left edge of its content. 3056 * {@hide} 3057 */ 3058 @ViewDebug.ExportedProperty(category = "padding") 3059 protected int mPaddingLeft = 0; 3060 /** 3061 * The right padding in pixels, that is the distance in pixels between the 3062 * right edge of this view and the right edge of its content. 3063 * {@hide} 3064 */ 3065 @ViewDebug.ExportedProperty(category = "padding") 3066 protected int mPaddingRight = 0; 3067 /** 3068 * The top padding in pixels, that is the distance in pixels between the 3069 * top edge of this view and the top edge of its content. 3070 * {@hide} 3071 */ 3072 @ViewDebug.ExportedProperty(category = "padding") 3073 protected int mPaddingTop; 3074 /** 3075 * The bottom padding in pixels, that is the distance in pixels between the 3076 * bottom edge of this view and the bottom edge of its content. 3077 * {@hide} 3078 */ 3079 @ViewDebug.ExportedProperty(category = "padding") 3080 protected int mPaddingBottom; 3081 3082 /** 3083 * The layout insets in pixels, that is the distance in pixels between the 3084 * visible edges of this view its bounds. 3085 */ 3086 private Insets mLayoutInsets; 3087 3088 /** 3089 * Briefly describes the view and is primarily used for accessibility support. 3090 */ 3091 private CharSequence mContentDescription; 3092 3093 /** 3094 * Specifies the id of a view for which this view serves as a label for 3095 * accessibility purposes. 3096 */ 3097 private int mLabelForId = View.NO_ID; 3098 3099 /** 3100 * Predicate for matching labeled view id with its label for 3101 * accessibility purposes. 3102 */ 3103 private MatchLabelForPredicate mMatchLabelForPredicate; 3104 3105 /** 3106 * Predicate for matching a view by its id. 3107 */ 3108 private MatchIdPredicate mMatchIdPredicate; 3109 3110 /** 3111 * Cache the paddingRight set by the user to append to the scrollbar's size. 3112 * 3113 * @hide 3114 */ 3115 @ViewDebug.ExportedProperty(category = "padding") 3116 protected int mUserPaddingRight; 3117 3118 /** 3119 * Cache the paddingBottom set by the user to append to the scrollbar's size. 3120 * 3121 * @hide 3122 */ 3123 @ViewDebug.ExportedProperty(category = "padding") 3124 protected int mUserPaddingBottom; 3125 3126 /** 3127 * Cache the paddingLeft set by the user to append to the scrollbar's size. 3128 * 3129 * @hide 3130 */ 3131 @ViewDebug.ExportedProperty(category = "padding") 3132 protected int mUserPaddingLeft; 3133 3134 /** 3135 * Cache the paddingStart set by the user to append to the scrollbar's size. 3136 * 3137 */ 3138 @ViewDebug.ExportedProperty(category = "padding") 3139 int mUserPaddingStart; 3140 3141 /** 3142 * Cache the paddingEnd set by the user to append to the scrollbar's size. 3143 * 3144 */ 3145 @ViewDebug.ExportedProperty(category = "padding") 3146 int mUserPaddingEnd; 3147 3148 /** 3149 * Cache initial left padding. 3150 * 3151 * @hide 3152 */ 3153 int mUserPaddingLeftInitial; 3154 3155 /** 3156 * Cache initial right padding. 3157 * 3158 * @hide 3159 */ 3160 int mUserPaddingRightInitial; 3161 3162 /** 3163 * Default undefined padding 3164 */ 3165 private static final int UNDEFINED_PADDING = Integer.MIN_VALUE; 3166 3167 /** 3168 * Cache if a left padding has been defined 3169 */ 3170 private boolean mLeftPaddingDefined = false; 3171 3172 /** 3173 * Cache if a right padding has been defined 3174 */ 3175 private boolean mRightPaddingDefined = false; 3176 3177 /** 3178 * @hide 3179 */ 3180 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 3181 /** 3182 * @hide 3183 */ 3184 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 3185 3186 private LongSparseLongArray mMeasureCache; 3187 3188 @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_") 3189 private Drawable mBackground; 3190 private ColorStateList mBackgroundTintList = null; 3191 private PorterDuff.Mode mBackgroundTintMode = PorterDuff.Mode.SRC_ATOP; 3192 private boolean mHasBackgroundTint = false; 3193 3194 /** 3195 * RenderNode used for backgrounds. 3196 * <p> 3197 * When non-null and valid, this is expected to contain an up-to-date copy 3198 * of the background drawable. It is cleared on temporary detach, and reset 3199 * on cleanup. 3200 */ 3201 private RenderNode mBackgroundRenderNode; 3202 3203 private int mBackgroundResource; 3204 private boolean mBackgroundSizeChanged; 3205 3206 private String mTransitionName; 3207 3208 static class ListenerInfo { 3209 /** 3210 * Listener used to dispatch focus change events. 3211 * This field should be made private, so it is hidden from the SDK. 3212 * {@hide} 3213 */ 3214 protected OnFocusChangeListener mOnFocusChangeListener; 3215 3216 /** 3217 * Listeners for layout change events. 3218 */ 3219 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 3220 3221 /** 3222 * Listeners for attach events. 3223 */ 3224 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 3225 3226 /** 3227 * Listener used to dispatch click events. 3228 * This field should be made private, so it is hidden from the SDK. 3229 * {@hide} 3230 */ 3231 public OnClickListener mOnClickListener; 3232 3233 /** 3234 * Listener used to dispatch long click events. 3235 * This field should be made private, so it is hidden from the SDK. 3236 * {@hide} 3237 */ 3238 protected OnLongClickListener mOnLongClickListener; 3239 3240 /** 3241 * Listener used to build the context menu. 3242 * This field should be made private, so it is hidden from the SDK. 3243 * {@hide} 3244 */ 3245 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 3246 3247 private OnKeyListener mOnKeyListener; 3248 3249 private OnTouchListener mOnTouchListener; 3250 3251 private OnHoverListener mOnHoverListener; 3252 3253 private OnGenericMotionListener mOnGenericMotionListener; 3254 3255 private OnDragListener mOnDragListener; 3256 3257 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 3258 3259 OnApplyWindowInsetsListener mOnApplyWindowInsetsListener; 3260 } 3261 3262 ListenerInfo mListenerInfo; 3263 3264 /** 3265 * The application environment this view lives in. 3266 * This field should be made private, so it is hidden from the SDK. 3267 * {@hide} 3268 */ 3269 @ViewDebug.ExportedProperty(deepExport = true) 3270 protected Context mContext; 3271 3272 private final Resources mResources; 3273 3274 private ScrollabilityCache mScrollCache; 3275 3276 private int[] mDrawableState = null; 3277 3278 ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND; 3279 3280 /** 3281 * Animator that automatically runs based on state changes. 3282 */ 3283 private StateListAnimator mStateListAnimator; 3284 3285 /** 3286 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 3287 * the user may specify which view to go to next. 3288 */ 3289 private int mNextFocusLeftId = View.NO_ID; 3290 3291 /** 3292 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 3293 * the user may specify which view to go to next. 3294 */ 3295 private int mNextFocusRightId = View.NO_ID; 3296 3297 /** 3298 * When this view has focus and the next focus is {@link #FOCUS_UP}, 3299 * the user may specify which view to go to next. 3300 */ 3301 private int mNextFocusUpId = View.NO_ID; 3302 3303 /** 3304 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 3305 * the user may specify which view to go to next. 3306 */ 3307 private int mNextFocusDownId = View.NO_ID; 3308 3309 /** 3310 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 3311 * the user may specify which view to go to next. 3312 */ 3313 int mNextFocusForwardId = View.NO_ID; 3314 3315 private CheckForLongPress mPendingCheckForLongPress; 3316 private CheckForTap mPendingCheckForTap = null; 3317 private PerformClick mPerformClick; 3318 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 3319 3320 private UnsetPressedState mUnsetPressedState; 3321 3322 /** 3323 * Whether the long press's action has been invoked. The tap's action is invoked on the 3324 * up event while a long press is invoked as soon as the long press duration is reached, so 3325 * a long press could be performed before the tap is checked, in which case the tap's action 3326 * should not be invoked. 3327 */ 3328 private boolean mHasPerformedLongPress; 3329 3330 /** 3331 * The minimum height of the view. We'll try our best to have the height 3332 * of this view to at least this amount. 3333 */ 3334 @ViewDebug.ExportedProperty(category = "measurement") 3335 private int mMinHeight; 3336 3337 /** 3338 * The minimum width of the view. We'll try our best to have the width 3339 * of this view to at least this amount. 3340 */ 3341 @ViewDebug.ExportedProperty(category = "measurement") 3342 private int mMinWidth; 3343 3344 /** 3345 * The delegate to handle touch events that are physically in this view 3346 * but should be handled by another view. 3347 */ 3348 private TouchDelegate mTouchDelegate = null; 3349 3350 /** 3351 * Solid color to use as a background when creating the drawing cache. Enables 3352 * the cache to use 16 bit bitmaps instead of 32 bit. 3353 */ 3354 private int mDrawingCacheBackgroundColor = 0; 3355 3356 /** 3357 * Special tree observer used when mAttachInfo is null. 3358 */ 3359 private ViewTreeObserver mFloatingTreeObserver; 3360 3361 /** 3362 * Cache the touch slop from the context that created the view. 3363 */ 3364 private int mTouchSlop; 3365 3366 /** 3367 * Object that handles automatic animation of view properties. 3368 */ 3369 private ViewPropertyAnimator mAnimator = null; 3370 3371 /** 3372 * Flag indicating that a drag can cross window boundaries. When 3373 * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called 3374 * with this flag set, all visible applications will be able to participate 3375 * in the drag operation and receive the dragged content. 3376 * 3377 * @hide 3378 */ 3379 public static final int DRAG_FLAG_GLOBAL = 1; 3380 3381 /** 3382 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 3383 */ 3384 private float mVerticalScrollFactor; 3385 3386 /** 3387 * Position of the vertical scroll bar. 3388 */ 3389 private int mVerticalScrollbarPosition; 3390 3391 /** 3392 * Position the scroll bar at the default position as determined by the system. 3393 */ 3394 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 3395 3396 /** 3397 * Position the scroll bar along the left edge. 3398 */ 3399 public static final int SCROLLBAR_POSITION_LEFT = 1; 3400 3401 /** 3402 * Position the scroll bar along the right edge. 3403 */ 3404 public static final int SCROLLBAR_POSITION_RIGHT = 2; 3405 3406 /** 3407 * Indicates that the view does not have a layer. 3408 * 3409 * @see #getLayerType() 3410 * @see #setLayerType(int, android.graphics.Paint) 3411 * @see #LAYER_TYPE_SOFTWARE 3412 * @see #LAYER_TYPE_HARDWARE 3413 */ 3414 public static final int LAYER_TYPE_NONE = 0; 3415 3416 /** 3417 * <p>Indicates that the view has a software layer. A software layer is backed 3418 * by a bitmap and causes the view to be rendered using Android's software 3419 * rendering pipeline, even if hardware acceleration is enabled.</p> 3420 * 3421 * <p>Software layers have various usages:</p> 3422 * <p>When the application is not using hardware acceleration, a software layer 3423 * is useful to apply a specific color filter and/or blending mode and/or 3424 * translucency to a view and all its children.</p> 3425 * <p>When the application is using hardware acceleration, a software layer 3426 * is useful to render drawing primitives not supported by the hardware 3427 * accelerated pipeline. It can also be used to cache a complex view tree 3428 * into a texture and reduce the complexity of drawing operations. For instance, 3429 * when animating a complex view tree with a translation, a software layer can 3430 * be used to render the view tree only once.</p> 3431 * <p>Software layers should be avoided when the affected view tree updates 3432 * often. Every update will require to re-render the software layer, which can 3433 * potentially be slow (particularly when hardware acceleration is turned on 3434 * since the layer will have to be uploaded into a hardware texture after every 3435 * update.)</p> 3436 * 3437 * @see #getLayerType() 3438 * @see #setLayerType(int, android.graphics.Paint) 3439 * @see #LAYER_TYPE_NONE 3440 * @see #LAYER_TYPE_HARDWARE 3441 */ 3442 public static final int LAYER_TYPE_SOFTWARE = 1; 3443 3444 /** 3445 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 3446 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 3447 * OpenGL hardware) and causes the view to be rendered using Android's hardware 3448 * rendering pipeline, but only if hardware acceleration is turned on for the 3449 * view hierarchy. When hardware acceleration is turned off, hardware layers 3450 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 3451 * 3452 * <p>A hardware layer is useful to apply a specific color filter and/or 3453 * blending mode and/or translucency to a view and all its children.</p> 3454 * <p>A hardware layer can be used to cache a complex view tree into a 3455 * texture and reduce the complexity of drawing operations. For instance, 3456 * when animating a complex view tree with a translation, a hardware layer can 3457 * be used to render the view tree only once.</p> 3458 * <p>A hardware layer can also be used to increase the rendering quality when 3459 * rotation transformations are applied on a view. It can also be used to 3460 * prevent potential clipping issues when applying 3D transforms on a view.</p> 3461 * 3462 * @see #getLayerType() 3463 * @see #setLayerType(int, android.graphics.Paint) 3464 * @see #LAYER_TYPE_NONE 3465 * @see #LAYER_TYPE_SOFTWARE 3466 */ 3467 public static final int LAYER_TYPE_HARDWARE = 2; 3468 3469 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 3470 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 3471 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 3472 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 3473 }) 3474 int mLayerType = LAYER_TYPE_NONE; 3475 Paint mLayerPaint; 3476 3477 /** 3478 * Set to true when drawing cache is enabled and cannot be created. 3479 * 3480 * @hide 3481 */ 3482 public boolean mCachingFailed; 3483 private Bitmap mDrawingCache; 3484 private Bitmap mUnscaledDrawingCache; 3485 3486 /** 3487 * RenderNode holding View properties, potentially holding a DisplayList of View content. 3488 * <p> 3489 * When non-null and valid, this is expected to contain an up-to-date copy 3490 * of the View content. Its DisplayList content is cleared on temporary detach and reset on 3491 * cleanup. 3492 */ 3493 final RenderNode mRenderNode; 3494 3495 /** 3496 * Set to true when the view is sending hover accessibility events because it 3497 * is the innermost hovered view. 3498 */ 3499 private boolean mSendingHoverAccessibilityEvents; 3500 3501 /** 3502 * Delegate for injecting accessibility functionality. 3503 */ 3504 AccessibilityDelegate mAccessibilityDelegate; 3505 3506 /** 3507 * The view's overlay layer. Developers get a reference to the overlay via getOverlay() 3508 * and add/remove objects to/from the overlay directly through the Overlay methods. 3509 */ 3510 ViewOverlay mOverlay; 3511 3512 /** 3513 * The currently active parent view for receiving delegated nested scrolling events. 3514 * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared 3515 * by {@link #stopNestedScroll()} at the same point where we clear 3516 * requestDisallowInterceptTouchEvent. 3517 */ 3518 private ViewParent mNestedScrollingParent; 3519 3520 /** 3521 * Consistency verifier for debugging purposes. 3522 * @hide 3523 */ 3524 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 3525 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 3526 new InputEventConsistencyVerifier(this, 0) : null; 3527 3528 private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); 3529 3530 private int[] mTempNestedScrollConsumed; 3531 3532 /** 3533 * An overlay is going to draw this View instead of being drawn as part of this 3534 * View's parent. mGhostView is the View in the Overlay that must be invalidated 3535 * when this view is invalidated. 3536 */ 3537 GhostView mGhostView; 3538 3539 /** 3540 * Holds pairs of adjacent attribute data: attribute name followed by its value. 3541 * @hide 3542 */ 3543 @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true) 3544 public String[] mAttributes; 3545 3546 /** 3547 * Maps a Resource id to its name. 3548 */ 3549 private static SparseArray<String> mAttributeMap; 3550 3551 /** 3552 * Simple constructor to use when creating a view from code. 3553 * 3554 * @param context The Context the view is running in, through which it can 3555 * access the current theme, resources, etc. 3556 */ 3557 public View(Context context) { 3558 mContext = context; 3559 mResources = context != null ? context.getResources() : null; 3560 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED; 3561 // Set some flags defaults 3562 mPrivateFlags2 = 3563 (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) | 3564 (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) | 3565 (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) | 3566 (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) | 3567 (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) | 3568 (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT); 3569 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 3570 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 3571 mUserPaddingStart = UNDEFINED_PADDING; 3572 mUserPaddingEnd = UNDEFINED_PADDING; 3573 mRenderNode = RenderNode.create(getClass().getName(), this); 3574 3575 if (!sCompatibilityDone && context != null) { 3576 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3577 3578 // Older apps may need this compatibility hack for measurement. 3579 sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1; 3580 3581 // Older apps expect onMeasure() to always be called on a layout pass, regardless 3582 // of whether a layout was requested on that View. 3583 sIgnoreMeasureCache = targetSdkVersion < KITKAT; 3584 3585 sCompatibilityDone = true; 3586 } 3587 } 3588 3589 /** 3590 * Constructor that is called when inflating a view from XML. This is called 3591 * when a view is being constructed from an XML file, supplying attributes 3592 * that were specified in the XML file. This version uses a default style of 3593 * 0, so the only attribute values applied are those in the Context's Theme 3594 * and the given AttributeSet. 3595 * 3596 * <p> 3597 * The method onFinishInflate() will be called after all children have been 3598 * added. 3599 * 3600 * @param context The Context the view is running in, through which it can 3601 * access the current theme, resources, etc. 3602 * @param attrs The attributes of the XML tag that is inflating the view. 3603 * @see #View(Context, AttributeSet, int) 3604 */ 3605 public View(Context context, AttributeSet attrs) { 3606 this(context, attrs, 0); 3607 } 3608 3609 /** 3610 * Perform inflation from XML and apply a class-specific base style from a 3611 * theme attribute. This constructor of View allows subclasses to use their 3612 * own base style when they are inflating. For example, a Button class's 3613 * constructor would call this version of the super class constructor and 3614 * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this 3615 * allows the theme's button style to modify all of the base view attributes 3616 * (in particular its background) as well as the Button class's attributes. 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 * @param defStyleAttr An attribute in the current theme that contains a 3622 * reference to a style resource that supplies default values for 3623 * the view. Can be 0 to not look for defaults. 3624 * @see #View(Context, AttributeSet) 3625 */ 3626 public View(Context context, AttributeSet attrs, int defStyleAttr) { 3627 this(context, attrs, defStyleAttr, 0); 3628 } 3629 3630 /** 3631 * Perform inflation from XML and apply a class-specific base style from a 3632 * theme attribute or style resource. This constructor of View allows 3633 * subclasses to use their own base style when they are inflating. 3634 * <p> 3635 * When determining the final value of a particular attribute, there are 3636 * four inputs that come into play: 3637 * <ol> 3638 * <li>Any attribute values in the given AttributeSet. 3639 * <li>The style resource specified in the AttributeSet (named "style"). 3640 * <li>The default style specified by <var>defStyleAttr</var>. 3641 * <li>The default style specified by <var>defStyleRes</var>. 3642 * <li>The base values in this theme. 3643 * </ol> 3644 * <p> 3645 * Each of these inputs is considered in-order, with the first listed taking 3646 * precedence over the following ones. In other words, if in the 3647 * AttributeSet you have supplied <code><Button * textColor="#ff000000"></code> 3648 * , then the button's text will <em>always</em> be black, regardless of 3649 * what is specified in any of the styles. 3650 * 3651 * @param context The Context the view is running in, through which it can 3652 * access the current theme, resources, etc. 3653 * @param attrs The attributes of the XML tag that is inflating the view. 3654 * @param defStyleAttr An attribute in the current theme that contains a 3655 * reference to a style resource that supplies default values for 3656 * the view. Can be 0 to not look for defaults. 3657 * @param defStyleRes A resource identifier of a style resource that 3658 * supplies default values for the view, used only if 3659 * defStyleAttr is 0 or can not be found in the theme. Can be 0 3660 * to not look for defaults. 3661 * @see #View(Context, AttributeSet, int) 3662 */ 3663 public View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { 3664 this(context); 3665 3666 final TypedArray a = context.obtainStyledAttributes( 3667 attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes); 3668 3669 if (mDebugViewAttributes) { 3670 saveAttributeData(attrs, a); 3671 } 3672 3673 Drawable background = null; 3674 3675 int leftPadding = -1; 3676 int topPadding = -1; 3677 int rightPadding = -1; 3678 int bottomPadding = -1; 3679 int startPadding = UNDEFINED_PADDING; 3680 int endPadding = UNDEFINED_PADDING; 3681 3682 int padding = -1; 3683 3684 int viewFlagValues = 0; 3685 int viewFlagMasks = 0; 3686 3687 boolean setScrollContainer = false; 3688 3689 int x = 0; 3690 int y = 0; 3691 3692 float tx = 0; 3693 float ty = 0; 3694 float tz = 0; 3695 float elevation = 0; 3696 float rotation = 0; 3697 float rotationX = 0; 3698 float rotationY = 0; 3699 float sx = 1f; 3700 float sy = 1f; 3701 boolean transformSet = false; 3702 3703 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 3704 int overScrollMode = mOverScrollMode; 3705 boolean initializeScrollbars = false; 3706 3707 boolean startPaddingDefined = false; 3708 boolean endPaddingDefined = false; 3709 boolean leftPaddingDefined = false; 3710 boolean rightPaddingDefined = false; 3711 3712 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3713 3714 final int N = a.getIndexCount(); 3715 for (int i = 0; i < N; i++) { 3716 int attr = a.getIndex(i); 3717 switch (attr) { 3718 case com.android.internal.R.styleable.View_background: 3719 background = a.getDrawable(attr); 3720 break; 3721 case com.android.internal.R.styleable.View_padding: 3722 padding = a.getDimensionPixelSize(attr, -1); 3723 mUserPaddingLeftInitial = padding; 3724 mUserPaddingRightInitial = padding; 3725 leftPaddingDefined = true; 3726 rightPaddingDefined = true; 3727 break; 3728 case com.android.internal.R.styleable.View_paddingLeft: 3729 leftPadding = a.getDimensionPixelSize(attr, -1); 3730 mUserPaddingLeftInitial = leftPadding; 3731 leftPaddingDefined = true; 3732 break; 3733 case com.android.internal.R.styleable.View_paddingTop: 3734 topPadding = a.getDimensionPixelSize(attr, -1); 3735 break; 3736 case com.android.internal.R.styleable.View_paddingRight: 3737 rightPadding = a.getDimensionPixelSize(attr, -1); 3738 mUserPaddingRightInitial = rightPadding; 3739 rightPaddingDefined = true; 3740 break; 3741 case com.android.internal.R.styleable.View_paddingBottom: 3742 bottomPadding = a.getDimensionPixelSize(attr, -1); 3743 break; 3744 case com.android.internal.R.styleable.View_paddingStart: 3745 startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3746 startPaddingDefined = (startPadding != UNDEFINED_PADDING); 3747 break; 3748 case com.android.internal.R.styleable.View_paddingEnd: 3749 endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3750 endPaddingDefined = (endPadding != UNDEFINED_PADDING); 3751 break; 3752 case com.android.internal.R.styleable.View_scrollX: 3753 x = a.getDimensionPixelOffset(attr, 0); 3754 break; 3755 case com.android.internal.R.styleable.View_scrollY: 3756 y = a.getDimensionPixelOffset(attr, 0); 3757 break; 3758 case com.android.internal.R.styleable.View_alpha: 3759 setAlpha(a.getFloat(attr, 1f)); 3760 break; 3761 case com.android.internal.R.styleable.View_transformPivotX: 3762 setPivotX(a.getDimensionPixelOffset(attr, 0)); 3763 break; 3764 case com.android.internal.R.styleable.View_transformPivotY: 3765 setPivotY(a.getDimensionPixelOffset(attr, 0)); 3766 break; 3767 case com.android.internal.R.styleable.View_translationX: 3768 tx = a.getDimensionPixelOffset(attr, 0); 3769 transformSet = true; 3770 break; 3771 case com.android.internal.R.styleable.View_translationY: 3772 ty = a.getDimensionPixelOffset(attr, 0); 3773 transformSet = true; 3774 break; 3775 case com.android.internal.R.styleable.View_translationZ: 3776 tz = a.getDimensionPixelOffset(attr, 0); 3777 transformSet = true; 3778 break; 3779 case com.android.internal.R.styleable.View_elevation: 3780 elevation = a.getDimensionPixelOffset(attr, 0); 3781 transformSet = true; 3782 break; 3783 case com.android.internal.R.styleable.View_rotation: 3784 rotation = a.getFloat(attr, 0); 3785 transformSet = true; 3786 break; 3787 case com.android.internal.R.styleable.View_rotationX: 3788 rotationX = a.getFloat(attr, 0); 3789 transformSet = true; 3790 break; 3791 case com.android.internal.R.styleable.View_rotationY: 3792 rotationY = a.getFloat(attr, 0); 3793 transformSet = true; 3794 break; 3795 case com.android.internal.R.styleable.View_scaleX: 3796 sx = a.getFloat(attr, 1f); 3797 transformSet = true; 3798 break; 3799 case com.android.internal.R.styleable.View_scaleY: 3800 sy = a.getFloat(attr, 1f); 3801 transformSet = true; 3802 break; 3803 case com.android.internal.R.styleable.View_id: 3804 mID = a.getResourceId(attr, NO_ID); 3805 break; 3806 case com.android.internal.R.styleable.View_tag: 3807 mTag = a.getText(attr); 3808 break; 3809 case com.android.internal.R.styleable.View_fitsSystemWindows: 3810 if (a.getBoolean(attr, false)) { 3811 viewFlagValues |= FITS_SYSTEM_WINDOWS; 3812 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 3813 } 3814 break; 3815 case com.android.internal.R.styleable.View_focusable: 3816 if (a.getBoolean(attr, false)) { 3817 viewFlagValues |= FOCUSABLE; 3818 viewFlagMasks |= FOCUSABLE_MASK; 3819 } 3820 break; 3821 case com.android.internal.R.styleable.View_focusableInTouchMode: 3822 if (a.getBoolean(attr, false)) { 3823 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 3824 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 3825 } 3826 break; 3827 case com.android.internal.R.styleable.View_clickable: 3828 if (a.getBoolean(attr, false)) { 3829 viewFlagValues |= CLICKABLE; 3830 viewFlagMasks |= CLICKABLE; 3831 } 3832 break; 3833 case com.android.internal.R.styleable.View_longClickable: 3834 if (a.getBoolean(attr, false)) { 3835 viewFlagValues |= LONG_CLICKABLE; 3836 viewFlagMasks |= LONG_CLICKABLE; 3837 } 3838 break; 3839 case com.android.internal.R.styleable.View_saveEnabled: 3840 if (!a.getBoolean(attr, true)) { 3841 viewFlagValues |= SAVE_DISABLED; 3842 viewFlagMasks |= SAVE_DISABLED_MASK; 3843 } 3844 break; 3845 case com.android.internal.R.styleable.View_duplicateParentState: 3846 if (a.getBoolean(attr, false)) { 3847 viewFlagValues |= DUPLICATE_PARENT_STATE; 3848 viewFlagMasks |= DUPLICATE_PARENT_STATE; 3849 } 3850 break; 3851 case com.android.internal.R.styleable.View_visibility: 3852 final int visibility = a.getInt(attr, 0); 3853 if (visibility != 0) { 3854 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 3855 viewFlagMasks |= VISIBILITY_MASK; 3856 } 3857 break; 3858 case com.android.internal.R.styleable.View_layoutDirection: 3859 // Clear any layout direction flags (included resolved bits) already set 3860 mPrivateFlags2 &= 3861 ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK); 3862 // Set the layout direction flags depending on the value of the attribute 3863 final int layoutDirection = a.getInt(attr, -1); 3864 final int value = (layoutDirection != -1) ? 3865 LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT; 3866 mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT); 3867 break; 3868 case com.android.internal.R.styleable.View_drawingCacheQuality: 3869 final int cacheQuality = a.getInt(attr, 0); 3870 if (cacheQuality != 0) { 3871 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 3872 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 3873 } 3874 break; 3875 case com.android.internal.R.styleable.View_contentDescription: 3876 setContentDescription(a.getString(attr)); 3877 break; 3878 case com.android.internal.R.styleable.View_labelFor: 3879 setLabelFor(a.getResourceId(attr, NO_ID)); 3880 break; 3881 case com.android.internal.R.styleable.View_soundEffectsEnabled: 3882 if (!a.getBoolean(attr, true)) { 3883 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 3884 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 3885 } 3886 break; 3887 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 3888 if (!a.getBoolean(attr, true)) { 3889 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 3890 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 3891 } 3892 break; 3893 case R.styleable.View_scrollbars: 3894 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 3895 if (scrollbars != SCROLLBARS_NONE) { 3896 viewFlagValues |= scrollbars; 3897 viewFlagMasks |= SCROLLBARS_MASK; 3898 initializeScrollbars = true; 3899 } 3900 break; 3901 //noinspection deprecation 3902 case R.styleable.View_fadingEdge: 3903 if (targetSdkVersion >= ICE_CREAM_SANDWICH) { 3904 // Ignore the attribute starting with ICS 3905 break; 3906 } 3907 // With builds < ICS, fall through and apply fading edges 3908 case R.styleable.View_requiresFadingEdge: 3909 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 3910 if (fadingEdge != FADING_EDGE_NONE) { 3911 viewFlagValues |= fadingEdge; 3912 viewFlagMasks |= FADING_EDGE_MASK; 3913 initializeFadingEdgeInternal(a); 3914 } 3915 break; 3916 case R.styleable.View_scrollbarStyle: 3917 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 3918 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3919 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 3920 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 3921 } 3922 break; 3923 case R.styleable.View_isScrollContainer: 3924 setScrollContainer = true; 3925 if (a.getBoolean(attr, false)) { 3926 setScrollContainer(true); 3927 } 3928 break; 3929 case com.android.internal.R.styleable.View_keepScreenOn: 3930 if (a.getBoolean(attr, false)) { 3931 viewFlagValues |= KEEP_SCREEN_ON; 3932 viewFlagMasks |= KEEP_SCREEN_ON; 3933 } 3934 break; 3935 case R.styleable.View_filterTouchesWhenObscured: 3936 if (a.getBoolean(attr, false)) { 3937 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 3938 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 3939 } 3940 break; 3941 case R.styleable.View_nextFocusLeft: 3942 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 3943 break; 3944 case R.styleable.View_nextFocusRight: 3945 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 3946 break; 3947 case R.styleable.View_nextFocusUp: 3948 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 3949 break; 3950 case R.styleable.View_nextFocusDown: 3951 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 3952 break; 3953 case R.styleable.View_nextFocusForward: 3954 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 3955 break; 3956 case R.styleable.View_minWidth: 3957 mMinWidth = a.getDimensionPixelSize(attr, 0); 3958 break; 3959 case R.styleable.View_minHeight: 3960 mMinHeight = a.getDimensionPixelSize(attr, 0); 3961 break; 3962 case R.styleable.View_onClick: 3963 if (context.isRestricted()) { 3964 throw new IllegalStateException("The android:onClick attribute cannot " 3965 + "be used within a restricted context"); 3966 } 3967 3968 final String handlerName = a.getString(attr); 3969 if (handlerName != null) { 3970 setOnClickListener(new OnClickListener() { 3971 private Method mHandler; 3972 3973 public void onClick(View v) { 3974 if (mHandler == null) { 3975 try { 3976 mHandler = getContext().getClass().getMethod(handlerName, 3977 View.class); 3978 } catch (NoSuchMethodException e) { 3979 int id = getId(); 3980 String idText = id == NO_ID ? "" : " with id '" 3981 + getContext().getResources().getResourceEntryName( 3982 id) + "'"; 3983 throw new IllegalStateException("Could not find a method " + 3984 handlerName + "(View) in the activity " 3985 + getContext().getClass() + " for onClick handler" 3986 + " on view " + View.this.getClass() + idText, e); 3987 } 3988 } 3989 3990 try { 3991 mHandler.invoke(getContext(), View.this); 3992 } catch (IllegalAccessException e) { 3993 throw new IllegalStateException("Could not execute non " 3994 + "public method of the activity", e); 3995 } catch (InvocationTargetException e) { 3996 throw new IllegalStateException("Could not execute " 3997 + "method of the activity", e); 3998 } 3999 } 4000 }); 4001 } 4002 break; 4003 case R.styleable.View_overScrollMode: 4004 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 4005 break; 4006 case R.styleable.View_verticalScrollbarPosition: 4007 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 4008 break; 4009 case R.styleable.View_layerType: 4010 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 4011 break; 4012 case R.styleable.View_textDirection: 4013 // Clear any text direction flag already set 4014 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 4015 // Set the text direction flags depending on the value of the attribute 4016 final int textDirection = a.getInt(attr, -1); 4017 if (textDirection != -1) { 4018 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection]; 4019 } 4020 break; 4021 case R.styleable.View_textAlignment: 4022 // Clear any text alignment flag already set 4023 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 4024 // Set the text alignment flag depending on the value of the attribute 4025 final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT); 4026 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment]; 4027 break; 4028 case R.styleable.View_importantForAccessibility: 4029 setImportantForAccessibility(a.getInt(attr, 4030 IMPORTANT_FOR_ACCESSIBILITY_DEFAULT)); 4031 break; 4032 case R.styleable.View_accessibilityLiveRegion: 4033 setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT)); 4034 break; 4035 case R.styleable.View_transitionName: 4036 setTransitionName(a.getString(attr)); 4037 break; 4038 case R.styleable.View_nestedScrollingEnabled: 4039 setNestedScrollingEnabled(a.getBoolean(attr, false)); 4040 break; 4041 case R.styleable.View_stateListAnimator: 4042 setStateListAnimator(AnimatorInflater.loadStateListAnimator(context, 4043 a.getResourceId(attr, 0))); 4044 break; 4045 case R.styleable.View_backgroundTint: 4046 // This will get applied later during setBackground(). 4047 mBackgroundTintList = a.getColorStateList(R.styleable.View_backgroundTint); 4048 mHasBackgroundTint = true; 4049 break; 4050 case R.styleable.View_backgroundTintMode: 4051 // This will get applied later during setBackground(). 4052 mBackgroundTintMode = Drawable.parseTintMode(a.getInt( 4053 R.styleable.View_backgroundTintMode, -1), mBackgroundTintMode); 4054 break; 4055 case R.styleable.View_outlineProvider: 4056 setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider, 4057 PROVIDER_BACKGROUND)); 4058 break; 4059 } 4060 } 4061 4062 setOverScrollMode(overScrollMode); 4063 4064 // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet 4065 // the resolved layout direction). Those cached values will be used later during padding 4066 // resolution. 4067 mUserPaddingStart = startPadding; 4068 mUserPaddingEnd = endPadding; 4069 4070 if (background != null) { 4071 setBackground(background); 4072 } 4073 4074 // setBackground above will record that padding is currently provided by the background. 4075 // If we have padding specified via xml, record that here instead and use it. 4076 mLeftPaddingDefined = leftPaddingDefined; 4077 mRightPaddingDefined = rightPaddingDefined; 4078 4079 if (padding >= 0) { 4080 leftPadding = padding; 4081 topPadding = padding; 4082 rightPadding = padding; 4083 bottomPadding = padding; 4084 mUserPaddingLeftInitial = padding; 4085 mUserPaddingRightInitial = padding; 4086 } 4087 4088 if (isRtlCompatibilityMode()) { 4089 // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case. 4090 // left / right padding are used if defined (meaning here nothing to do). If they are not 4091 // defined and start / end padding are defined (e.g. in Frameworks resources), then we use 4092 // start / end and resolve them as left / right (layout direction is not taken into account). 4093 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4094 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4095 // defined. 4096 if (!mLeftPaddingDefined && startPaddingDefined) { 4097 leftPadding = startPadding; 4098 } 4099 mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial; 4100 if (!mRightPaddingDefined && endPaddingDefined) { 4101 rightPadding = endPadding; 4102 } 4103 mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial; 4104 } else { 4105 // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right 4106 // values defined. Otherwise, left /right values are used. 4107 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4108 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4109 // defined. 4110 final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined; 4111 4112 if (mLeftPaddingDefined && !hasRelativePadding) { 4113 mUserPaddingLeftInitial = leftPadding; 4114 } 4115 if (mRightPaddingDefined && !hasRelativePadding) { 4116 mUserPaddingRightInitial = rightPadding; 4117 } 4118 } 4119 4120 internalSetPadding( 4121 mUserPaddingLeftInitial, 4122 topPadding >= 0 ? topPadding : mPaddingTop, 4123 mUserPaddingRightInitial, 4124 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 4125 4126 if (viewFlagMasks != 0) { 4127 setFlags(viewFlagValues, viewFlagMasks); 4128 } 4129 4130 if (initializeScrollbars) { 4131 initializeScrollbarsInternal(a); 4132 } 4133 4134 a.recycle(); 4135 4136 // Needs to be called after mViewFlags is set 4137 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 4138 recomputePadding(); 4139 } 4140 4141 if (x != 0 || y != 0) { 4142 scrollTo(x, y); 4143 } 4144 4145 if (transformSet) { 4146 setTranslationX(tx); 4147 setTranslationY(ty); 4148 setTranslationZ(tz); 4149 setElevation(elevation); 4150 setRotation(rotation); 4151 setRotationX(rotationX); 4152 setRotationY(rotationY); 4153 setScaleX(sx); 4154 setScaleY(sy); 4155 } 4156 4157 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 4158 setScrollContainer(true); 4159 } 4160 4161 computeOpaqueFlags(); 4162 } 4163 4164 /** 4165 * Non-public constructor for use in testing 4166 */ 4167 View() { 4168 mResources = null; 4169 mRenderNode = RenderNode.create(getClass().getName(), this); 4170 } 4171 4172 private static SparseArray<String> getAttributeMap() { 4173 if (mAttributeMap == null) { 4174 mAttributeMap = new SparseArray<String>(); 4175 } 4176 return mAttributeMap; 4177 } 4178 4179 private void saveAttributeData(AttributeSet attrs, TypedArray a) { 4180 int length = ((attrs == null ? 0 : attrs.getAttributeCount()) + a.getIndexCount()) * 2; 4181 mAttributes = new String[length]; 4182 4183 int i = 0; 4184 if (attrs != null) { 4185 for (i = 0; i < attrs.getAttributeCount(); i += 2) { 4186 mAttributes[i] = attrs.getAttributeName(i); 4187 mAttributes[i + 1] = attrs.getAttributeValue(i); 4188 } 4189 4190 } 4191 4192 SparseArray<String> attributeMap = getAttributeMap(); 4193 for (int j = 0; j < a.length(); ++j) { 4194 if (a.hasValue(j)) { 4195 try { 4196 int resourceId = a.getResourceId(j, 0); 4197 if (resourceId == 0) { 4198 continue; 4199 } 4200 4201 String resourceName = attributeMap.get(resourceId); 4202 if (resourceName == null) { 4203 resourceName = a.getResources().getResourceName(resourceId); 4204 attributeMap.put(resourceId, resourceName); 4205 } 4206 4207 mAttributes[i] = resourceName; 4208 mAttributes[i + 1] = a.getText(j).toString(); 4209 i += 2; 4210 } catch (Resources.NotFoundException e) { 4211 // if we can't get the resource name, we just ignore it 4212 } 4213 } 4214 } 4215 } 4216 4217 public String toString() { 4218 StringBuilder out = new StringBuilder(128); 4219 out.append(getClass().getName()); 4220 out.append('{'); 4221 out.append(Integer.toHexString(System.identityHashCode(this))); 4222 out.append(' '); 4223 switch (mViewFlags&VISIBILITY_MASK) { 4224 case VISIBLE: out.append('V'); break; 4225 case INVISIBLE: out.append('I'); break; 4226 case GONE: out.append('G'); break; 4227 default: out.append('.'); break; 4228 } 4229 out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.'); 4230 out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.'); 4231 out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D'); 4232 out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.'); 4233 out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.'); 4234 out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.'); 4235 out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.'); 4236 out.append(' '); 4237 out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.'); 4238 out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.'); 4239 out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.'); 4240 if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) { 4241 out.append('p'); 4242 } else { 4243 out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.'); 4244 } 4245 out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.'); 4246 out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.'); 4247 out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.'); 4248 out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.'); 4249 out.append(' '); 4250 out.append(mLeft); 4251 out.append(','); 4252 out.append(mTop); 4253 out.append('-'); 4254 out.append(mRight); 4255 out.append(','); 4256 out.append(mBottom); 4257 final int id = getId(); 4258 if (id != NO_ID) { 4259 out.append(" #"); 4260 out.append(Integer.toHexString(id)); 4261 final Resources r = mResources; 4262 if (Resources.resourceHasPackage(id) && r != null) { 4263 try { 4264 String pkgname; 4265 switch (id&0xff000000) { 4266 case 0x7f000000: 4267 pkgname="app"; 4268 break; 4269 case 0x01000000: 4270 pkgname="android"; 4271 break; 4272 default: 4273 pkgname = r.getResourcePackageName(id); 4274 break; 4275 } 4276 String typename = r.getResourceTypeName(id); 4277 String entryname = r.getResourceEntryName(id); 4278 out.append(" "); 4279 out.append(pkgname); 4280 out.append(":"); 4281 out.append(typename); 4282 out.append("/"); 4283 out.append(entryname); 4284 } catch (Resources.NotFoundException e) { 4285 } 4286 } 4287 } 4288 out.append("}"); 4289 return out.toString(); 4290 } 4291 4292 /** 4293 * <p> 4294 * Initializes the fading edges from a given set of styled attributes. This 4295 * method should be called by subclasses that need fading edges and when an 4296 * instance of these subclasses is created programmatically rather than 4297 * being inflated from XML. This method is automatically called when the XML 4298 * is inflated. 4299 * </p> 4300 * 4301 * @param a the styled attributes set to initialize the fading edges from 4302 * 4303 * @removed 4304 */ 4305 protected void initializeFadingEdge(TypedArray a) { 4306 // This method probably shouldn't have been included in the SDK to begin with. 4307 // It relies on 'a' having been initialized using an attribute filter array that is 4308 // not publicly available to the SDK. The old method has been renamed 4309 // to initializeFadingEdgeInternal and hidden for framework use only; 4310 // this one initializes using defaults to make it safe to call for apps. 4311 4312 TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View); 4313 4314 initializeFadingEdgeInternal(arr); 4315 4316 arr.recycle(); 4317 } 4318 4319 /** 4320 * <p> 4321 * Initializes the fading edges from a given set of styled attributes. This 4322 * method should be called by subclasses that need fading edges and when an 4323 * instance of these subclasses is created programmatically rather than 4324 * being inflated from XML. This method is automatically called when the XML 4325 * is inflated. 4326 * </p> 4327 * 4328 * @param a the styled attributes set to initialize the fading edges from 4329 * @hide This is the real method; the public one is shimmed to be safe to call from apps. 4330 */ 4331 protected void initializeFadingEdgeInternal(TypedArray a) { 4332 initScrollCache(); 4333 4334 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 4335 R.styleable.View_fadingEdgeLength, 4336 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 4337 } 4338 4339 /** 4340 * Returns the size of the vertical faded edges used to indicate that more 4341 * content in this view is visible. 4342 * 4343 * @return The size in pixels of the vertical faded edge or 0 if vertical 4344 * faded edges are not enabled for this view. 4345 * @attr ref android.R.styleable#View_fadingEdgeLength 4346 */ 4347 public int getVerticalFadingEdgeLength() { 4348 if (isVerticalFadingEdgeEnabled()) { 4349 ScrollabilityCache cache = mScrollCache; 4350 if (cache != null) { 4351 return cache.fadingEdgeLength; 4352 } 4353 } 4354 return 0; 4355 } 4356 4357 /** 4358 * Set the size of the faded edge used to indicate that more content in this 4359 * view is available. Will not change whether the fading edge is enabled; use 4360 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 4361 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 4362 * for the vertical or horizontal fading edges. 4363 * 4364 * @param length The size in pixels of the faded edge used to indicate that more 4365 * content in this view is visible. 4366 */ 4367 public void setFadingEdgeLength(int length) { 4368 initScrollCache(); 4369 mScrollCache.fadingEdgeLength = length; 4370 } 4371 4372 /** 4373 * Returns the size of the horizontal faded edges used to indicate that more 4374 * content in this view is visible. 4375 * 4376 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 4377 * faded edges are not enabled for this view. 4378 * @attr ref android.R.styleable#View_fadingEdgeLength 4379 */ 4380 public int getHorizontalFadingEdgeLength() { 4381 if (isHorizontalFadingEdgeEnabled()) { 4382 ScrollabilityCache cache = mScrollCache; 4383 if (cache != null) { 4384 return cache.fadingEdgeLength; 4385 } 4386 } 4387 return 0; 4388 } 4389 4390 /** 4391 * Returns the width of the vertical scrollbar. 4392 * 4393 * @return The width in pixels of the vertical scrollbar or 0 if there 4394 * is no vertical scrollbar. 4395 */ 4396 public int getVerticalScrollbarWidth() { 4397 ScrollabilityCache cache = mScrollCache; 4398 if (cache != null) { 4399 ScrollBarDrawable scrollBar = cache.scrollBar; 4400 if (scrollBar != null) { 4401 int size = scrollBar.getSize(true); 4402 if (size <= 0) { 4403 size = cache.scrollBarSize; 4404 } 4405 return size; 4406 } 4407 return 0; 4408 } 4409 return 0; 4410 } 4411 4412 /** 4413 * Returns the height of the horizontal scrollbar. 4414 * 4415 * @return The height in pixels of the horizontal scrollbar or 0 if 4416 * there is no horizontal scrollbar. 4417 */ 4418 protected int getHorizontalScrollbarHeight() { 4419 ScrollabilityCache cache = mScrollCache; 4420 if (cache != null) { 4421 ScrollBarDrawable scrollBar = cache.scrollBar; 4422 if (scrollBar != null) { 4423 int size = scrollBar.getSize(false); 4424 if (size <= 0) { 4425 size = cache.scrollBarSize; 4426 } 4427 return size; 4428 } 4429 return 0; 4430 } 4431 return 0; 4432 } 4433 4434 /** 4435 * <p> 4436 * Initializes the scrollbars from a given set of styled attributes. This 4437 * method should be called by subclasses that need scrollbars and when an 4438 * instance of these subclasses is created programmatically rather than 4439 * being inflated from XML. This method is automatically called when the XML 4440 * is inflated. 4441 * </p> 4442 * 4443 * @param a the styled attributes set to initialize the scrollbars from 4444 * 4445 * @removed 4446 */ 4447 protected void initializeScrollbars(TypedArray a) { 4448 // It's not safe to use this method from apps. The parameter 'a' must have been obtained 4449 // using the View filter array which is not available to the SDK. As such, internal 4450 // framework usage now uses initializeScrollbarsInternal and we grab a default 4451 // TypedArray with the right filter instead here. 4452 TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View); 4453 4454 initializeScrollbarsInternal(arr); 4455 4456 // We ignored the method parameter. Recycle the one we actually did use. 4457 arr.recycle(); 4458 } 4459 4460 /** 4461 * <p> 4462 * Initializes the scrollbars from a given set of styled attributes. This 4463 * method should be called by subclasses that need scrollbars and when an 4464 * instance of these subclasses is created programmatically rather than 4465 * being inflated from XML. This method is automatically called when the XML 4466 * is inflated. 4467 * </p> 4468 * 4469 * @param a the styled attributes set to initialize the scrollbars from 4470 * @hide 4471 */ 4472 protected void initializeScrollbarsInternal(TypedArray a) { 4473 initScrollCache(); 4474 4475 final ScrollabilityCache scrollabilityCache = mScrollCache; 4476 4477 if (scrollabilityCache.scrollBar == null) { 4478 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 4479 } 4480 4481 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 4482 4483 if (!fadeScrollbars) { 4484 scrollabilityCache.state = ScrollabilityCache.ON; 4485 } 4486 scrollabilityCache.fadeScrollBars = fadeScrollbars; 4487 4488 4489 scrollabilityCache.scrollBarFadeDuration = a.getInt( 4490 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 4491 .getScrollBarFadeDuration()); 4492 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 4493 R.styleable.View_scrollbarDefaultDelayBeforeFade, 4494 ViewConfiguration.getScrollDefaultDelay()); 4495 4496 4497 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 4498 com.android.internal.R.styleable.View_scrollbarSize, 4499 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 4500 4501 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 4502 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 4503 4504 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 4505 if (thumb != null) { 4506 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 4507 } 4508 4509 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 4510 false); 4511 if (alwaysDraw) { 4512 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 4513 } 4514 4515 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 4516 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 4517 4518 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 4519 if (thumb != null) { 4520 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 4521 } 4522 4523 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 4524 false); 4525 if (alwaysDraw) { 4526 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 4527 } 4528 4529 // Apply layout direction to the new Drawables if needed 4530 final int layoutDirection = getLayoutDirection(); 4531 if (track != null) { 4532 track.setLayoutDirection(layoutDirection); 4533 } 4534 if (thumb != null) { 4535 thumb.setLayoutDirection(layoutDirection); 4536 } 4537 4538 // Re-apply user/background padding so that scrollbar(s) get added 4539 resolvePadding(); 4540 } 4541 4542 /** 4543 * <p> 4544 * Initalizes the scrollability cache if necessary. 4545 * </p> 4546 */ 4547 private void initScrollCache() { 4548 if (mScrollCache == null) { 4549 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 4550 } 4551 } 4552 4553 private ScrollabilityCache getScrollCache() { 4554 initScrollCache(); 4555 return mScrollCache; 4556 } 4557 4558 /** 4559 * Set the position of the vertical scroll bar. Should be one of 4560 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 4561 * {@link #SCROLLBAR_POSITION_RIGHT}. 4562 * 4563 * @param position Where the vertical scroll bar should be positioned. 4564 */ 4565 public void setVerticalScrollbarPosition(int position) { 4566 if (mVerticalScrollbarPosition != position) { 4567 mVerticalScrollbarPosition = position; 4568 computeOpaqueFlags(); 4569 resolvePadding(); 4570 } 4571 } 4572 4573 /** 4574 * @return The position where the vertical scroll bar will show, if applicable. 4575 * @see #setVerticalScrollbarPosition(int) 4576 */ 4577 public int getVerticalScrollbarPosition() { 4578 return mVerticalScrollbarPosition; 4579 } 4580 4581 ListenerInfo getListenerInfo() { 4582 if (mListenerInfo != null) { 4583 return mListenerInfo; 4584 } 4585 mListenerInfo = new ListenerInfo(); 4586 return mListenerInfo; 4587 } 4588 4589 /** 4590 * Register a callback to be invoked when focus of this view changed. 4591 * 4592 * @param l The callback that will run. 4593 */ 4594 public void setOnFocusChangeListener(OnFocusChangeListener l) { 4595 getListenerInfo().mOnFocusChangeListener = l; 4596 } 4597 4598 /** 4599 * Add a listener that will be called when the bounds of the view change due to 4600 * layout processing. 4601 * 4602 * @param listener The listener that will be called when layout bounds change. 4603 */ 4604 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 4605 ListenerInfo li = getListenerInfo(); 4606 if (li.mOnLayoutChangeListeners == null) { 4607 li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 4608 } 4609 if (!li.mOnLayoutChangeListeners.contains(listener)) { 4610 li.mOnLayoutChangeListeners.add(listener); 4611 } 4612 } 4613 4614 /** 4615 * Remove a listener for layout changes. 4616 * 4617 * @param listener The listener for layout bounds change. 4618 */ 4619 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 4620 ListenerInfo li = mListenerInfo; 4621 if (li == null || li.mOnLayoutChangeListeners == null) { 4622 return; 4623 } 4624 li.mOnLayoutChangeListeners.remove(listener); 4625 } 4626 4627 /** 4628 * Add a listener for attach state changes. 4629 * 4630 * This listener will be called whenever this view is attached or detached 4631 * from a window. Remove the listener using 4632 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 4633 * 4634 * @param listener Listener to attach 4635 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 4636 */ 4637 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4638 ListenerInfo li = getListenerInfo(); 4639 if (li.mOnAttachStateChangeListeners == null) { 4640 li.mOnAttachStateChangeListeners 4641 = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 4642 } 4643 li.mOnAttachStateChangeListeners.add(listener); 4644 } 4645 4646 /** 4647 * Remove a listener for attach state changes. The listener will receive no further 4648 * notification of window attach/detach events. 4649 * 4650 * @param listener Listener to remove 4651 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 4652 */ 4653 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4654 ListenerInfo li = mListenerInfo; 4655 if (li == null || li.mOnAttachStateChangeListeners == null) { 4656 return; 4657 } 4658 li.mOnAttachStateChangeListeners.remove(listener); 4659 } 4660 4661 /** 4662 * Returns the focus-change callback registered for this view. 4663 * 4664 * @return The callback, or null if one is not registered. 4665 */ 4666 public OnFocusChangeListener getOnFocusChangeListener() { 4667 ListenerInfo li = mListenerInfo; 4668 return li != null ? li.mOnFocusChangeListener : null; 4669 } 4670 4671 /** 4672 * Register a callback to be invoked when this view is clicked. If this view is not 4673 * clickable, it becomes clickable. 4674 * 4675 * @param l The callback that will run 4676 * 4677 * @see #setClickable(boolean) 4678 */ 4679 public void setOnClickListener(OnClickListener l) { 4680 if (!isClickable()) { 4681 setClickable(true); 4682 } 4683 getListenerInfo().mOnClickListener = l; 4684 } 4685 4686 /** 4687 * Return whether this view has an attached OnClickListener. Returns 4688 * true if there is a listener, false if there is none. 4689 */ 4690 public boolean hasOnClickListeners() { 4691 ListenerInfo li = mListenerInfo; 4692 return (li != null && li.mOnClickListener != null); 4693 } 4694 4695 /** 4696 * Register a callback to be invoked when this view is clicked and held. If this view is not 4697 * long clickable, it becomes long clickable. 4698 * 4699 * @param l The callback that will run 4700 * 4701 * @see #setLongClickable(boolean) 4702 */ 4703 public void setOnLongClickListener(OnLongClickListener l) { 4704 if (!isLongClickable()) { 4705 setLongClickable(true); 4706 } 4707 getListenerInfo().mOnLongClickListener = l; 4708 } 4709 4710 /** 4711 * Register a callback to be invoked when the context menu for this view is 4712 * being built. If this view is not long clickable, it becomes long clickable. 4713 * 4714 * @param l The callback that will run 4715 * 4716 */ 4717 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 4718 if (!isLongClickable()) { 4719 setLongClickable(true); 4720 } 4721 getListenerInfo().mOnCreateContextMenuListener = l; 4722 } 4723 4724 /** 4725 * Call this view's OnClickListener, if it is defined. Performs all normal 4726 * actions associated with clicking: reporting accessibility event, playing 4727 * a sound, etc. 4728 * 4729 * @return True there was an assigned OnClickListener that was called, false 4730 * otherwise is returned. 4731 */ 4732 public boolean performClick() { 4733 final boolean result; 4734 final ListenerInfo li = mListenerInfo; 4735 if (li != null && li.mOnClickListener != null) { 4736 playSoundEffect(SoundEffectConstants.CLICK); 4737 li.mOnClickListener.onClick(this); 4738 result = true; 4739 } else { 4740 result = false; 4741 } 4742 4743 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 4744 return result; 4745 } 4746 4747 /** 4748 * Directly call any attached OnClickListener. Unlike {@link #performClick()}, 4749 * this only calls the listener, and does not do any associated clicking 4750 * actions like reporting an accessibility event. 4751 * 4752 * @return True there was an assigned OnClickListener that was called, false 4753 * otherwise is returned. 4754 */ 4755 public boolean callOnClick() { 4756 ListenerInfo li = mListenerInfo; 4757 if (li != null && li.mOnClickListener != null) { 4758 li.mOnClickListener.onClick(this); 4759 return true; 4760 } 4761 return false; 4762 } 4763 4764 /** 4765 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the 4766 * OnLongClickListener did not consume the event. 4767 * 4768 * @return True if one of the above receivers consumed the event, false otherwise. 4769 */ 4770 public boolean performLongClick() { 4771 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 4772 4773 boolean handled = false; 4774 ListenerInfo li = mListenerInfo; 4775 if (li != null && li.mOnLongClickListener != null) { 4776 handled = li.mOnLongClickListener.onLongClick(View.this); 4777 } 4778 if (!handled) { 4779 handled = showContextMenu(); 4780 } 4781 if (handled) { 4782 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 4783 } 4784 return handled; 4785 } 4786 4787 /** 4788 * Performs button-related actions during a touch down event. 4789 * 4790 * @param event The event. 4791 * @return True if the down was consumed. 4792 * 4793 * @hide 4794 */ 4795 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 4796 if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 4797 if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) { 4798 return true; 4799 } 4800 } 4801 return false; 4802 } 4803 4804 /** 4805 * Bring up the context menu for this view. 4806 * 4807 * @return Whether a context menu was displayed. 4808 */ 4809 public boolean showContextMenu() { 4810 return getParent().showContextMenuForChild(this); 4811 } 4812 4813 /** 4814 * Bring up the context menu for this view, referring to the item under the specified point. 4815 * 4816 * @param x The referenced x coordinate. 4817 * @param y The referenced y coordinate. 4818 * @param metaState The keyboard modifiers that were pressed. 4819 * @return Whether a context menu was displayed. 4820 * 4821 * @hide 4822 */ 4823 public boolean showContextMenu(float x, float y, int metaState) { 4824 return showContextMenu(); 4825 } 4826 4827 /** 4828 * Start an action mode. 4829 * 4830 * @param callback Callback that will control the lifecycle of the action mode 4831 * @return The new action mode if it is started, null otherwise 4832 * 4833 * @see ActionMode 4834 */ 4835 public ActionMode startActionMode(ActionMode.Callback callback) { 4836 ViewParent parent = getParent(); 4837 if (parent == null) return null; 4838 return parent.startActionModeForChild(this, callback); 4839 } 4840 4841 /** 4842 * Register a callback to be invoked when a hardware key is pressed in this view. 4843 * Key presses in software input methods will generally not trigger the methods of 4844 * this listener. 4845 * @param l the key listener to attach to this view 4846 */ 4847 public void setOnKeyListener(OnKeyListener l) { 4848 getListenerInfo().mOnKeyListener = l; 4849 } 4850 4851 /** 4852 * Register a callback to be invoked when a touch event is sent to this view. 4853 * @param l the touch listener to attach to this view 4854 */ 4855 public void setOnTouchListener(OnTouchListener l) { 4856 getListenerInfo().mOnTouchListener = l; 4857 } 4858 4859 /** 4860 * Register a callback to be invoked when a generic motion event is sent to this view. 4861 * @param l the generic motion listener to attach to this view 4862 */ 4863 public void setOnGenericMotionListener(OnGenericMotionListener l) { 4864 getListenerInfo().mOnGenericMotionListener = l; 4865 } 4866 4867 /** 4868 * Register a callback to be invoked when a hover event is sent to this view. 4869 * @param l the hover listener to attach to this view 4870 */ 4871 public void setOnHoverListener(OnHoverListener l) { 4872 getListenerInfo().mOnHoverListener = l; 4873 } 4874 4875 /** 4876 * Register a drag event listener callback object for this View. The parameter is 4877 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 4878 * View, the system calls the 4879 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 4880 * @param l An implementation of {@link android.view.View.OnDragListener}. 4881 */ 4882 public void setOnDragListener(OnDragListener l) { 4883 getListenerInfo().mOnDragListener = l; 4884 } 4885 4886 /** 4887 * Give this view focus. This will cause 4888 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 4889 * 4890 * Note: this does not check whether this {@link View} should get focus, it just 4891 * gives it focus no matter what. It should only be called internally by framework 4892 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 4893 * 4894 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 4895 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 4896 * focus moved when requestFocus() is called. It may not always 4897 * apply, in which case use the default View.FOCUS_DOWN. 4898 * @param previouslyFocusedRect The rectangle of the view that had focus 4899 * prior in this View's coordinate system. 4900 */ 4901 void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) { 4902 if (DBG) { 4903 System.out.println(this + " requestFocus()"); 4904 } 4905 4906 if ((mPrivateFlags & PFLAG_FOCUSED) == 0) { 4907 mPrivateFlags |= PFLAG_FOCUSED; 4908 4909 View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null; 4910 4911 if (mParent != null) { 4912 mParent.requestChildFocus(this, this); 4913 } 4914 4915 if (mAttachInfo != null) { 4916 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this); 4917 } 4918 4919 onFocusChanged(true, direction, previouslyFocusedRect); 4920 refreshDrawableState(); 4921 } 4922 } 4923 4924 /** 4925 * Populates <code>outRect</code> with the hotspot bounds. By default, 4926 * the hotspot bounds are identical to the screen bounds. 4927 * 4928 * @param outRect rect to populate with hotspot bounds 4929 * @hide Only for internal use by views and widgets. 4930 */ 4931 public void getHotspotBounds(Rect outRect) { 4932 final Drawable background = getBackground(); 4933 if (background != null) { 4934 background.getHotspotBounds(outRect); 4935 } else { 4936 getBoundsOnScreen(outRect); 4937 } 4938 } 4939 4940 /** 4941 * Request that a rectangle of this view be visible on the screen, 4942 * scrolling if necessary just enough. 4943 * 4944 * <p>A View should call this if it maintains some notion of which part 4945 * of its content is interesting. For example, a text editing view 4946 * should call this when its cursor moves. 4947 * 4948 * @param rectangle The rectangle. 4949 * @return Whether any parent scrolled. 4950 */ 4951 public boolean requestRectangleOnScreen(Rect rectangle) { 4952 return requestRectangleOnScreen(rectangle, false); 4953 } 4954 4955 /** 4956 * Request that a rectangle of this view be visible on the screen, 4957 * scrolling if necessary just enough. 4958 * 4959 * <p>A View should call this if it maintains some notion of which part 4960 * of its content is interesting. For example, a text editing view 4961 * should call this when its cursor moves. 4962 * 4963 * <p>When <code>immediate</code> is set to true, scrolling will not be 4964 * animated. 4965 * 4966 * @param rectangle The rectangle. 4967 * @param immediate True to forbid animated scrolling, false otherwise 4968 * @return Whether any parent scrolled. 4969 */ 4970 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 4971 if (mParent == null) { 4972 return false; 4973 } 4974 4975 View child = this; 4976 4977 RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF(); 4978 position.set(rectangle); 4979 4980 ViewParent parent = mParent; 4981 boolean scrolled = false; 4982 while (parent != null) { 4983 rectangle.set((int) position.left, (int) position.top, 4984 (int) position.right, (int) position.bottom); 4985 4986 scrolled |= parent.requestChildRectangleOnScreen(child, 4987 rectangle, immediate); 4988 4989 if (!child.hasIdentityMatrix()) { 4990 child.getMatrix().mapRect(position); 4991 } 4992 4993 position.offset(child.mLeft, child.mTop); 4994 4995 if (!(parent instanceof View)) { 4996 break; 4997 } 4998 4999 View parentView = (View) parent; 5000 5001 position.offset(-parentView.getScrollX(), -parentView.getScrollY()); 5002 5003 child = parentView; 5004 parent = child.getParent(); 5005 } 5006 5007 return scrolled; 5008 } 5009 5010 /** 5011 * Called when this view wants to give up focus. If focus is cleared 5012 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called. 5013 * <p> 5014 * <strong>Note:</strong> When a View clears focus the framework is trying 5015 * to give focus to the first focusable View from the top. Hence, if this 5016 * View is the first from the top that can take focus, then all callbacks 5017 * related to clearing focus will be invoked after wich the framework will 5018 * give focus to this view. 5019 * </p> 5020 */ 5021 public void clearFocus() { 5022 if (DBG) { 5023 System.out.println(this + " clearFocus()"); 5024 } 5025 5026 clearFocusInternal(null, true, true); 5027 } 5028 5029 /** 5030 * Clears focus from the view, optionally propagating the change up through 5031 * the parent hierarchy and requesting that the root view place new focus. 5032 * 5033 * @param propagate whether to propagate the change up through the parent 5034 * hierarchy 5035 * @param refocus when propagate is true, specifies whether to request the 5036 * root view place new focus 5037 */ 5038 void clearFocusInternal(View focused, boolean propagate, boolean refocus) { 5039 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 5040 mPrivateFlags &= ~PFLAG_FOCUSED; 5041 5042 if (propagate && mParent != null) { 5043 mParent.clearChildFocus(this); 5044 } 5045 5046 onFocusChanged(false, 0, null); 5047 refreshDrawableState(); 5048 5049 if (propagate && (!refocus || !rootViewRequestFocus())) { 5050 notifyGlobalFocusCleared(this); 5051 } 5052 } 5053 } 5054 5055 void notifyGlobalFocusCleared(View oldFocus) { 5056 if (oldFocus != null && mAttachInfo != null) { 5057 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null); 5058 } 5059 } 5060 5061 boolean rootViewRequestFocus() { 5062 final View root = getRootView(); 5063 return root != null && root.requestFocus(); 5064 } 5065 5066 /** 5067 * Called internally by the view system when a new view is getting focus. 5068 * This is what clears the old focus. 5069 * <p> 5070 * <b>NOTE:</b> The parent view's focused child must be updated manually 5071 * after calling this method. Otherwise, the view hierarchy may be left in 5072 * an inconstent state. 5073 */ 5074 void unFocus(View focused) { 5075 if (DBG) { 5076 System.out.println(this + " unFocus()"); 5077 } 5078 5079 clearFocusInternal(focused, false, false); 5080 } 5081 5082 /** 5083 * Returns true if this view has focus iteself, or is the ancestor of the 5084 * view that has focus. 5085 * 5086 * @return True if this view has or contains focus, false otherwise. 5087 */ 5088 @ViewDebug.ExportedProperty(category = "focus") 5089 public boolean hasFocus() { 5090 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 5091 } 5092 5093 /** 5094 * Returns true if this view is focusable or if it contains a reachable View 5095 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 5096 * is a View whose parents do not block descendants focus. 5097 * 5098 * Only {@link #VISIBLE} views are considered focusable. 5099 * 5100 * @return True if the view is focusable or if the view contains a focusable 5101 * View, false otherwise. 5102 * 5103 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 5104 * @see ViewGroup#getTouchscreenBlocksFocus() 5105 */ 5106 public boolean hasFocusable() { 5107 if (!isFocusableInTouchMode()) { 5108 for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) { 5109 final ViewGroup g = (ViewGroup) p; 5110 if (g.shouldBlockFocusForTouchscreen()) { 5111 return false; 5112 } 5113 } 5114 } 5115 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 5116 } 5117 5118 /** 5119 * Called by the view system when the focus state of this view changes. 5120 * When the focus change event is caused by directional navigation, direction 5121 * and previouslyFocusedRect provide insight into where the focus is coming from. 5122 * When overriding, be sure to call up through to the super class so that 5123 * the standard focus handling will occur. 5124 * 5125 * @param gainFocus True if the View has focus; false otherwise. 5126 * @param direction The direction focus has moved when requestFocus() 5127 * is called to give this view focus. Values are 5128 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 5129 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 5130 * It may not always apply, in which case use the default. 5131 * @param previouslyFocusedRect The rectangle, in this view's coordinate 5132 * system, of the previously focused view. If applicable, this will be 5133 * passed in as finer grained information about where the focus is coming 5134 * from (in addition to direction). Will be <code>null</code> otherwise. 5135 */ 5136 protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction, 5137 @Nullable Rect previouslyFocusedRect) { 5138 if (gainFocus) { 5139 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 5140 } else { 5141 notifyViewAccessibilityStateChangedIfNeeded( 5142 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 5143 } 5144 5145 InputMethodManager imm = InputMethodManager.peekInstance(); 5146 if (!gainFocus) { 5147 if (isPressed()) { 5148 setPressed(false); 5149 } 5150 if (imm != null && mAttachInfo != null 5151 && mAttachInfo.mHasWindowFocus) { 5152 imm.focusOut(this); 5153 } 5154 onFocusLost(); 5155 } else if (imm != null && mAttachInfo != null 5156 && mAttachInfo.mHasWindowFocus) { 5157 imm.focusIn(this); 5158 } 5159 5160 invalidate(true); 5161 ListenerInfo li = mListenerInfo; 5162 if (li != null && li.mOnFocusChangeListener != null) { 5163 li.mOnFocusChangeListener.onFocusChange(this, gainFocus); 5164 } 5165 5166 if (mAttachInfo != null) { 5167 mAttachInfo.mKeyDispatchState.reset(this); 5168 } 5169 } 5170 5171 /** 5172 * Sends an accessibility event of the given type. If accessibility is 5173 * not enabled this method has no effect. The default implementation calls 5174 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 5175 * to populate information about the event source (this View), then calls 5176 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 5177 * populate the text content of the event source including its descendants, 5178 * and last calls 5179 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 5180 * on its parent to resuest sending of the event to interested parties. 5181 * <p> 5182 * If an {@link AccessibilityDelegate} has been specified via calling 5183 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5184 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 5185 * responsible for handling this call. 5186 * </p> 5187 * 5188 * @param eventType The type of the event to send, as defined by several types from 5189 * {@link android.view.accessibility.AccessibilityEvent}, such as 5190 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or 5191 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}. 5192 * 5193 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 5194 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5195 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 5196 * @see AccessibilityDelegate 5197 */ 5198 public void sendAccessibilityEvent(int eventType) { 5199 if (mAccessibilityDelegate != null) { 5200 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 5201 } else { 5202 sendAccessibilityEventInternal(eventType); 5203 } 5204 } 5205 5206 /** 5207 * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT} 5208 * {@link AccessibilityEvent} to make an announcement which is related to some 5209 * sort of a context change for which none of the events representing UI transitions 5210 * is a good fit. For example, announcing a new page in a book. If accessibility 5211 * is not enabled this method does nothing. 5212 * 5213 * @param text The announcement text. 5214 */ 5215 public void announceForAccessibility(CharSequence text) { 5216 if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) { 5217 AccessibilityEvent event = AccessibilityEvent.obtain( 5218 AccessibilityEvent.TYPE_ANNOUNCEMENT); 5219 onInitializeAccessibilityEvent(event); 5220 event.getText().add(text); 5221 event.setContentDescription(null); 5222 mParent.requestSendAccessibilityEvent(this, event); 5223 } 5224 } 5225 5226 /** 5227 * @see #sendAccessibilityEvent(int) 5228 * 5229 * Note: Called from the default {@link AccessibilityDelegate}. 5230 */ 5231 void sendAccessibilityEventInternal(int eventType) { 5232 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 5233 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 5234 } 5235 } 5236 5237 /** 5238 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 5239 * takes as an argument an empty {@link AccessibilityEvent} and does not 5240 * perform a check whether accessibility is enabled. 5241 * <p> 5242 * If an {@link AccessibilityDelegate} has been specified via calling 5243 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5244 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 5245 * is responsible for handling this call. 5246 * </p> 5247 * 5248 * @param event The event to send. 5249 * 5250 * @see #sendAccessibilityEvent(int) 5251 */ 5252 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 5253 if (mAccessibilityDelegate != null) { 5254 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 5255 } else { 5256 sendAccessibilityEventUncheckedInternal(event); 5257 } 5258 } 5259 5260 /** 5261 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 5262 * 5263 * Note: Called from the default {@link AccessibilityDelegate}. 5264 */ 5265 void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 5266 if (!isShown()) { 5267 return; 5268 } 5269 onInitializeAccessibilityEvent(event); 5270 // Only a subset of accessibility events populates text content. 5271 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) { 5272 dispatchPopulateAccessibilityEvent(event); 5273 } 5274 // In the beginning we called #isShown(), so we know that getParent() is not null. 5275 getParent().requestSendAccessibilityEvent(this, event); 5276 } 5277 5278 /** 5279 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 5280 * to its children for adding their text content to the event. Note that the 5281 * event text is populated in a separate dispatch path since we add to the 5282 * event not only the text of the source but also the text of all its descendants. 5283 * A typical implementation will call 5284 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 5285 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 5286 * on each child. Override this method if custom population of the event text 5287 * content is required. 5288 * <p> 5289 * If an {@link AccessibilityDelegate} has been specified via calling 5290 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5291 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 5292 * is responsible for handling this call. 5293 * </p> 5294 * <p> 5295 * <em>Note:</em> Accessibility events of certain types are not dispatched for 5296 * populating the event text via this method. For details refer to {@link AccessibilityEvent}. 5297 * </p> 5298 * 5299 * @param event The event. 5300 * 5301 * @return True if the event population was completed. 5302 */ 5303 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 5304 if (mAccessibilityDelegate != null) { 5305 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 5306 } else { 5307 return dispatchPopulateAccessibilityEventInternal(event); 5308 } 5309 } 5310 5311 /** 5312 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5313 * 5314 * Note: Called from the default {@link AccessibilityDelegate}. 5315 */ 5316 boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5317 onPopulateAccessibilityEvent(event); 5318 return false; 5319 } 5320 5321 /** 5322 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 5323 * giving a chance to this View to populate the accessibility event with its 5324 * text content. While this method is free to modify event 5325 * attributes other than text content, doing so should normally be performed in 5326 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 5327 * <p> 5328 * Example: Adding formatted date string to an accessibility event in addition 5329 * to the text added by the super implementation: 5330 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5331 * super.onPopulateAccessibilityEvent(event); 5332 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 5333 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 5334 * mCurrentDate.getTimeInMillis(), flags); 5335 * event.getText().add(selectedDateUtterance); 5336 * }</pre> 5337 * <p> 5338 * If an {@link AccessibilityDelegate} has been specified via calling 5339 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5340 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 5341 * is responsible for handling this call. 5342 * </p> 5343 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5344 * information to the event, in case the default implementation has basic information to add. 5345 * </p> 5346 * 5347 * @param event The accessibility event which to populate. 5348 * 5349 * @see #sendAccessibilityEvent(int) 5350 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5351 */ 5352 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5353 if (mAccessibilityDelegate != null) { 5354 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 5355 } else { 5356 onPopulateAccessibilityEventInternal(event); 5357 } 5358 } 5359 5360 /** 5361 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 5362 * 5363 * Note: Called from the default {@link AccessibilityDelegate}. 5364 */ 5365 void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5366 } 5367 5368 /** 5369 * Initializes an {@link AccessibilityEvent} with information about 5370 * this View which is the event source. In other words, the source of 5371 * an accessibility event is the view whose state change triggered firing 5372 * the event. 5373 * <p> 5374 * Example: Setting the password property of an event in addition 5375 * to properties set by the super implementation: 5376 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5377 * super.onInitializeAccessibilityEvent(event); 5378 * event.setPassword(true); 5379 * }</pre> 5380 * <p> 5381 * If an {@link AccessibilityDelegate} has been specified via calling 5382 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5383 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(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 * @param event The event to initialize. 5390 * 5391 * @see #sendAccessibilityEvent(int) 5392 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5393 */ 5394 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5395 if (mAccessibilityDelegate != null) { 5396 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 5397 } else { 5398 onInitializeAccessibilityEventInternal(event); 5399 } 5400 } 5401 5402 /** 5403 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 5404 * 5405 * Note: Called from the default {@link AccessibilityDelegate}. 5406 */ 5407 void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 5408 event.setSource(this); 5409 event.setClassName(View.class.getName()); 5410 event.setPackageName(getContext().getPackageName()); 5411 event.setEnabled(isEnabled()); 5412 event.setContentDescription(mContentDescription); 5413 5414 switch (event.getEventType()) { 5415 case AccessibilityEvent.TYPE_VIEW_FOCUSED: { 5416 ArrayList<View> focusablesTempList = (mAttachInfo != null) 5417 ? mAttachInfo.mTempArrayList : new ArrayList<View>(); 5418 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL); 5419 event.setItemCount(focusablesTempList.size()); 5420 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 5421 if (mAttachInfo != null) { 5422 focusablesTempList.clear(); 5423 } 5424 } break; 5425 case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: { 5426 CharSequence text = getIterableTextForAccessibility(); 5427 if (text != null && text.length() > 0) { 5428 event.setFromIndex(getAccessibilitySelectionStart()); 5429 event.setToIndex(getAccessibilitySelectionEnd()); 5430 event.setItemCount(text.length()); 5431 } 5432 } break; 5433 } 5434 } 5435 5436 /** 5437 * Returns an {@link AccessibilityNodeInfo} representing this view from the 5438 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 5439 * This method is responsible for obtaining an accessibility node info from a 5440 * pool of reusable instances and calling 5441 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 5442 * initialize the former. 5443 * <p> 5444 * Note: The client is responsible for recycling the obtained instance by calling 5445 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 5446 * </p> 5447 * 5448 * @return A populated {@link AccessibilityNodeInfo}. 5449 * 5450 * @see AccessibilityNodeInfo 5451 */ 5452 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 5453 if (mAccessibilityDelegate != null) { 5454 return mAccessibilityDelegate.createAccessibilityNodeInfo(this); 5455 } else { 5456 return createAccessibilityNodeInfoInternal(); 5457 } 5458 } 5459 5460 /** 5461 * @see #createAccessibilityNodeInfo() 5462 */ 5463 AccessibilityNodeInfo createAccessibilityNodeInfoInternal() { 5464 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 5465 if (provider != null) { 5466 return provider.createAccessibilityNodeInfo(View.NO_ID); 5467 } else { 5468 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 5469 onInitializeAccessibilityNodeInfo(info); 5470 return info; 5471 } 5472 } 5473 5474 /** 5475 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 5476 * The base implementation sets: 5477 * <ul> 5478 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 5479 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 5480 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 5481 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 5482 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 5483 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 5484 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 5485 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 5486 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 5487 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 5488 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 5489 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 5490 * </ul> 5491 * <p> 5492 * Subclasses should override this method, call the super implementation, 5493 * and set additional attributes. 5494 * </p> 5495 * <p> 5496 * If an {@link AccessibilityDelegate} has been specified via calling 5497 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5498 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 5499 * is responsible for handling this call. 5500 * </p> 5501 * 5502 * @param info The instance to initialize. 5503 */ 5504 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 5505 if (mAccessibilityDelegate != null) { 5506 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 5507 } else { 5508 onInitializeAccessibilityNodeInfoInternal(info); 5509 } 5510 } 5511 5512 /** 5513 * Gets the location of this view in screen coordintates. 5514 * 5515 * @param outRect The output location 5516 * @hide 5517 */ 5518 public void getBoundsOnScreen(Rect outRect) { 5519 if (mAttachInfo == null) { 5520 return; 5521 } 5522 5523 RectF position = mAttachInfo.mTmpTransformRect; 5524 position.set(0, 0, mRight - mLeft, mBottom - mTop); 5525 5526 if (!hasIdentityMatrix()) { 5527 getMatrix().mapRect(position); 5528 } 5529 5530 position.offset(mLeft, mTop); 5531 5532 ViewParent parent = mParent; 5533 while (parent instanceof View) { 5534 View parentView = (View) parent; 5535 5536 position.offset(-parentView.mScrollX, -parentView.mScrollY); 5537 5538 if (!parentView.hasIdentityMatrix()) { 5539 parentView.getMatrix().mapRect(position); 5540 } 5541 5542 position.offset(parentView.mLeft, parentView.mTop); 5543 5544 parent = parentView.mParent; 5545 } 5546 5547 if (parent instanceof ViewRootImpl) { 5548 ViewRootImpl viewRootImpl = (ViewRootImpl) parent; 5549 position.offset(0, -viewRootImpl.mCurScrollY); 5550 } 5551 5552 position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 5553 5554 outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f), 5555 (int) (position.right + 0.5f), (int) (position.bottom + 0.5f)); 5556 } 5557 5558 /** 5559 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 5560 * 5561 * Note: Called from the default {@link AccessibilityDelegate}. 5562 */ 5563 void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 5564 Rect bounds = mAttachInfo.mTmpInvalRect; 5565 5566 getDrawingRect(bounds); 5567 info.setBoundsInParent(bounds); 5568 5569 getBoundsOnScreen(bounds); 5570 info.setBoundsInScreen(bounds); 5571 5572 ViewParent parent = getParentForAccessibility(); 5573 if (parent instanceof View) { 5574 info.setParent((View) parent); 5575 } 5576 5577 if (mID != View.NO_ID) { 5578 View rootView = getRootView(); 5579 if (rootView == null) { 5580 rootView = this; 5581 } 5582 View label = rootView.findLabelForView(this, mID); 5583 if (label != null) { 5584 info.setLabeledBy(label); 5585 } 5586 5587 if ((mAttachInfo.mAccessibilityFetchFlags 5588 & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0 5589 && Resources.resourceHasPackage(mID)) { 5590 try { 5591 String viewId = getResources().getResourceName(mID); 5592 info.setViewIdResourceName(viewId); 5593 } catch (Resources.NotFoundException nfe) { 5594 /* ignore */ 5595 } 5596 } 5597 } 5598 5599 if (mLabelForId != View.NO_ID) { 5600 View rootView = getRootView(); 5601 if (rootView == null) { 5602 rootView = this; 5603 } 5604 View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId); 5605 if (labeled != null) { 5606 info.setLabelFor(labeled); 5607 } 5608 } 5609 5610 info.setVisibleToUser(isVisibleToUser()); 5611 5612 info.setPackageName(mContext.getPackageName()); 5613 info.setClassName(View.class.getName()); 5614 info.setContentDescription(getContentDescription()); 5615 5616 info.setEnabled(isEnabled()); 5617 info.setClickable(isClickable()); 5618 info.setFocusable(isFocusable()); 5619 info.setFocused(isFocused()); 5620 info.setAccessibilityFocused(isAccessibilityFocused()); 5621 info.setSelected(isSelected()); 5622 info.setLongClickable(isLongClickable()); 5623 info.setLiveRegion(getAccessibilityLiveRegion()); 5624 5625 // TODO: These make sense only if we are in an AdapterView but all 5626 // views can be selected. Maybe from accessibility perspective 5627 // we should report as selectable view in an AdapterView. 5628 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 5629 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 5630 5631 if (isFocusable()) { 5632 if (isFocused()) { 5633 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 5634 } else { 5635 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 5636 } 5637 } 5638 5639 if (!isAccessibilityFocused()) { 5640 info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); 5641 } else { 5642 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); 5643 } 5644 5645 if (isClickable() && isEnabled()) { 5646 info.addAction(AccessibilityNodeInfo.ACTION_CLICK); 5647 } 5648 5649 if (isLongClickable() && isEnabled()) { 5650 info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); 5651 } 5652 5653 CharSequence text = getIterableTextForAccessibility(); 5654 if (text != null && text.length() > 0) { 5655 info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd()); 5656 5657 info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION); 5658 info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); 5659 info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); 5660 info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER 5661 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD 5662 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH); 5663 } 5664 } 5665 5666 private View findLabelForView(View view, int labeledId) { 5667 if (mMatchLabelForPredicate == null) { 5668 mMatchLabelForPredicate = new MatchLabelForPredicate(); 5669 } 5670 mMatchLabelForPredicate.mLabeledId = labeledId; 5671 return findViewByPredicateInsideOut(view, mMatchLabelForPredicate); 5672 } 5673 5674 /** 5675 * Computes whether this view is visible to the user. Such a view is 5676 * attached, visible, all its predecessors are visible, it is not clipped 5677 * entirely by its predecessors, and has an alpha greater than zero. 5678 * 5679 * @return Whether the view is visible on the screen. 5680 * 5681 * @hide 5682 */ 5683 protected boolean isVisibleToUser() { 5684 return isVisibleToUser(null); 5685 } 5686 5687 /** 5688 * Computes whether the given portion of this view is visible to the user. 5689 * Such a view is attached, visible, all its predecessors are visible, 5690 * has an alpha greater than zero, and the specified portion is not 5691 * clipped entirely by its predecessors. 5692 * 5693 * @param boundInView the portion of the view to test; coordinates should be relative; may be 5694 * <code>null</code>, and the entire view will be tested in this case. 5695 * When <code>true</code> is returned by the function, the actual visible 5696 * region will be stored in this parameter; that is, if boundInView is fully 5697 * contained within the view, no modification will be made, otherwise regions 5698 * outside of the visible area of the view will be clipped. 5699 * 5700 * @return Whether the specified portion of the view is visible on the screen. 5701 * 5702 * @hide 5703 */ 5704 protected boolean isVisibleToUser(Rect boundInView) { 5705 if (mAttachInfo != null) { 5706 // Attached to invisible window means this view is not visible. 5707 if (mAttachInfo.mWindowVisibility != View.VISIBLE) { 5708 return false; 5709 } 5710 // An invisible predecessor or one with alpha zero means 5711 // that this view is not visible to the user. 5712 Object current = this; 5713 while (current instanceof View) { 5714 View view = (View) current; 5715 // We have attach info so this view is attached and there is no 5716 // need to check whether we reach to ViewRootImpl on the way up. 5717 if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 || 5718 view.getVisibility() != VISIBLE) { 5719 return false; 5720 } 5721 current = view.mParent; 5722 } 5723 // Check if the view is entirely covered by its predecessors. 5724 Rect visibleRect = mAttachInfo.mTmpInvalRect; 5725 Point offset = mAttachInfo.mPoint; 5726 if (!getGlobalVisibleRect(visibleRect, offset)) { 5727 return false; 5728 } 5729 // Check if the visible portion intersects the rectangle of interest. 5730 if (boundInView != null) { 5731 visibleRect.offset(-offset.x, -offset.y); 5732 return boundInView.intersect(visibleRect); 5733 } 5734 return true; 5735 } 5736 return false; 5737 } 5738 5739 /** 5740 * Computes a point on which a sequence of a down/up event can be sent to 5741 * trigger clicking this view. This method is for the exclusive use by the 5742 * accessibility layer to determine where to send a click event in explore 5743 * by touch mode. 5744 * 5745 * @param interactiveRegion The interactive portion of this window. 5746 * @param outPoint The point to populate. 5747 * @return True of such a point exists. 5748 */ 5749 boolean computeClickPointInScreenForAccessibility(Region interactiveRegion, 5750 Point outPoint) { 5751 // Since the interactive portion of the view is a region but as a view 5752 // may have a transformation matrix which cannot be applied to a 5753 // region we compute the view bounds rectangle and all interactive 5754 // predecessor's and sibling's (siblings of predecessors included) 5755 // rectangles that intersect the view bounds. At the 5756 // end if the view was partially covered by another interactive 5757 // view we compute the view's interactive region and pick a point 5758 // on its boundary path as regions do not offer APIs to get inner 5759 // points. Note that the the code is optimized to fail early and 5760 // avoid unnecessary allocations plus computations. 5761 5762 // The current approach has edge cases that may produce false 5763 // positives or false negatives. For example, a portion of the 5764 // view may be covered by an interactive descendant of a 5765 // predecessor, which we do not compute. Also a view may be handling 5766 // raw touch events instead registering click listeners, which 5767 // we cannot compute. Despite these limitations this approach will 5768 // work most of the time and it is a huge improvement over just 5769 // blindly sending the down and up events in the center of the 5770 // view. 5771 5772 // Cannot click on an unattached view. 5773 if (mAttachInfo == null) { 5774 return false; 5775 } 5776 5777 // Attached to an invisible window means this view is not visible. 5778 if (mAttachInfo.mWindowVisibility != View.VISIBLE) { 5779 return false; 5780 } 5781 5782 RectF bounds = mAttachInfo.mTmpTransformRect; 5783 bounds.set(0, 0, getWidth(), getHeight()); 5784 List<RectF> intersections = mAttachInfo.mTmpRectList; 5785 intersections.clear(); 5786 5787 if (mParent instanceof ViewGroup) { 5788 ViewGroup parentGroup = (ViewGroup) mParent; 5789 if (!parentGroup.translateBoundsAndIntersectionsInWindowCoordinates( 5790 this, bounds, intersections)) { 5791 intersections.clear(); 5792 return false; 5793 } 5794 } 5795 5796 // Take into account the window location. 5797 final int dx = mAttachInfo.mWindowLeft; 5798 final int dy = mAttachInfo.mWindowTop; 5799 bounds.offset(dx, dy); 5800 offsetRects(intersections, dx, dy); 5801 5802 if (intersections.isEmpty() && interactiveRegion == null) { 5803 outPoint.set((int) bounds.centerX(), (int) bounds.centerY()); 5804 } else { 5805 // This view is partially covered by other views, then compute 5806 // the not covered region and pick a point on its boundary. 5807 Region region = new Region(); 5808 region.set((int) bounds.left, (int) bounds.top, 5809 (int) bounds.right, (int) bounds.bottom); 5810 5811 final int intersectionCount = intersections.size(); 5812 for (int i = intersectionCount - 1; i >= 0; i--) { 5813 RectF intersection = intersections.remove(i); 5814 region.op((int) intersection.left, (int) intersection.top, 5815 (int) intersection.right, (int) intersection.bottom, 5816 Region.Op.DIFFERENCE); 5817 } 5818 5819 // If the view is completely covered, done. 5820 if (region.isEmpty()) { 5821 return false; 5822 } 5823 5824 // Take into account the interactive portion of the window 5825 // as the rest is covered by other windows. If no such a region 5826 // then the whole window is interactive. 5827 if (interactiveRegion != null) { 5828 region.op(interactiveRegion, Region.Op.INTERSECT); 5829 } 5830 5831 // If the view is completely covered, done. 5832 if (region.isEmpty()) { 5833 return false; 5834 } 5835 5836 // Try a shortcut here. 5837 if (region.isRect()) { 5838 Rect regionBounds = mAttachInfo.mTmpInvalRect; 5839 region.getBounds(regionBounds); 5840 outPoint.set(regionBounds.centerX(), regionBounds.centerY()); 5841 return true; 5842 } 5843 5844 // Get the a point on the region boundary path. 5845 Path path = region.getBoundaryPath(); 5846 PathMeasure pathMeasure = new PathMeasure(path, false); 5847 final float[] coordinates = mAttachInfo.mTmpTransformLocation; 5848 5849 // Without loss of generality pick a point. 5850 final float point = pathMeasure.getLength() * 0.01f; 5851 if (!pathMeasure.getPosTan(point, coordinates, null)) { 5852 return false; 5853 } 5854 5855 outPoint.set(Math.round(coordinates[0]), Math.round(coordinates[1])); 5856 } 5857 5858 return true; 5859 } 5860 5861 static void offsetRects(List<RectF> rects, float offsetX, float offsetY) { 5862 final int rectCount = rects.size(); 5863 for (int i = 0; i < rectCount; i++) { 5864 RectF intersection = rects.get(i); 5865 intersection.offset(offsetX, offsetY); 5866 } 5867 } 5868 5869 /** 5870 * Returns the delegate for implementing accessibility support via 5871 * composition. For more details see {@link AccessibilityDelegate}. 5872 * 5873 * @return The delegate, or null if none set. 5874 * 5875 * @hide 5876 */ 5877 public AccessibilityDelegate getAccessibilityDelegate() { 5878 return mAccessibilityDelegate; 5879 } 5880 5881 /** 5882 * Sets a delegate for implementing accessibility support via composition as 5883 * opposed to inheritance. The delegate's primary use is for implementing 5884 * backwards compatible widgets. For more details see {@link AccessibilityDelegate}. 5885 * 5886 * @param delegate The delegate instance. 5887 * 5888 * @see AccessibilityDelegate 5889 */ 5890 public void setAccessibilityDelegate(AccessibilityDelegate delegate) { 5891 mAccessibilityDelegate = delegate; 5892 } 5893 5894 /** 5895 * Gets the provider for managing a virtual view hierarchy rooted at this View 5896 * and reported to {@link android.accessibilityservice.AccessibilityService}s 5897 * that explore the window content. 5898 * <p> 5899 * If this method returns an instance, this instance is responsible for managing 5900 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this 5901 * View including the one representing the View itself. Similarly the returned 5902 * instance is responsible for performing accessibility actions on any virtual 5903 * view or the root view itself. 5904 * </p> 5905 * <p> 5906 * If an {@link AccessibilityDelegate} has been specified via calling 5907 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5908 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)} 5909 * is responsible for handling this call. 5910 * </p> 5911 * 5912 * @return The provider. 5913 * 5914 * @see AccessibilityNodeProvider 5915 */ 5916 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 5917 if (mAccessibilityDelegate != null) { 5918 return mAccessibilityDelegate.getAccessibilityNodeProvider(this); 5919 } else { 5920 return null; 5921 } 5922 } 5923 5924 /** 5925 * Gets the unique identifier of this view on the screen for accessibility purposes. 5926 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 5927 * 5928 * @return The view accessibility id. 5929 * 5930 * @hide 5931 */ 5932 public int getAccessibilityViewId() { 5933 if (mAccessibilityViewId == NO_ID) { 5934 mAccessibilityViewId = sNextAccessibilityViewId++; 5935 } 5936 return mAccessibilityViewId; 5937 } 5938 5939 /** 5940 * Gets the unique identifier of the window in which this View reseides. 5941 * 5942 * @return The window accessibility id. 5943 * 5944 * @hide 5945 */ 5946 public int getAccessibilityWindowId() { 5947 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId 5948 : AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 5949 } 5950 5951 /** 5952 * Gets the {@link View} description. It briefly describes the view and is 5953 * primarily used for accessibility support. Set this property to enable 5954 * better accessibility support for your application. This is especially 5955 * true for views that do not have textual representation (For example, 5956 * ImageButton). 5957 * 5958 * @return The content description. 5959 * 5960 * @attr ref android.R.styleable#View_contentDescription 5961 */ 5962 @ViewDebug.ExportedProperty(category = "accessibility") 5963 public CharSequence getContentDescription() { 5964 return mContentDescription; 5965 } 5966 5967 /** 5968 * Sets the {@link View} description. It briefly describes the view and is 5969 * primarily used for accessibility support. Set this property to enable 5970 * better accessibility support for your application. This is especially 5971 * true for views that do not have textual representation (For example, 5972 * ImageButton). 5973 * 5974 * @param contentDescription The content description. 5975 * 5976 * @attr ref android.R.styleable#View_contentDescription 5977 */ 5978 @RemotableViewMethod 5979 public void setContentDescription(CharSequence contentDescription) { 5980 if (mContentDescription == null) { 5981 if (contentDescription == null) { 5982 return; 5983 } 5984 } else if (mContentDescription.equals(contentDescription)) { 5985 return; 5986 } 5987 mContentDescription = contentDescription; 5988 final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0; 5989 if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 5990 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); 5991 notifySubtreeAccessibilityStateChangedIfNeeded(); 5992 } else { 5993 notifyViewAccessibilityStateChangedIfNeeded( 5994 AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION); 5995 } 5996 } 5997 5998 /** 5999 * Gets the id of a view for which this view serves as a label for 6000 * accessibility purposes. 6001 * 6002 * @return The labeled view id. 6003 */ 6004 @ViewDebug.ExportedProperty(category = "accessibility") 6005 public int getLabelFor() { 6006 return mLabelForId; 6007 } 6008 6009 /** 6010 * Sets the id of a view for which this view serves as a label for 6011 * accessibility purposes. 6012 * 6013 * @param id The labeled view id. 6014 */ 6015 @RemotableViewMethod 6016 public void setLabelFor(int id) { 6017 mLabelForId = id; 6018 if (mLabelForId != View.NO_ID 6019 && mID == View.NO_ID) { 6020 mID = generateViewId(); 6021 } 6022 } 6023 6024 /** 6025 * Invoked whenever this view loses focus, either by losing window focus or by losing 6026 * focus within its window. This method can be used to clear any state tied to the 6027 * focus. For instance, if a button is held pressed with the trackball and the window 6028 * loses focus, this method can be used to cancel the press. 6029 * 6030 * Subclasses of View overriding this method should always call super.onFocusLost(). 6031 * 6032 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 6033 * @see #onWindowFocusChanged(boolean) 6034 * 6035 * @hide pending API council approval 6036 */ 6037 protected void onFocusLost() { 6038 resetPressedState(); 6039 } 6040 6041 private void resetPressedState() { 6042 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 6043 return; 6044 } 6045 6046 if (isPressed()) { 6047 setPressed(false); 6048 6049 if (!mHasPerformedLongPress) { 6050 removeLongPressCallback(); 6051 } 6052 } 6053 } 6054 6055 /** 6056 * Returns true if this view has focus 6057 * 6058 * @return True if this view has focus, false otherwise. 6059 */ 6060 @ViewDebug.ExportedProperty(category = "focus") 6061 public boolean isFocused() { 6062 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 6063 } 6064 6065 /** 6066 * Find the view in the hierarchy rooted at this view that currently has 6067 * focus. 6068 * 6069 * @return The view that currently has focus, or null if no focused view can 6070 * be found. 6071 */ 6072 public View findFocus() { 6073 return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null; 6074 } 6075 6076 /** 6077 * Indicates whether this view is one of the set of scrollable containers in 6078 * its window. 6079 * 6080 * @return whether this view is one of the set of scrollable containers in 6081 * its window 6082 * 6083 * @attr ref android.R.styleable#View_isScrollContainer 6084 */ 6085 public boolean isScrollContainer() { 6086 return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0; 6087 } 6088 6089 /** 6090 * Change whether this view is one of the set of scrollable containers in 6091 * its window. This will be used to determine whether the window can 6092 * resize or must pan when a soft input area is open -- scrollable 6093 * containers allow the window to use resize mode since the container 6094 * will appropriately shrink. 6095 * 6096 * @attr ref android.R.styleable#View_isScrollContainer 6097 */ 6098 public void setScrollContainer(boolean isScrollContainer) { 6099 if (isScrollContainer) { 6100 if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) { 6101 mAttachInfo.mScrollContainers.add(this); 6102 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 6103 } 6104 mPrivateFlags |= PFLAG_SCROLL_CONTAINER; 6105 } else { 6106 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 6107 mAttachInfo.mScrollContainers.remove(this); 6108 } 6109 mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED); 6110 } 6111 } 6112 6113 /** 6114 * Returns the quality of the drawing cache. 6115 * 6116 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 6117 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 6118 * 6119 * @see #setDrawingCacheQuality(int) 6120 * @see #setDrawingCacheEnabled(boolean) 6121 * @see #isDrawingCacheEnabled() 6122 * 6123 * @attr ref android.R.styleable#View_drawingCacheQuality 6124 */ 6125 @DrawingCacheQuality 6126 public int getDrawingCacheQuality() { 6127 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 6128 } 6129 6130 /** 6131 * Set the drawing cache quality of this view. This value is used only when the 6132 * drawing cache is enabled 6133 * 6134 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 6135 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 6136 * 6137 * @see #getDrawingCacheQuality() 6138 * @see #setDrawingCacheEnabled(boolean) 6139 * @see #isDrawingCacheEnabled() 6140 * 6141 * @attr ref android.R.styleable#View_drawingCacheQuality 6142 */ 6143 public void setDrawingCacheQuality(@DrawingCacheQuality int quality) { 6144 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 6145 } 6146 6147 /** 6148 * Returns whether the screen should remain on, corresponding to the current 6149 * value of {@link #KEEP_SCREEN_ON}. 6150 * 6151 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 6152 * 6153 * @see #setKeepScreenOn(boolean) 6154 * 6155 * @attr ref android.R.styleable#View_keepScreenOn 6156 */ 6157 public boolean getKeepScreenOn() { 6158 return (mViewFlags & KEEP_SCREEN_ON) != 0; 6159 } 6160 6161 /** 6162 * Controls whether the screen should remain on, modifying the 6163 * value of {@link #KEEP_SCREEN_ON}. 6164 * 6165 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 6166 * 6167 * @see #getKeepScreenOn() 6168 * 6169 * @attr ref android.R.styleable#View_keepScreenOn 6170 */ 6171 public void setKeepScreenOn(boolean keepScreenOn) { 6172 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 6173 } 6174 6175 /** 6176 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 6177 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6178 * 6179 * @attr ref android.R.styleable#View_nextFocusLeft 6180 */ 6181 public int getNextFocusLeftId() { 6182 return mNextFocusLeftId; 6183 } 6184 6185 /** 6186 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 6187 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 6188 * decide automatically. 6189 * 6190 * @attr ref android.R.styleable#View_nextFocusLeft 6191 */ 6192 public void setNextFocusLeftId(int nextFocusLeftId) { 6193 mNextFocusLeftId = nextFocusLeftId; 6194 } 6195 6196 /** 6197 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 6198 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6199 * 6200 * @attr ref android.R.styleable#View_nextFocusRight 6201 */ 6202 public int getNextFocusRightId() { 6203 return mNextFocusRightId; 6204 } 6205 6206 /** 6207 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 6208 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 6209 * decide automatically. 6210 * 6211 * @attr ref android.R.styleable#View_nextFocusRight 6212 */ 6213 public void setNextFocusRightId(int nextFocusRightId) { 6214 mNextFocusRightId = nextFocusRightId; 6215 } 6216 6217 /** 6218 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 6219 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6220 * 6221 * @attr ref android.R.styleable#View_nextFocusUp 6222 */ 6223 public int getNextFocusUpId() { 6224 return mNextFocusUpId; 6225 } 6226 6227 /** 6228 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 6229 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 6230 * decide automatically. 6231 * 6232 * @attr ref android.R.styleable#View_nextFocusUp 6233 */ 6234 public void setNextFocusUpId(int nextFocusUpId) { 6235 mNextFocusUpId = nextFocusUpId; 6236 } 6237 6238 /** 6239 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 6240 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6241 * 6242 * @attr ref android.R.styleable#View_nextFocusDown 6243 */ 6244 public int getNextFocusDownId() { 6245 return mNextFocusDownId; 6246 } 6247 6248 /** 6249 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 6250 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 6251 * decide automatically. 6252 * 6253 * @attr ref android.R.styleable#View_nextFocusDown 6254 */ 6255 public void setNextFocusDownId(int nextFocusDownId) { 6256 mNextFocusDownId = nextFocusDownId; 6257 } 6258 6259 /** 6260 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 6261 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6262 * 6263 * @attr ref android.R.styleable#View_nextFocusForward 6264 */ 6265 public int getNextFocusForwardId() { 6266 return mNextFocusForwardId; 6267 } 6268 6269 /** 6270 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 6271 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 6272 * decide automatically. 6273 * 6274 * @attr ref android.R.styleable#View_nextFocusForward 6275 */ 6276 public void setNextFocusForwardId(int nextFocusForwardId) { 6277 mNextFocusForwardId = nextFocusForwardId; 6278 } 6279 6280 /** 6281 * Returns the visibility of this view and all of its ancestors 6282 * 6283 * @return True if this view and all of its ancestors are {@link #VISIBLE} 6284 */ 6285 public boolean isShown() { 6286 View current = this; 6287 //noinspection ConstantConditions 6288 do { 6289 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 6290 return false; 6291 } 6292 ViewParent parent = current.mParent; 6293 if (parent == null) { 6294 return false; // We are not attached to the view root 6295 } 6296 if (!(parent instanceof View)) { 6297 return true; 6298 } 6299 current = (View) parent; 6300 } while (current != null); 6301 6302 return false; 6303 } 6304 6305 /** 6306 * Called by the view hierarchy when the content insets for a window have 6307 * changed, to allow it to adjust its content to fit within those windows. 6308 * The content insets tell you the space that the status bar, input method, 6309 * and other system windows infringe on the application's window. 6310 * 6311 * <p>You do not normally need to deal with this function, since the default 6312 * window decoration given to applications takes care of applying it to the 6313 * content of the window. If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 6314 * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case, 6315 * and your content can be placed under those system elements. You can then 6316 * use this method within your view hierarchy if you have parts of your UI 6317 * which you would like to ensure are not being covered. 6318 * 6319 * <p>The default implementation of this method simply applies the content 6320 * insets to the view's padding, consuming that content (modifying the 6321 * insets to be 0), and returning true. This behavior is off by default, but can 6322 * be enabled through {@link #setFitsSystemWindows(boolean)}. 6323 * 6324 * <p>This function's traversal down the hierarchy is depth-first. The same content 6325 * insets object is propagated down the hierarchy, so any changes made to it will 6326 * be seen by all following views (including potentially ones above in 6327 * the hierarchy since this is a depth-first traversal). The first view 6328 * that returns true will abort the entire traversal. 6329 * 6330 * <p>The default implementation works well for a situation where it is 6331 * used with a container that covers the entire window, allowing it to 6332 * apply the appropriate insets to its content on all edges. If you need 6333 * a more complicated layout (such as two different views fitting system 6334 * windows, one on the top of the window, and one on the bottom), 6335 * you can override the method and handle the insets however you would like. 6336 * Note that the insets provided by the framework are always relative to the 6337 * far edges of the window, not accounting for the location of the called view 6338 * within that window. (In fact when this method is called you do not yet know 6339 * where the layout will place the view, as it is done before layout happens.) 6340 * 6341 * <p>Note: unlike many View methods, there is no dispatch phase to this 6342 * call. If you are overriding it in a ViewGroup and want to allow the 6343 * call to continue to your children, you must be sure to call the super 6344 * implementation. 6345 * 6346 * <p>Here is a sample layout that makes use of fitting system windows 6347 * to have controls for a video view placed inside of the window decorations 6348 * that it hides and shows. This can be used with code like the second 6349 * sample (video player) shown in {@link #setSystemUiVisibility(int)}. 6350 * 6351 * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete} 6352 * 6353 * @param insets Current content insets of the window. Prior to 6354 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify 6355 * the insets or else you and Android will be unhappy. 6356 * 6357 * @return {@code true} if this view applied the insets and it should not 6358 * continue propagating further down the hierarchy, {@code false} otherwise. 6359 * @see #getFitsSystemWindows() 6360 * @see #setFitsSystemWindows(boolean) 6361 * @see #setSystemUiVisibility(int) 6362 * 6363 * @deprecated As of API XX use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply 6364 * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use 6365 * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)} 6366 * to implement handling their own insets. 6367 */ 6368 protected boolean fitSystemWindows(Rect insets) { 6369 if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) { 6370 if (insets == null) { 6371 // Null insets by definition have already been consumed. 6372 // This call cannot apply insets since there are none to apply, 6373 // so return false. 6374 return false; 6375 } 6376 // If we're not in the process of dispatching the newer apply insets call, 6377 // that means we're not in the compatibility path. Dispatch into the newer 6378 // apply insets path and take things from there. 6379 try { 6380 mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS; 6381 return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed(); 6382 } finally { 6383 mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS; 6384 } 6385 } else { 6386 // We're being called from the newer apply insets path. 6387 // Perform the standard fallback behavior. 6388 return fitSystemWindowsInt(insets); 6389 } 6390 } 6391 6392 private boolean fitSystemWindowsInt(Rect insets) { 6393 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 6394 mUserPaddingStart = UNDEFINED_PADDING; 6395 mUserPaddingEnd = UNDEFINED_PADDING; 6396 Rect localInsets = sThreadLocal.get(); 6397 if (localInsets == null) { 6398 localInsets = new Rect(); 6399 sThreadLocal.set(localInsets); 6400 } 6401 boolean res = computeFitSystemWindows(insets, localInsets); 6402 mUserPaddingLeftInitial = localInsets.left; 6403 mUserPaddingRightInitial = localInsets.right; 6404 internalSetPadding(localInsets.left, localInsets.top, 6405 localInsets.right, localInsets.bottom); 6406 return res; 6407 } 6408 return false; 6409 } 6410 6411 /** 6412 * Called when the view should apply {@link WindowInsets} according to its internal policy. 6413 * 6414 * <p>This method should be overridden by views that wish to apply a policy different from or 6415 * in addition to the default behavior. Clients that wish to force a view subtree 6416 * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p> 6417 * 6418 * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set 6419 * it will be called during dispatch instead of this method. The listener may optionally 6420 * call this method from its own implementation if it wishes to apply the view's default 6421 * insets policy in addition to its own.</p> 6422 * 6423 * <p>Implementations of this method should either return the insets parameter unchanged 6424 * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed 6425 * that this view applied itself. This allows new inset types added in future platform 6426 * versions to pass through existing implementations unchanged without being erroneously 6427 * consumed.</p> 6428 * 6429 * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows} 6430 * property is set then the view will consume the system window insets and apply them 6431 * as padding for the view.</p> 6432 * 6433 * @param insets Insets to apply 6434 * @return The supplied insets with any applied insets consumed 6435 */ 6436 public WindowInsets onApplyWindowInsets(WindowInsets insets) { 6437 if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) { 6438 // We weren't called from within a direct call to fitSystemWindows, 6439 // call into it as a fallback in case we're in a class that overrides it 6440 // and has logic to perform. 6441 if (fitSystemWindows(insets.getSystemWindowInsets())) { 6442 return insets.consumeSystemWindowInsets(); 6443 } 6444 } else { 6445 // We were called from within a direct call to fitSystemWindows. 6446 if (fitSystemWindowsInt(insets.getSystemWindowInsets())) { 6447 return insets.consumeSystemWindowInsets(); 6448 } 6449 } 6450 return insets; 6451 } 6452 6453 /** 6454 * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying 6455 * window insets to this view. The listener's 6456 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 6457 * method will be called instead of the view's 6458 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 6459 * 6460 * @param listener Listener to set 6461 * 6462 * @see #onApplyWindowInsets(WindowInsets) 6463 */ 6464 public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) { 6465 getListenerInfo().mOnApplyWindowInsetsListener = listener; 6466 } 6467 6468 /** 6469 * Request to apply the given window insets to this view or another view in its subtree. 6470 * 6471 * <p>This method should be called by clients wishing to apply insets corresponding to areas 6472 * obscured by window decorations or overlays. This can include the status and navigation bars, 6473 * action bars, input methods and more. New inset categories may be added in the future. 6474 * The method returns the insets provided minus any that were applied by this view or its 6475 * children.</p> 6476 * 6477 * <p>Clients wishing to provide custom behavior should override the 6478 * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a 6479 * {@link OnApplyWindowInsetsListener} via the 6480 * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener} 6481 * method.</p> 6482 * 6483 * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method. 6484 * </p> 6485 * 6486 * @param insets Insets to apply 6487 * @return The provided insets minus the insets that were consumed 6488 */ 6489 public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) { 6490 try { 6491 mPrivateFlags3 |= PFLAG3_APPLYING_INSETS; 6492 if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) { 6493 return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets); 6494 } else { 6495 return onApplyWindowInsets(insets); 6496 } 6497 } finally { 6498 mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS; 6499 } 6500 } 6501 6502 /** 6503 * @hide Compute the insets that should be consumed by this view and the ones 6504 * that should propagate to those under it. 6505 */ 6506 protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) { 6507 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 6508 || mAttachInfo == null 6509 || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0 6510 && !mAttachInfo.mOverscanRequested)) { 6511 outLocalInsets.set(inoutInsets); 6512 inoutInsets.set(0, 0, 0, 0); 6513 return true; 6514 } else { 6515 // The application wants to take care of fitting system window for 6516 // the content... however we still need to take care of any overscan here. 6517 final Rect overscan = mAttachInfo.mOverscanInsets; 6518 outLocalInsets.set(overscan); 6519 inoutInsets.left -= overscan.left; 6520 inoutInsets.top -= overscan.top; 6521 inoutInsets.right -= overscan.right; 6522 inoutInsets.bottom -= overscan.bottom; 6523 return false; 6524 } 6525 } 6526 6527 /** 6528 * Compute insets that should be consumed by this view and the ones that should propagate 6529 * to those under it. 6530 * 6531 * @param in Insets currently being processed by this View, likely received as a parameter 6532 * to {@link #onApplyWindowInsets(WindowInsets)}. 6533 * @param outLocalInsets A Rect that will receive the insets that should be consumed 6534 * by this view 6535 * @return Insets that should be passed along to views under this one 6536 */ 6537 public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) { 6538 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 6539 || mAttachInfo == null 6540 || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) { 6541 outLocalInsets.set(in.getSystemWindowInsets()); 6542 return in.consumeSystemWindowInsets(); 6543 } else { 6544 outLocalInsets.set(0, 0, 0, 0); 6545 return in; 6546 } 6547 } 6548 6549 /** 6550 * Sets whether or not this view should account for system screen decorations 6551 * such as the status bar and inset its content; that is, controlling whether 6552 * the default implementation of {@link #fitSystemWindows(Rect)} will be 6553 * executed. See that method for more details. 6554 * 6555 * <p>Note that if you are providing your own implementation of 6556 * {@link #fitSystemWindows(Rect)}, then there is no need to set this 6557 * flag to true -- your implementation will be overriding the default 6558 * implementation that checks this flag. 6559 * 6560 * @param fitSystemWindows If true, then the default implementation of 6561 * {@link #fitSystemWindows(Rect)} will be executed. 6562 * 6563 * @attr ref android.R.styleable#View_fitsSystemWindows 6564 * @see #getFitsSystemWindows() 6565 * @see #fitSystemWindows(Rect) 6566 * @see #setSystemUiVisibility(int) 6567 */ 6568 public void setFitsSystemWindows(boolean fitSystemWindows) { 6569 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 6570 } 6571 6572 /** 6573 * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method 6574 * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)} 6575 * will be executed. 6576 * 6577 * @return {@code true} if the default implementation of 6578 * {@link #fitSystemWindows(Rect)} will be executed. 6579 * 6580 * @attr ref android.R.styleable#View_fitsSystemWindows 6581 * @see #setFitsSystemWindows(boolean) 6582 * @see #fitSystemWindows(Rect) 6583 * @see #setSystemUiVisibility(int) 6584 */ 6585 public boolean getFitsSystemWindows() { 6586 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 6587 } 6588 6589 /** @hide */ 6590 public boolean fitsSystemWindows() { 6591 return getFitsSystemWindows(); 6592 } 6593 6594 /** 6595 * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed. 6596 * @deprecated Use {@link #requestApplyInsets()} for newer platform versions. 6597 */ 6598 public void requestFitSystemWindows() { 6599 if (mParent != null) { 6600 mParent.requestFitSystemWindows(); 6601 } 6602 } 6603 6604 /** 6605 * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed. 6606 */ 6607 public void requestApplyInsets() { 6608 requestFitSystemWindows(); 6609 } 6610 6611 /** 6612 * For use by PhoneWindow to make its own system window fitting optional. 6613 * @hide 6614 */ 6615 public void makeOptionalFitsSystemWindows() { 6616 setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS); 6617 } 6618 6619 /** 6620 * Returns the visibility status for this view. 6621 * 6622 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 6623 * @attr ref android.R.styleable#View_visibility 6624 */ 6625 @ViewDebug.ExportedProperty(mapping = { 6626 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 6627 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 6628 @ViewDebug.IntToString(from = GONE, to = "GONE") 6629 }) 6630 @Visibility 6631 public int getVisibility() { 6632 return mViewFlags & VISIBILITY_MASK; 6633 } 6634 6635 /** 6636 * Set the enabled state of this view. 6637 * 6638 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 6639 * @attr ref android.R.styleable#View_visibility 6640 */ 6641 @RemotableViewMethod 6642 public void setVisibility(@Visibility int visibility) { 6643 setFlags(visibility, VISIBILITY_MASK); 6644 if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false); 6645 } 6646 6647 /** 6648 * Returns the enabled status for this view. The interpretation of the 6649 * enabled state varies by subclass. 6650 * 6651 * @return True if this view is enabled, false otherwise. 6652 */ 6653 @ViewDebug.ExportedProperty 6654 public boolean isEnabled() { 6655 return (mViewFlags & ENABLED_MASK) == ENABLED; 6656 } 6657 6658 /** 6659 * Set the enabled state of this view. The interpretation of the enabled 6660 * state varies by subclass. 6661 * 6662 * @param enabled True if this view is enabled, false otherwise. 6663 */ 6664 @RemotableViewMethod 6665 public void setEnabled(boolean enabled) { 6666 if (enabled == isEnabled()) return; 6667 6668 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 6669 6670 /* 6671 * The View most likely has to change its appearance, so refresh 6672 * the drawable state. 6673 */ 6674 refreshDrawableState(); 6675 6676 // Invalidate too, since the default behavior for views is to be 6677 // be drawn at 50% alpha rather than to change the drawable. 6678 invalidate(true); 6679 6680 if (!enabled) { 6681 cancelPendingInputEvents(); 6682 } 6683 } 6684 6685 /** 6686 * Set whether this view can receive the focus. 6687 * 6688 * Setting this to false will also ensure that this view is not focusable 6689 * in touch mode. 6690 * 6691 * @param focusable If true, this view can receive the focus. 6692 * 6693 * @see #setFocusableInTouchMode(boolean) 6694 * @attr ref android.R.styleable#View_focusable 6695 */ 6696 public void setFocusable(boolean focusable) { 6697 if (!focusable) { 6698 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 6699 } 6700 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 6701 } 6702 6703 /** 6704 * Set whether this view can receive focus while in touch mode. 6705 * 6706 * Setting this to true will also ensure that this view is focusable. 6707 * 6708 * @param focusableInTouchMode If true, this view can receive the focus while 6709 * in touch mode. 6710 * 6711 * @see #setFocusable(boolean) 6712 * @attr ref android.R.styleable#View_focusableInTouchMode 6713 */ 6714 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 6715 // Focusable in touch mode should always be set before the focusable flag 6716 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 6717 // which, in touch mode, will not successfully request focus on this view 6718 // because the focusable in touch mode flag is not set 6719 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 6720 if (focusableInTouchMode) { 6721 setFlags(FOCUSABLE, FOCUSABLE_MASK); 6722 } 6723 } 6724 6725 /** 6726 * Set whether this view should have sound effects enabled for events such as 6727 * clicking and touching. 6728 * 6729 * <p>You may wish to disable sound effects for a view if you already play sounds, 6730 * for instance, a dial key that plays dtmf tones. 6731 * 6732 * @param soundEffectsEnabled whether sound effects are enabled for this view. 6733 * @see #isSoundEffectsEnabled() 6734 * @see #playSoundEffect(int) 6735 * @attr ref android.R.styleable#View_soundEffectsEnabled 6736 */ 6737 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 6738 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 6739 } 6740 6741 /** 6742 * @return whether this view should have sound effects enabled for events such as 6743 * clicking and touching. 6744 * 6745 * @see #setSoundEffectsEnabled(boolean) 6746 * @see #playSoundEffect(int) 6747 * @attr ref android.R.styleable#View_soundEffectsEnabled 6748 */ 6749 @ViewDebug.ExportedProperty 6750 public boolean isSoundEffectsEnabled() { 6751 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 6752 } 6753 6754 /** 6755 * Set whether this view should have haptic feedback for events such as 6756 * long presses. 6757 * 6758 * <p>You may wish to disable haptic feedback if your view already controls 6759 * its own haptic feedback. 6760 * 6761 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 6762 * @see #isHapticFeedbackEnabled() 6763 * @see #performHapticFeedback(int) 6764 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6765 */ 6766 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 6767 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 6768 } 6769 6770 /** 6771 * @return whether this view should have haptic feedback enabled for events 6772 * long presses. 6773 * 6774 * @see #setHapticFeedbackEnabled(boolean) 6775 * @see #performHapticFeedback(int) 6776 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6777 */ 6778 @ViewDebug.ExportedProperty 6779 public boolean isHapticFeedbackEnabled() { 6780 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 6781 } 6782 6783 /** 6784 * Returns the layout direction for this view. 6785 * 6786 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 6787 * {@link #LAYOUT_DIRECTION_RTL}, 6788 * {@link #LAYOUT_DIRECTION_INHERIT} or 6789 * {@link #LAYOUT_DIRECTION_LOCALE}. 6790 * 6791 * @attr ref android.R.styleable#View_layoutDirection 6792 * 6793 * @hide 6794 */ 6795 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6796 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 6797 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 6798 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 6799 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 6800 }) 6801 @LayoutDir 6802 public int getRawLayoutDirection() { 6803 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 6804 } 6805 6806 /** 6807 * Set the layout direction for this view. This will propagate a reset of layout direction 6808 * resolution to the view's children and resolve layout direction for this view. 6809 * 6810 * @param layoutDirection the layout direction to set. Should be one of: 6811 * 6812 * {@link #LAYOUT_DIRECTION_LTR}, 6813 * {@link #LAYOUT_DIRECTION_RTL}, 6814 * {@link #LAYOUT_DIRECTION_INHERIT}, 6815 * {@link #LAYOUT_DIRECTION_LOCALE}. 6816 * 6817 * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution 6818 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 6819 * will return the default {@link #LAYOUT_DIRECTION_LTR}. 6820 * 6821 * @attr ref android.R.styleable#View_layoutDirection 6822 */ 6823 @RemotableViewMethod 6824 public void setLayoutDirection(@LayoutDir int layoutDirection) { 6825 if (getRawLayoutDirection() != layoutDirection) { 6826 // Reset the current layout direction and the resolved one 6827 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK; 6828 resetRtlProperties(); 6829 // Set the new layout direction (filtered) 6830 mPrivateFlags2 |= 6831 ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK); 6832 // We need to resolve all RTL properties as they all depend on layout direction 6833 resolveRtlPropertiesIfNeeded(); 6834 requestLayout(); 6835 invalidate(true); 6836 } 6837 } 6838 6839 /** 6840 * Returns the resolved layout direction for this view. 6841 * 6842 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 6843 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL. 6844 * 6845 * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version 6846 * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}. 6847 * 6848 * @attr ref android.R.styleable#View_layoutDirection 6849 */ 6850 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6851 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 6852 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 6853 }) 6854 @ResolvedLayoutDir 6855 public int getLayoutDirection() { 6856 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 6857 if (targetSdkVersion < JELLY_BEAN_MR1) { 6858 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 6859 return LAYOUT_DIRECTION_RESOLVED_DEFAULT; 6860 } 6861 return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) == 6862 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 6863 } 6864 6865 /** 6866 * Indicates whether or not this view's layout is right-to-left. This is resolved from 6867 * layout attribute and/or the inherited value from the parent 6868 * 6869 * @return true if the layout is right-to-left. 6870 * 6871 * @hide 6872 */ 6873 @ViewDebug.ExportedProperty(category = "layout") 6874 public boolean isLayoutRtl() { 6875 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL); 6876 } 6877 6878 /** 6879 * Indicates whether the view is currently tracking transient state that the 6880 * app should not need to concern itself with saving and restoring, but that 6881 * the framework should take special note to preserve when possible. 6882 * 6883 * <p>A view with transient state cannot be trivially rebound from an external 6884 * data source, such as an adapter binding item views in a list. This may be 6885 * because the view is performing an animation, tracking user selection 6886 * of content, or similar.</p> 6887 * 6888 * @return true if the view has transient state 6889 */ 6890 @ViewDebug.ExportedProperty(category = "layout") 6891 public boolean hasTransientState() { 6892 return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE; 6893 } 6894 6895 /** 6896 * Set whether this view is currently tracking transient state that the 6897 * framework should attempt to preserve when possible. This flag is reference counted, 6898 * so every call to setHasTransientState(true) should be paired with a later call 6899 * to setHasTransientState(false). 6900 * 6901 * <p>A view with transient state cannot be trivially rebound from an external 6902 * data source, such as an adapter binding item views in a list. This may be 6903 * because the view is performing an animation, tracking user selection 6904 * of content, or similar.</p> 6905 * 6906 * @param hasTransientState true if this view has transient state 6907 */ 6908 public void setHasTransientState(boolean hasTransientState) { 6909 mTransientStateCount = hasTransientState ? mTransientStateCount + 1 : 6910 mTransientStateCount - 1; 6911 if (mTransientStateCount < 0) { 6912 mTransientStateCount = 0; 6913 Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " + 6914 "unmatched pair of setHasTransientState calls"); 6915 } else if ((hasTransientState && mTransientStateCount == 1) || 6916 (!hasTransientState && mTransientStateCount == 0)) { 6917 // update flag if we've just incremented up from 0 or decremented down to 0 6918 mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) | 6919 (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0); 6920 if (mParent != null) { 6921 try { 6922 mParent.childHasTransientStateChanged(this, hasTransientState); 6923 } catch (AbstractMethodError e) { 6924 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 6925 " does not fully implement ViewParent", e); 6926 } 6927 } 6928 } 6929 } 6930 6931 /** 6932 * Returns true if this view is currently attached to a window. 6933 */ 6934 public boolean isAttachedToWindow() { 6935 return mAttachInfo != null; 6936 } 6937 6938 /** 6939 * Returns true if this view has been through at least one layout since it 6940 * was last attached to or detached from a window. 6941 */ 6942 public boolean isLaidOut() { 6943 return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT; 6944 } 6945 6946 /** 6947 * If this view doesn't do any drawing on its own, set this flag to 6948 * allow further optimizations. By default, this flag is not set on 6949 * View, but could be set on some View subclasses such as ViewGroup. 6950 * 6951 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 6952 * you should clear this flag. 6953 * 6954 * @param willNotDraw whether or not this View draw on its own 6955 */ 6956 public void setWillNotDraw(boolean willNotDraw) { 6957 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 6958 } 6959 6960 /** 6961 * Returns whether or not this View draws on its own. 6962 * 6963 * @return true if this view has nothing to draw, false otherwise 6964 */ 6965 @ViewDebug.ExportedProperty(category = "drawing") 6966 public boolean willNotDraw() { 6967 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 6968 } 6969 6970 /** 6971 * When a View's drawing cache is enabled, drawing is redirected to an 6972 * offscreen bitmap. Some views, like an ImageView, must be able to 6973 * bypass this mechanism if they already draw a single bitmap, to avoid 6974 * unnecessary usage of the memory. 6975 * 6976 * @param willNotCacheDrawing true if this view does not cache its 6977 * drawing, false otherwise 6978 */ 6979 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 6980 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 6981 } 6982 6983 /** 6984 * Returns whether or not this View can cache its drawing or not. 6985 * 6986 * @return true if this view does not cache its drawing, false otherwise 6987 */ 6988 @ViewDebug.ExportedProperty(category = "drawing") 6989 public boolean willNotCacheDrawing() { 6990 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 6991 } 6992 6993 /** 6994 * Indicates whether this view reacts to click events or not. 6995 * 6996 * @return true if the view is clickable, false otherwise 6997 * 6998 * @see #setClickable(boolean) 6999 * @attr ref android.R.styleable#View_clickable 7000 */ 7001 @ViewDebug.ExportedProperty 7002 public boolean isClickable() { 7003 return (mViewFlags & CLICKABLE) == CLICKABLE; 7004 } 7005 7006 /** 7007 * Enables or disables click events for this view. When a view 7008 * is clickable it will change its state to "pressed" on every click. 7009 * Subclasses should set the view clickable to visually react to 7010 * user's clicks. 7011 * 7012 * @param clickable true to make the view clickable, false otherwise 7013 * 7014 * @see #isClickable() 7015 * @attr ref android.R.styleable#View_clickable 7016 */ 7017 public void setClickable(boolean clickable) { 7018 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 7019 } 7020 7021 /** 7022 * Indicates whether this view reacts to long click events or not. 7023 * 7024 * @return true if the view is long clickable, false otherwise 7025 * 7026 * @see #setLongClickable(boolean) 7027 * @attr ref android.R.styleable#View_longClickable 7028 */ 7029 public boolean isLongClickable() { 7030 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 7031 } 7032 7033 /** 7034 * Enables or disables long click events for this view. When a view is long 7035 * clickable it reacts to the user holding down the button for a longer 7036 * duration than a tap. This event can either launch the listener or a 7037 * context menu. 7038 * 7039 * @param longClickable true to make the view long clickable, false otherwise 7040 * @see #isLongClickable() 7041 * @attr ref android.R.styleable#View_longClickable 7042 */ 7043 public void setLongClickable(boolean longClickable) { 7044 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 7045 } 7046 7047 /** 7048 * Sets the pressed state for this view and provides a touch coordinate for 7049 * animation hinting. 7050 * 7051 * @param pressed Pass true to set the View's internal state to "pressed", 7052 * or false to reverts the View's internal state from a 7053 * previously set "pressed" state. 7054 * @param x The x coordinate of the touch that caused the press 7055 * @param y The y coordinate of the touch that caused the press 7056 */ 7057 private void setPressed(boolean pressed, float x, float y) { 7058 if (pressed) { 7059 drawableHotspotChanged(x, y); 7060 } 7061 7062 setPressed(pressed); 7063 } 7064 7065 /** 7066 * Sets the pressed state for this view. 7067 * 7068 * @see #isClickable() 7069 * @see #setClickable(boolean) 7070 * 7071 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 7072 * the View's internal state from a previously set "pressed" state. 7073 */ 7074 public void setPressed(boolean pressed) { 7075 final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED); 7076 7077 if (pressed) { 7078 mPrivateFlags |= PFLAG_PRESSED; 7079 } else { 7080 mPrivateFlags &= ~PFLAG_PRESSED; 7081 } 7082 7083 if (needsRefresh) { 7084 refreshDrawableState(); 7085 } 7086 dispatchSetPressed(pressed); 7087 } 7088 7089 /** 7090 * Dispatch setPressed to all of this View's children. 7091 * 7092 * @see #setPressed(boolean) 7093 * 7094 * @param pressed The new pressed state 7095 */ 7096 protected void dispatchSetPressed(boolean pressed) { 7097 } 7098 7099 /** 7100 * Indicates whether the view is currently in pressed state. Unless 7101 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 7102 * the pressed state. 7103 * 7104 * @see #setPressed(boolean) 7105 * @see #isClickable() 7106 * @see #setClickable(boolean) 7107 * 7108 * @return true if the view is currently pressed, false otherwise 7109 */ 7110 @ViewDebug.ExportedProperty 7111 public boolean isPressed() { 7112 return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED; 7113 } 7114 7115 /** 7116 * Indicates whether this view will save its state (that is, 7117 * whether its {@link #onSaveInstanceState} method will be called). 7118 * 7119 * @return Returns true if the view state saving is enabled, else false. 7120 * 7121 * @see #setSaveEnabled(boolean) 7122 * @attr ref android.R.styleable#View_saveEnabled 7123 */ 7124 public boolean isSaveEnabled() { 7125 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 7126 } 7127 7128 /** 7129 * Controls whether the saving of this view's state is 7130 * enabled (that is, whether its {@link #onSaveInstanceState} method 7131 * will be called). Note that even if freezing is enabled, the 7132 * view still must have an id assigned to it (via {@link #setId(int)}) 7133 * for its state to be saved. This flag can only disable the 7134 * saving of this view; any child views may still have their state saved. 7135 * 7136 * @param enabled Set to false to <em>disable</em> state saving, or true 7137 * (the default) to allow it. 7138 * 7139 * @see #isSaveEnabled() 7140 * @see #setId(int) 7141 * @see #onSaveInstanceState() 7142 * @attr ref android.R.styleable#View_saveEnabled 7143 */ 7144 public void setSaveEnabled(boolean enabled) { 7145 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 7146 } 7147 7148 /** 7149 * Gets whether the framework should discard touches when the view's 7150 * window is obscured by another visible window. 7151 * Refer to the {@link View} security documentation for more details. 7152 * 7153 * @return True if touch filtering is enabled. 7154 * 7155 * @see #setFilterTouchesWhenObscured(boolean) 7156 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 7157 */ 7158 @ViewDebug.ExportedProperty 7159 public boolean getFilterTouchesWhenObscured() { 7160 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 7161 } 7162 7163 /** 7164 * Sets whether the framework should discard touches when the view's 7165 * window is obscured by another visible window. 7166 * Refer to the {@link View} security documentation for more details. 7167 * 7168 * @param enabled True if touch filtering should be enabled. 7169 * 7170 * @see #getFilterTouchesWhenObscured 7171 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 7172 */ 7173 public void setFilterTouchesWhenObscured(boolean enabled) { 7174 setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0, 7175 FILTER_TOUCHES_WHEN_OBSCURED); 7176 } 7177 7178 /** 7179 * Indicates whether the entire hierarchy under this view will save its 7180 * state when a state saving traversal occurs from its parent. The default 7181 * is true; if false, these views will not be saved unless 7182 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 7183 * 7184 * @return Returns true if the view state saving from parent is enabled, else false. 7185 * 7186 * @see #setSaveFromParentEnabled(boolean) 7187 */ 7188 public boolean isSaveFromParentEnabled() { 7189 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 7190 } 7191 7192 /** 7193 * Controls whether the entire hierarchy under this view will save its 7194 * state when a state saving traversal occurs from its parent. The default 7195 * is true; if false, these views will not be saved unless 7196 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 7197 * 7198 * @param enabled Set to false to <em>disable</em> state saving, or true 7199 * (the default) to allow it. 7200 * 7201 * @see #isSaveFromParentEnabled() 7202 * @see #setId(int) 7203 * @see #onSaveInstanceState() 7204 */ 7205 public void setSaveFromParentEnabled(boolean enabled) { 7206 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 7207 } 7208 7209 7210 /** 7211 * Returns whether this View is able to take focus. 7212 * 7213 * @return True if this view can take focus, or false otherwise. 7214 * @attr ref android.R.styleable#View_focusable 7215 */ 7216 @ViewDebug.ExportedProperty(category = "focus") 7217 public final boolean isFocusable() { 7218 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 7219 } 7220 7221 /** 7222 * When a view is focusable, it may not want to take focus when in touch mode. 7223 * For example, a button would like focus when the user is navigating via a D-pad 7224 * so that the user can click on it, but once the user starts touching the screen, 7225 * the button shouldn't take focus 7226 * @return Whether the view is focusable in touch mode. 7227 * @attr ref android.R.styleable#View_focusableInTouchMode 7228 */ 7229 @ViewDebug.ExportedProperty 7230 public final boolean isFocusableInTouchMode() { 7231 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 7232 } 7233 7234 /** 7235 * Find the nearest view in the specified direction that can take focus. 7236 * This does not actually give focus to that view. 7237 * 7238 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7239 * 7240 * @return The nearest focusable in the specified direction, or null if none 7241 * can be found. 7242 */ 7243 public View focusSearch(@FocusRealDirection int direction) { 7244 if (mParent != null) { 7245 return mParent.focusSearch(this, direction); 7246 } else { 7247 return null; 7248 } 7249 } 7250 7251 /** 7252 * This method is the last chance for the focused view and its ancestors to 7253 * respond to an arrow key. This is called when the focused view did not 7254 * consume the key internally, nor could the view system find a new view in 7255 * the requested direction to give focus to. 7256 * 7257 * @param focused The currently focused view. 7258 * @param direction The direction focus wants to move. One of FOCUS_UP, 7259 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 7260 * @return True if the this view consumed this unhandled move. 7261 */ 7262 public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) { 7263 return false; 7264 } 7265 7266 /** 7267 * If a user manually specified the next view id for a particular direction, 7268 * use the root to look up the view. 7269 * @param root The root view of the hierarchy containing this view. 7270 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 7271 * or FOCUS_BACKWARD. 7272 * @return The user specified next view, or null if there is none. 7273 */ 7274 View findUserSetNextFocus(View root, @FocusDirection int direction) { 7275 switch (direction) { 7276 case FOCUS_LEFT: 7277 if (mNextFocusLeftId == View.NO_ID) return null; 7278 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 7279 case FOCUS_RIGHT: 7280 if (mNextFocusRightId == View.NO_ID) return null; 7281 return findViewInsideOutShouldExist(root, mNextFocusRightId); 7282 case FOCUS_UP: 7283 if (mNextFocusUpId == View.NO_ID) return null; 7284 return findViewInsideOutShouldExist(root, mNextFocusUpId); 7285 case FOCUS_DOWN: 7286 if (mNextFocusDownId == View.NO_ID) return null; 7287 return findViewInsideOutShouldExist(root, mNextFocusDownId); 7288 case FOCUS_FORWARD: 7289 if (mNextFocusForwardId == View.NO_ID) return null; 7290 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 7291 case FOCUS_BACKWARD: { 7292 if (mID == View.NO_ID) return null; 7293 final int id = mID; 7294 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 7295 @Override 7296 public boolean apply(View t) { 7297 return t.mNextFocusForwardId == id; 7298 } 7299 }); 7300 } 7301 } 7302 return null; 7303 } 7304 7305 private View findViewInsideOutShouldExist(View root, int id) { 7306 if (mMatchIdPredicate == null) { 7307 mMatchIdPredicate = new MatchIdPredicate(); 7308 } 7309 mMatchIdPredicate.mId = id; 7310 View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate); 7311 if (result == null) { 7312 Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id); 7313 } 7314 return result; 7315 } 7316 7317 /** 7318 * Find and return all focusable views that are descendants of this view, 7319 * possibly including this view if it is focusable itself. 7320 * 7321 * @param direction The direction of the focus 7322 * @return A list of focusable views 7323 */ 7324 public ArrayList<View> getFocusables(@FocusDirection int direction) { 7325 ArrayList<View> result = new ArrayList<View>(24); 7326 addFocusables(result, direction); 7327 return result; 7328 } 7329 7330 /** 7331 * Add any focusable views that are descendants of this view (possibly 7332 * including this view if it is focusable itself) to views. If we are in touch mode, 7333 * only add views that are also focusable in touch mode. 7334 * 7335 * @param views Focusable views found so far 7336 * @param direction The direction of the focus 7337 */ 7338 public void addFocusables(ArrayList<View> views, @FocusDirection int direction) { 7339 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 7340 } 7341 7342 /** 7343 * Adds any focusable views that are descendants of this view (possibly 7344 * including this view if it is focusable itself) to views. This method 7345 * adds all focusable views regardless if we are in touch mode or 7346 * only views focusable in touch mode if we are in touch mode or 7347 * only views that can take accessibility focus if accessibility is enabeld 7348 * depending on the focusable mode paramater. 7349 * 7350 * @param views Focusable views found so far or null if all we are interested is 7351 * the number of focusables. 7352 * @param direction The direction of the focus. 7353 * @param focusableMode The type of focusables to be added. 7354 * 7355 * @see #FOCUSABLES_ALL 7356 * @see #FOCUSABLES_TOUCH_MODE 7357 */ 7358 public void addFocusables(ArrayList<View> views, @FocusDirection int direction, 7359 @FocusableMode int focusableMode) { 7360 if (views == null) { 7361 return; 7362 } 7363 if (!isFocusable()) { 7364 return; 7365 } 7366 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE 7367 && isInTouchMode() && !isFocusableInTouchMode()) { 7368 return; 7369 } 7370 views.add(this); 7371 } 7372 7373 /** 7374 * Finds the Views that contain given text. The containment is case insensitive. 7375 * The search is performed by either the text that the View renders or the content 7376 * description that describes the view for accessibility purposes and the view does 7377 * not render or both. Clients can specify how the search is to be performed via 7378 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 7379 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 7380 * 7381 * @param outViews The output list of matching Views. 7382 * @param searched The text to match against. 7383 * 7384 * @see #FIND_VIEWS_WITH_TEXT 7385 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 7386 * @see #setContentDescription(CharSequence) 7387 */ 7388 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, 7389 @FindViewFlags int flags) { 7390 if (getAccessibilityNodeProvider() != null) { 7391 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 7392 outViews.add(this); 7393 } 7394 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 7395 && (searched != null && searched.length() > 0) 7396 && (mContentDescription != null && mContentDescription.length() > 0)) { 7397 String searchedLowerCase = searched.toString().toLowerCase(); 7398 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 7399 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 7400 outViews.add(this); 7401 } 7402 } 7403 } 7404 7405 /** 7406 * Find and return all touchable views that are descendants of this view, 7407 * possibly including this view if it is touchable itself. 7408 * 7409 * @return A list of touchable views 7410 */ 7411 public ArrayList<View> getTouchables() { 7412 ArrayList<View> result = new ArrayList<View>(); 7413 addTouchables(result); 7414 return result; 7415 } 7416 7417 /** 7418 * Add any touchable views that are descendants of this view (possibly 7419 * including this view if it is touchable itself) to views. 7420 * 7421 * @param views Touchable views found so far 7422 */ 7423 public void addTouchables(ArrayList<View> views) { 7424 final int viewFlags = mViewFlags; 7425 7426 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 7427 && (viewFlags & ENABLED_MASK) == ENABLED) { 7428 views.add(this); 7429 } 7430 } 7431 7432 /** 7433 * Returns whether this View is accessibility focused. 7434 * 7435 * @return True if this View is accessibility focused. 7436 */ 7437 public boolean isAccessibilityFocused() { 7438 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0; 7439 } 7440 7441 /** 7442 * Call this to try to give accessibility focus to this view. 7443 * 7444 * A view will not actually take focus if {@link AccessibilityManager#isEnabled()} 7445 * returns false or the view is no visible or the view already has accessibility 7446 * focus. 7447 * 7448 * See also {@link #focusSearch(int)}, which is what you call to say that you 7449 * have focus, and you want your parent to look for the next one. 7450 * 7451 * @return Whether this view actually took accessibility focus. 7452 * 7453 * @hide 7454 */ 7455 public boolean requestAccessibilityFocus() { 7456 AccessibilityManager manager = AccessibilityManager.getInstance(mContext); 7457 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 7458 return false; 7459 } 7460 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7461 return false; 7462 } 7463 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) { 7464 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED; 7465 ViewRootImpl viewRootImpl = getViewRootImpl(); 7466 if (viewRootImpl != null) { 7467 viewRootImpl.setAccessibilityFocus(this, null); 7468 } 7469 invalidate(); 7470 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); 7471 return true; 7472 } 7473 return false; 7474 } 7475 7476 /** 7477 * Call this to try to clear accessibility focus of this view. 7478 * 7479 * See also {@link #focusSearch(int)}, which is what you call to say that you 7480 * have focus, and you want your parent to look for the next one. 7481 * 7482 * @hide 7483 */ 7484 public void clearAccessibilityFocus() { 7485 clearAccessibilityFocusNoCallbacks(); 7486 // Clear the global reference of accessibility focus if this 7487 // view or any of its descendants had accessibility focus. 7488 ViewRootImpl viewRootImpl = getViewRootImpl(); 7489 if (viewRootImpl != null) { 7490 View focusHost = viewRootImpl.getAccessibilityFocusedHost(); 7491 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 7492 viewRootImpl.setAccessibilityFocus(null, null); 7493 } 7494 } 7495 } 7496 7497 private void sendAccessibilityHoverEvent(int eventType) { 7498 // Since we are not delivering to a client accessibility events from not 7499 // important views (unless the clinet request that) we need to fire the 7500 // event from the deepest view exposed to the client. As a consequence if 7501 // the user crosses a not exposed view the client will see enter and exit 7502 // of the exposed predecessor followed by and enter and exit of that same 7503 // predecessor when entering and exiting the not exposed descendant. This 7504 // is fine since the client has a clear idea which view is hovered at the 7505 // price of a couple more events being sent. This is a simple and 7506 // working solution. 7507 View source = this; 7508 while (true) { 7509 if (source.includeForAccessibility()) { 7510 source.sendAccessibilityEvent(eventType); 7511 return; 7512 } 7513 ViewParent parent = source.getParent(); 7514 if (parent instanceof View) { 7515 source = (View) parent; 7516 } else { 7517 return; 7518 } 7519 } 7520 } 7521 7522 /** 7523 * Clears accessibility focus without calling any callback methods 7524 * normally invoked in {@link #clearAccessibilityFocus()}. This method 7525 * is used for clearing accessibility focus when giving this focus to 7526 * another view. 7527 */ 7528 void clearAccessibilityFocusNoCallbacks() { 7529 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 7530 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 7531 invalidate(); 7532 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); 7533 } 7534 } 7535 7536 /** 7537 * Call this to try to give focus to a specific view or to one of its 7538 * descendants. 7539 * 7540 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7541 * false), or if it is focusable and it is not focusable in touch mode 7542 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7543 * 7544 * See also {@link #focusSearch(int)}, which is what you call to say that you 7545 * have focus, and you want your parent to look for the next one. 7546 * 7547 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 7548 * {@link #FOCUS_DOWN} and <code>null</code>. 7549 * 7550 * @return Whether this view or one of its descendants actually took focus. 7551 */ 7552 public final boolean requestFocus() { 7553 return requestFocus(View.FOCUS_DOWN); 7554 } 7555 7556 /** 7557 * Call this to try to give focus to a specific view or to one of its 7558 * descendants and give it a hint about what direction focus is heading. 7559 * 7560 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7561 * false), or if it is focusable and it is not focusable in touch mode 7562 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7563 * 7564 * See also {@link #focusSearch(int)}, which is what you call to say that you 7565 * have focus, and you want your parent to look for the next one. 7566 * 7567 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 7568 * <code>null</code> set for the previously focused rectangle. 7569 * 7570 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7571 * @return Whether this view or one of its descendants actually took focus. 7572 */ 7573 public final boolean requestFocus(int direction) { 7574 return requestFocus(direction, null); 7575 } 7576 7577 /** 7578 * Call this to try to give focus to a specific view or to one of its descendants 7579 * and give it hints about the direction and a specific rectangle that the focus 7580 * is coming from. The rectangle can help give larger views a finer grained hint 7581 * about where focus is coming from, and therefore, where to show selection, or 7582 * forward focus change internally. 7583 * 7584 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7585 * false), or if it is focusable and it is not focusable in touch mode 7586 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7587 * 7588 * A View will not take focus if it is not visible. 7589 * 7590 * A View will not take focus if one of its parents has 7591 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 7592 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 7593 * 7594 * See also {@link #focusSearch(int)}, which is what you call to say that you 7595 * have focus, and you want your parent to look for the next one. 7596 * 7597 * You may wish to override this method if your custom {@link View} has an internal 7598 * {@link View} that it wishes to forward the request to. 7599 * 7600 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7601 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 7602 * to give a finer grained hint about where focus is coming from. May be null 7603 * if there is no hint. 7604 * @return Whether this view or one of its descendants actually took focus. 7605 */ 7606 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 7607 return requestFocusNoSearch(direction, previouslyFocusedRect); 7608 } 7609 7610 private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) { 7611 // need to be focusable 7612 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 7613 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7614 return false; 7615 } 7616 7617 // need to be focusable in touch mode if in touch mode 7618 if (isInTouchMode() && 7619 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 7620 return false; 7621 } 7622 7623 // need to not have any parents blocking us 7624 if (hasAncestorThatBlocksDescendantFocus()) { 7625 return false; 7626 } 7627 7628 handleFocusGainInternal(direction, previouslyFocusedRect); 7629 return true; 7630 } 7631 7632 /** 7633 * Call this to try to give focus to a specific view or to one of its descendants. This is a 7634 * special variant of {@link #requestFocus() } that will allow views that are not focuable in 7635 * touch mode to request focus when they are touched. 7636 * 7637 * @return Whether this view or one of its descendants actually took focus. 7638 * 7639 * @see #isInTouchMode() 7640 * 7641 */ 7642 public final boolean requestFocusFromTouch() { 7643 // Leave touch mode if we need to 7644 if (isInTouchMode()) { 7645 ViewRootImpl viewRoot = getViewRootImpl(); 7646 if (viewRoot != null) { 7647 viewRoot.ensureTouchMode(false); 7648 } 7649 } 7650 return requestFocus(View.FOCUS_DOWN); 7651 } 7652 7653 /** 7654 * @return Whether any ancestor of this view blocks descendant focus. 7655 */ 7656 private boolean hasAncestorThatBlocksDescendantFocus() { 7657 final boolean focusableInTouchMode = isFocusableInTouchMode(); 7658 ViewParent ancestor = mParent; 7659 while (ancestor instanceof ViewGroup) { 7660 final ViewGroup vgAncestor = (ViewGroup) ancestor; 7661 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS 7662 || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) { 7663 return true; 7664 } else { 7665 ancestor = vgAncestor.getParent(); 7666 } 7667 } 7668 return false; 7669 } 7670 7671 /** 7672 * Gets the mode for determining whether this View is important for accessibility 7673 * which is if it fires accessibility events and if it is reported to 7674 * accessibility services that query the screen. 7675 * 7676 * @return The mode for determining whether a View is important for accessibility. 7677 * 7678 * @attr ref android.R.styleable#View_importantForAccessibility 7679 * 7680 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 7681 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 7682 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 7683 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 7684 */ 7685 @ViewDebug.ExportedProperty(category = "accessibility", mapping = { 7686 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"), 7687 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"), 7688 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"), 7689 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS, 7690 to = "noHideDescendants") 7691 }) 7692 public int getImportantForAccessibility() { 7693 return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 7694 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 7695 } 7696 7697 /** 7698 * Sets the live region mode for this view. This indicates to accessibility 7699 * services whether they should automatically notify the user about changes 7700 * to the view's content description or text, or to the content descriptions 7701 * or text of the view's children (where applicable). 7702 * <p> 7703 * For example, in a login screen with a TextView that displays an "incorrect 7704 * password" notification, that view should be marked as a live region with 7705 * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 7706 * <p> 7707 * To disable change notifications for this view, use 7708 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region 7709 * mode for most views. 7710 * <p> 7711 * To indicate that the user should be notified of changes, use 7712 * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 7713 * <p> 7714 * If the view's changes should interrupt ongoing speech and notify the user 7715 * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}. 7716 * 7717 * @param mode The live region mode for this view, one of: 7718 * <ul> 7719 * <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE} 7720 * <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE} 7721 * <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE} 7722 * </ul> 7723 * @attr ref android.R.styleable#View_accessibilityLiveRegion 7724 */ 7725 public void setAccessibilityLiveRegion(int mode) { 7726 if (mode != getAccessibilityLiveRegion()) { 7727 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 7728 mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT) 7729 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 7730 notifyViewAccessibilityStateChangedIfNeeded( 7731 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7732 } 7733 } 7734 7735 /** 7736 * Gets the live region mode for this View. 7737 * 7738 * @return The live region mode for the view. 7739 * 7740 * @attr ref android.R.styleable#View_accessibilityLiveRegion 7741 * 7742 * @see #setAccessibilityLiveRegion(int) 7743 */ 7744 public int getAccessibilityLiveRegion() { 7745 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK) 7746 >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 7747 } 7748 7749 /** 7750 * Sets how to determine whether this view is important for accessibility 7751 * which is if it fires accessibility events and if it is reported to 7752 * accessibility services that query the screen. 7753 * 7754 * @param mode How to determine whether this view is important for accessibility. 7755 * 7756 * @attr ref android.R.styleable#View_importantForAccessibility 7757 * 7758 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 7759 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 7760 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 7761 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 7762 */ 7763 public void setImportantForAccessibility(int mode) { 7764 final int oldMode = getImportantForAccessibility(); 7765 if (mode != oldMode) { 7766 // If we're moving between AUTO and another state, we might not need 7767 // to send a subtree changed notification. We'll store the computed 7768 // importance, since we'll need to check it later to make sure. 7769 final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO 7770 || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO; 7771 final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility(); 7772 mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 7773 mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT) 7774 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 7775 if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) { 7776 notifySubtreeAccessibilityStateChangedIfNeeded(); 7777 } else { 7778 notifyViewAccessibilityStateChangedIfNeeded( 7779 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7780 } 7781 } 7782 } 7783 7784 /** 7785 * Computes whether this view should be exposed for accessibility. In 7786 * general, views that are interactive or provide information are exposed 7787 * while views that serve only as containers are hidden. 7788 * <p> 7789 * If an ancestor of this view has importance 7790 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method 7791 * returns <code>false</code>. 7792 * <p> 7793 * Otherwise, the value is computed according to the view's 7794 * {@link #getImportantForAccessibility()} value: 7795 * <ol> 7796 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or 7797 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false 7798 * </code> 7799 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code> 7800 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if 7801 * view satisfies any of the following: 7802 * <ul> 7803 * <li>Is actionable, e.g. {@link #isClickable()}, 7804 * {@link #isLongClickable()}, or {@link #isFocusable()} 7805 * <li>Has an {@link AccessibilityDelegate} 7806 * <li>Has an interaction listener, e.g. {@link OnTouchListener}, 7807 * {@link OnKeyListener}, etc. 7808 * <li>Is an accessibility live region, e.g. 7809 * {@link #getAccessibilityLiveRegion()} is not 7810 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. 7811 * </ul> 7812 * </ol> 7813 * 7814 * @return Whether the view is exposed for accessibility. 7815 * @see #setImportantForAccessibility(int) 7816 * @see #getImportantForAccessibility() 7817 */ 7818 public boolean isImportantForAccessibility() { 7819 final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 7820 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 7821 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO 7822 || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 7823 return false; 7824 } 7825 7826 // Check parent mode to ensure we're not hidden. 7827 ViewParent parent = mParent; 7828 while (parent instanceof View) { 7829 if (((View) parent).getImportantForAccessibility() 7830 == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 7831 return false; 7832 } 7833 parent = parent.getParent(); 7834 } 7835 7836 return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility() 7837 || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null 7838 || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE; 7839 } 7840 7841 /** 7842 * Gets the parent for accessibility purposes. Note that the parent for 7843 * accessibility is not necessary the immediate parent. It is the first 7844 * predecessor that is important for accessibility. 7845 * 7846 * @return The parent for accessibility purposes. 7847 */ 7848 public ViewParent getParentForAccessibility() { 7849 if (mParent instanceof View) { 7850 View parentView = (View) mParent; 7851 if (parentView.includeForAccessibility()) { 7852 return mParent; 7853 } else { 7854 return mParent.getParentForAccessibility(); 7855 } 7856 } 7857 return null; 7858 } 7859 7860 /** 7861 * Adds the children of a given View for accessibility. Since some Views are 7862 * not important for accessibility the children for accessibility are not 7863 * necessarily direct children of the view, rather they are the first level of 7864 * descendants important for accessibility. 7865 * 7866 * @param children The list of children for accessibility. 7867 */ 7868 public void addChildrenForAccessibility(ArrayList<View> children) { 7869 7870 } 7871 7872 /** 7873 * Whether to regard this view for accessibility. A view is regarded for 7874 * accessibility if it is important for accessibility or the querying 7875 * accessibility service has explicitly requested that view not 7876 * important for accessibility are regarded. 7877 * 7878 * @return Whether to regard the view for accessibility. 7879 * 7880 * @hide 7881 */ 7882 public boolean includeForAccessibility() { 7883 if (mAttachInfo != null) { 7884 return (mAttachInfo.mAccessibilityFetchFlags 7885 & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0 7886 || isImportantForAccessibility(); 7887 } 7888 return false; 7889 } 7890 7891 /** 7892 * Returns whether the View is considered actionable from 7893 * accessibility perspective. Such view are important for 7894 * accessibility. 7895 * 7896 * @return True if the view is actionable for accessibility. 7897 * 7898 * @hide 7899 */ 7900 public boolean isActionableForAccessibility() { 7901 return (isClickable() || isLongClickable() || isFocusable()); 7902 } 7903 7904 /** 7905 * Returns whether the View has registered callbacks which makes it 7906 * important for accessibility. 7907 * 7908 * @return True if the view is actionable for accessibility. 7909 */ 7910 private boolean hasListenersForAccessibility() { 7911 ListenerInfo info = getListenerInfo(); 7912 return mTouchDelegate != null || info.mOnKeyListener != null 7913 || info.mOnTouchListener != null || info.mOnGenericMotionListener != null 7914 || info.mOnHoverListener != null || info.mOnDragListener != null; 7915 } 7916 7917 /** 7918 * Notifies that the accessibility state of this view changed. The change 7919 * is local to this view and does not represent structural changes such 7920 * as children and parent. For example, the view became focusable. The 7921 * notification is at at most once every 7922 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 7923 * to avoid unnecessary load to the system. Also once a view has a pending 7924 * notification this method is a NOP until the notification has been sent. 7925 * 7926 * @hide 7927 */ 7928 public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) { 7929 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 7930 return; 7931 } 7932 if (mSendViewStateChangedAccessibilityEvent == null) { 7933 mSendViewStateChangedAccessibilityEvent = 7934 new SendViewStateChangedAccessibilityEvent(); 7935 } 7936 mSendViewStateChangedAccessibilityEvent.runOrPost(changeType); 7937 } 7938 7939 /** 7940 * Notifies that the accessibility state of this view changed. The change 7941 * is *not* local to this view and does represent structural changes such 7942 * as children and parent. For example, the view size changed. The 7943 * notification is at at most once every 7944 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 7945 * to avoid unnecessary load to the system. Also once a view has a pending 7946 * notification this method is a NOP until the notification has been sent. 7947 * 7948 * @hide 7949 */ 7950 public void notifySubtreeAccessibilityStateChangedIfNeeded() { 7951 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 7952 return; 7953 } 7954 if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) { 7955 mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 7956 if (mParent != null) { 7957 try { 7958 mParent.notifySubtreeAccessibilityStateChanged( 7959 this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE); 7960 } catch (AbstractMethodError e) { 7961 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 7962 " does not fully implement ViewParent", e); 7963 } 7964 } 7965 } 7966 } 7967 7968 /** 7969 * Reset the flag indicating the accessibility state of the subtree rooted 7970 * at this view changed. 7971 */ 7972 void resetSubtreeAccessibilityStateChanged() { 7973 mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 7974 } 7975 7976 /** 7977 * Performs the specified accessibility action on the view. For 7978 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 7979 * <p> 7980 * If an {@link AccessibilityDelegate} has been specified via calling 7981 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 7982 * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)} 7983 * is responsible for handling this call. 7984 * </p> 7985 * 7986 * @param action The action to perform. 7987 * @param arguments Optional action arguments. 7988 * @return Whether the action was performed. 7989 */ 7990 public boolean performAccessibilityAction(int action, Bundle arguments) { 7991 if (mAccessibilityDelegate != null) { 7992 return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments); 7993 } else { 7994 return performAccessibilityActionInternal(action, arguments); 7995 } 7996 } 7997 7998 /** 7999 * @see #performAccessibilityAction(int, Bundle) 8000 * 8001 * Note: Called from the default {@link AccessibilityDelegate}. 8002 */ 8003 boolean performAccessibilityActionInternal(int action, Bundle arguments) { 8004 switch (action) { 8005 case AccessibilityNodeInfo.ACTION_CLICK: { 8006 if (isClickable()) { 8007 performClick(); 8008 return true; 8009 } 8010 } break; 8011 case AccessibilityNodeInfo.ACTION_LONG_CLICK: { 8012 if (isLongClickable()) { 8013 performLongClick(); 8014 return true; 8015 } 8016 } break; 8017 case AccessibilityNodeInfo.ACTION_FOCUS: { 8018 if (!hasFocus()) { 8019 // Get out of touch mode since accessibility 8020 // wants to move focus around. 8021 getViewRootImpl().ensureTouchMode(false); 8022 return requestFocus(); 8023 } 8024 } break; 8025 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 8026 if (hasFocus()) { 8027 clearFocus(); 8028 return !isFocused(); 8029 } 8030 } break; 8031 case AccessibilityNodeInfo.ACTION_SELECT: { 8032 if (!isSelected()) { 8033 setSelected(true); 8034 return isSelected(); 8035 } 8036 } break; 8037 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: { 8038 if (isSelected()) { 8039 setSelected(false); 8040 return !isSelected(); 8041 } 8042 } break; 8043 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 8044 if (!isAccessibilityFocused()) { 8045 return requestAccessibilityFocus(); 8046 } 8047 } break; 8048 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 8049 if (isAccessibilityFocused()) { 8050 clearAccessibilityFocus(); 8051 return true; 8052 } 8053 } break; 8054 case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { 8055 if (arguments != null) { 8056 final int granularity = arguments.getInt( 8057 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 8058 final boolean extendSelection = arguments.getBoolean( 8059 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 8060 return traverseAtGranularity(granularity, true, extendSelection); 8061 } 8062 } break; 8063 case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { 8064 if (arguments != null) { 8065 final int granularity = arguments.getInt( 8066 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 8067 final boolean extendSelection = arguments.getBoolean( 8068 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 8069 return traverseAtGranularity(granularity, false, extendSelection); 8070 } 8071 } break; 8072 case AccessibilityNodeInfo.ACTION_SET_SELECTION: { 8073 CharSequence text = getIterableTextForAccessibility(); 8074 if (text == null) { 8075 return false; 8076 } 8077 final int start = (arguments != null) ? arguments.getInt( 8078 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1; 8079 final int end = (arguments != null) ? arguments.getInt( 8080 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1; 8081 // Only cursor position can be specified (selection length == 0) 8082 if ((getAccessibilitySelectionStart() != start 8083 || getAccessibilitySelectionEnd() != end) 8084 && (start == end)) { 8085 setAccessibilitySelection(start, end); 8086 notifyViewAccessibilityStateChangedIfNeeded( 8087 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 8088 return true; 8089 } 8090 } break; 8091 } 8092 return false; 8093 } 8094 8095 private boolean traverseAtGranularity(int granularity, boolean forward, 8096 boolean extendSelection) { 8097 CharSequence text = getIterableTextForAccessibility(); 8098 if (text == null || text.length() == 0) { 8099 return false; 8100 } 8101 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 8102 if (iterator == null) { 8103 return false; 8104 } 8105 int current = getAccessibilitySelectionEnd(); 8106 if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 8107 current = forward ? 0 : text.length(); 8108 } 8109 final int[] range = forward ? iterator.following(current) : iterator.preceding(current); 8110 if (range == null) { 8111 return false; 8112 } 8113 final int segmentStart = range[0]; 8114 final int segmentEnd = range[1]; 8115 int selectionStart; 8116 int selectionEnd; 8117 if (extendSelection && isAccessibilitySelectionExtendable()) { 8118 selectionStart = getAccessibilitySelectionStart(); 8119 if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 8120 selectionStart = forward ? segmentStart : segmentEnd; 8121 } 8122 selectionEnd = forward ? segmentEnd : segmentStart; 8123 } else { 8124 selectionStart = selectionEnd= forward ? segmentEnd : segmentStart; 8125 } 8126 setAccessibilitySelection(selectionStart, selectionEnd); 8127 final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY 8128 : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY; 8129 sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd); 8130 return true; 8131 } 8132 8133 /** 8134 * Gets the text reported for accessibility purposes. 8135 * 8136 * @return The accessibility text. 8137 * 8138 * @hide 8139 */ 8140 public CharSequence getIterableTextForAccessibility() { 8141 return getContentDescription(); 8142 } 8143 8144 /** 8145 * Gets whether accessibility selection can be extended. 8146 * 8147 * @return If selection is extensible. 8148 * 8149 * @hide 8150 */ 8151 public boolean isAccessibilitySelectionExtendable() { 8152 return false; 8153 } 8154 8155 /** 8156 * @hide 8157 */ 8158 public int getAccessibilitySelectionStart() { 8159 return mAccessibilityCursorPosition; 8160 } 8161 8162 /** 8163 * @hide 8164 */ 8165 public int getAccessibilitySelectionEnd() { 8166 return getAccessibilitySelectionStart(); 8167 } 8168 8169 /** 8170 * @hide 8171 */ 8172 public void setAccessibilitySelection(int start, int end) { 8173 if (start == end && end == mAccessibilityCursorPosition) { 8174 return; 8175 } 8176 if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) { 8177 mAccessibilityCursorPosition = start; 8178 } else { 8179 mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 8180 } 8181 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); 8182 } 8183 8184 private void sendViewTextTraversedAtGranularityEvent(int action, int granularity, 8185 int fromIndex, int toIndex) { 8186 if (mParent == null) { 8187 return; 8188 } 8189 AccessibilityEvent event = AccessibilityEvent.obtain( 8190 AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY); 8191 onInitializeAccessibilityEvent(event); 8192 onPopulateAccessibilityEvent(event); 8193 event.setFromIndex(fromIndex); 8194 event.setToIndex(toIndex); 8195 event.setAction(action); 8196 event.setMovementGranularity(granularity); 8197 mParent.requestSendAccessibilityEvent(this, event); 8198 } 8199 8200 /** 8201 * @hide 8202 */ 8203 public TextSegmentIterator getIteratorForGranularity(int granularity) { 8204 switch (granularity) { 8205 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { 8206 CharSequence text = getIterableTextForAccessibility(); 8207 if (text != null && text.length() > 0) { 8208 CharacterTextSegmentIterator iterator = 8209 CharacterTextSegmentIterator.getInstance( 8210 mContext.getResources().getConfiguration().locale); 8211 iterator.initialize(text.toString()); 8212 return iterator; 8213 } 8214 } break; 8215 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: { 8216 CharSequence text = getIterableTextForAccessibility(); 8217 if (text != null && text.length() > 0) { 8218 WordTextSegmentIterator iterator = 8219 WordTextSegmentIterator.getInstance( 8220 mContext.getResources().getConfiguration().locale); 8221 iterator.initialize(text.toString()); 8222 return iterator; 8223 } 8224 } break; 8225 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: { 8226 CharSequence text = getIterableTextForAccessibility(); 8227 if (text != null && text.length() > 0) { 8228 ParagraphTextSegmentIterator iterator = 8229 ParagraphTextSegmentIterator.getInstance(); 8230 iterator.initialize(text.toString()); 8231 return iterator; 8232 } 8233 } break; 8234 } 8235 return null; 8236 } 8237 8238 /** 8239 * @hide 8240 */ 8241 public void dispatchStartTemporaryDetach() { 8242 onStartTemporaryDetach(); 8243 } 8244 8245 /** 8246 * This is called when a container is going to temporarily detach a child, with 8247 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 8248 * It will either be followed by {@link #onFinishTemporaryDetach()} or 8249 * {@link #onDetachedFromWindow()} when the container is done. 8250 */ 8251 public void onStartTemporaryDetach() { 8252 removeUnsetPressCallback(); 8253 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 8254 } 8255 8256 /** 8257 * @hide 8258 */ 8259 public void dispatchFinishTemporaryDetach() { 8260 onFinishTemporaryDetach(); 8261 } 8262 8263 /** 8264 * Called after {@link #onStartTemporaryDetach} when the container is done 8265 * changing the view. 8266 */ 8267 public void onFinishTemporaryDetach() { 8268 } 8269 8270 /** 8271 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 8272 * for this view's window. Returns null if the view is not currently attached 8273 * to the window. Normally you will not need to use this directly, but 8274 * just use the standard high-level event callbacks like 8275 * {@link #onKeyDown(int, KeyEvent)}. 8276 */ 8277 public KeyEvent.DispatcherState getKeyDispatcherState() { 8278 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 8279 } 8280 8281 /** 8282 * Dispatch a key event before it is processed by any input method 8283 * associated with the view hierarchy. This can be used to intercept 8284 * key events in special situations before the IME consumes them; a 8285 * typical example would be handling the BACK key to update the application's 8286 * UI instead of allowing the IME to see it and close itself. 8287 * 8288 * @param event The key event to be dispatched. 8289 * @return True if the event was handled, false otherwise. 8290 */ 8291 public boolean dispatchKeyEventPreIme(KeyEvent event) { 8292 return onKeyPreIme(event.getKeyCode(), event); 8293 } 8294 8295 /** 8296 * Dispatch a key event to the next view on the focus path. This path runs 8297 * from the top of the view tree down to the currently focused view. If this 8298 * view has focus, it will dispatch to itself. Otherwise it will dispatch 8299 * the next node down the focus path. This method also fires any key 8300 * listeners. 8301 * 8302 * @param event The key event to be dispatched. 8303 * @return True if the event was handled, false otherwise. 8304 */ 8305 public boolean dispatchKeyEvent(KeyEvent event) { 8306 if (mInputEventConsistencyVerifier != null) { 8307 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 8308 } 8309 8310 // Give any attached key listener a first crack at the event. 8311 //noinspection SimplifiableIfStatement 8312 ListenerInfo li = mListenerInfo; 8313 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 8314 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 8315 return true; 8316 } 8317 8318 if (event.dispatch(this, mAttachInfo != null 8319 ? mAttachInfo.mKeyDispatchState : null, this)) { 8320 return true; 8321 } 8322 8323 if (mInputEventConsistencyVerifier != null) { 8324 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8325 } 8326 return false; 8327 } 8328 8329 /** 8330 * Dispatches a key shortcut event. 8331 * 8332 * @param event The key event to be dispatched. 8333 * @return True if the event was handled by the view, false otherwise. 8334 */ 8335 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 8336 return onKeyShortcut(event.getKeyCode(), event); 8337 } 8338 8339 /** 8340 * Pass the touch screen motion event down to the target view, or this 8341 * view if it is the target. 8342 * 8343 * @param event The motion event to be dispatched. 8344 * @return True if the event was handled by the view, false otherwise. 8345 */ 8346 public boolean dispatchTouchEvent(MotionEvent event) { 8347 boolean result = false; 8348 8349 if (mInputEventConsistencyVerifier != null) { 8350 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 8351 } 8352 8353 final int actionMasked = event.getActionMasked(); 8354 if (actionMasked == MotionEvent.ACTION_DOWN) { 8355 // Defensive cleanup for new gesture 8356 stopNestedScroll(); 8357 } 8358 8359 if (onFilterTouchEventForSecurity(event)) { 8360 //noinspection SimplifiableIfStatement 8361 ListenerInfo li = mListenerInfo; 8362 if (li != null && li.mOnTouchListener != null 8363 && (mViewFlags & ENABLED_MASK) == ENABLED 8364 && li.mOnTouchListener.onTouch(this, event)) { 8365 result = true; 8366 } 8367 8368 if (!result && onTouchEvent(event)) { 8369 result = true; 8370 } 8371 } 8372 8373 if (!result && mInputEventConsistencyVerifier != null) { 8374 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8375 } 8376 8377 // Clean up after nested scrolls if this is the end of a gesture; 8378 // also cancel it if we tried an ACTION_DOWN but we didn't want the rest 8379 // of the gesture. 8380 if (actionMasked == MotionEvent.ACTION_UP || 8381 actionMasked == MotionEvent.ACTION_CANCEL || 8382 (actionMasked == MotionEvent.ACTION_DOWN && !result)) { 8383 stopNestedScroll(); 8384 } 8385 8386 return result; 8387 } 8388 8389 /** 8390 * Filter the touch event to apply security policies. 8391 * 8392 * @param event The motion event to be filtered. 8393 * @return True if the event should be dispatched, false if the event should be dropped. 8394 * 8395 * @see #getFilterTouchesWhenObscured 8396 */ 8397 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 8398 //noinspection RedundantIfStatement 8399 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 8400 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 8401 // Window is obscured, drop this touch. 8402 return false; 8403 } 8404 return true; 8405 } 8406 8407 /** 8408 * Pass a trackball motion event down to the focused view. 8409 * 8410 * @param event The motion event to be dispatched. 8411 * @return True if the event was handled by the view, false otherwise. 8412 */ 8413 public boolean dispatchTrackballEvent(MotionEvent event) { 8414 if (mInputEventConsistencyVerifier != null) { 8415 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 8416 } 8417 8418 return onTrackballEvent(event); 8419 } 8420 8421 /** 8422 * Dispatch a generic motion event. 8423 * <p> 8424 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 8425 * are delivered to the view under the pointer. All other generic motion events are 8426 * delivered to the focused view. Hover events are handled specially and are delivered 8427 * to {@link #onHoverEvent(MotionEvent)}. 8428 * </p> 8429 * 8430 * @param event The motion event to be dispatched. 8431 * @return True if the event was handled by the view, false otherwise. 8432 */ 8433 public boolean dispatchGenericMotionEvent(MotionEvent event) { 8434 if (mInputEventConsistencyVerifier != null) { 8435 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 8436 } 8437 8438 final int source = event.getSource(); 8439 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 8440 final int action = event.getAction(); 8441 if (action == MotionEvent.ACTION_HOVER_ENTER 8442 || action == MotionEvent.ACTION_HOVER_MOVE 8443 || action == MotionEvent.ACTION_HOVER_EXIT) { 8444 if (dispatchHoverEvent(event)) { 8445 return true; 8446 } 8447 } else if (dispatchGenericPointerEvent(event)) { 8448 return true; 8449 } 8450 } else if (dispatchGenericFocusedEvent(event)) { 8451 return true; 8452 } 8453 8454 if (dispatchGenericMotionEventInternal(event)) { 8455 return true; 8456 } 8457 8458 if (mInputEventConsistencyVerifier != null) { 8459 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8460 } 8461 return false; 8462 } 8463 8464 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 8465 //noinspection SimplifiableIfStatement 8466 ListenerInfo li = mListenerInfo; 8467 if (li != null && li.mOnGenericMotionListener != null 8468 && (mViewFlags & ENABLED_MASK) == ENABLED 8469 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 8470 return true; 8471 } 8472 8473 if (onGenericMotionEvent(event)) { 8474 return true; 8475 } 8476 8477 if (mInputEventConsistencyVerifier != null) { 8478 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8479 } 8480 return false; 8481 } 8482 8483 /** 8484 * Dispatch a hover event. 8485 * <p> 8486 * Do not call this method directly. 8487 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8488 * </p> 8489 * 8490 * @param event The motion event to be dispatched. 8491 * @return True if the event was handled by the view, false otherwise. 8492 */ 8493 protected boolean dispatchHoverEvent(MotionEvent event) { 8494 ListenerInfo li = mListenerInfo; 8495 //noinspection SimplifiableIfStatement 8496 if (li != null && li.mOnHoverListener != null 8497 && (mViewFlags & ENABLED_MASK) == ENABLED 8498 && li.mOnHoverListener.onHover(this, event)) { 8499 return true; 8500 } 8501 8502 return onHoverEvent(event); 8503 } 8504 8505 /** 8506 * Returns true if the view has a child to which it has recently sent 8507 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 8508 * it does not have a hovered child, then it must be the innermost hovered view. 8509 * @hide 8510 */ 8511 protected boolean hasHoveredChild() { 8512 return false; 8513 } 8514 8515 /** 8516 * Dispatch a generic motion event to the view under the first pointer. 8517 * <p> 8518 * Do not call this method directly. 8519 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8520 * </p> 8521 * 8522 * @param event The motion event to be dispatched. 8523 * @return True if the event was handled by the view, false otherwise. 8524 */ 8525 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 8526 return false; 8527 } 8528 8529 /** 8530 * Dispatch a generic motion event to the currently focused view. 8531 * <p> 8532 * Do not call this method directly. 8533 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8534 * </p> 8535 * 8536 * @param event The motion event to be dispatched. 8537 * @return True if the event was handled by the view, false otherwise. 8538 */ 8539 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 8540 return false; 8541 } 8542 8543 /** 8544 * Dispatch a pointer event. 8545 * <p> 8546 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 8547 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 8548 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 8549 * and should not be expected to handle other pointing device features. 8550 * </p> 8551 * 8552 * @param event The motion event to be dispatched. 8553 * @return True if the event was handled by the view, false otherwise. 8554 * @hide 8555 */ 8556 public final boolean dispatchPointerEvent(MotionEvent event) { 8557 if (event.isTouchEvent()) { 8558 return dispatchTouchEvent(event); 8559 } else { 8560 return dispatchGenericMotionEvent(event); 8561 } 8562 } 8563 8564 /** 8565 * Called when the window containing this view gains or loses window focus. 8566 * ViewGroups should override to route to their children. 8567 * 8568 * @param hasFocus True if the window containing this view now has focus, 8569 * false otherwise. 8570 */ 8571 public void dispatchWindowFocusChanged(boolean hasFocus) { 8572 onWindowFocusChanged(hasFocus); 8573 } 8574 8575 /** 8576 * Called when the window containing this view gains or loses focus. Note 8577 * that this is separate from view focus: to receive key events, both 8578 * your view and its window must have focus. If a window is displayed 8579 * on top of yours that takes input focus, then your own window will lose 8580 * focus but the view focus will remain unchanged. 8581 * 8582 * @param hasWindowFocus True if the window containing this view now has 8583 * focus, false otherwise. 8584 */ 8585 public void onWindowFocusChanged(boolean hasWindowFocus) { 8586 InputMethodManager imm = InputMethodManager.peekInstance(); 8587 if (!hasWindowFocus) { 8588 if (isPressed()) { 8589 setPressed(false); 8590 } 8591 if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 8592 imm.focusOut(this); 8593 } 8594 removeLongPressCallback(); 8595 removeTapCallback(); 8596 onFocusLost(); 8597 } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 8598 imm.focusIn(this); 8599 } 8600 refreshDrawableState(); 8601 } 8602 8603 /** 8604 * Returns true if this view is in a window that currently has window focus. 8605 * Note that this is not the same as the view itself having focus. 8606 * 8607 * @return True if this view is in a window that currently has window focus. 8608 */ 8609 public boolean hasWindowFocus() { 8610 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 8611 } 8612 8613 /** 8614 * Dispatch a view visibility change down the view hierarchy. 8615 * ViewGroups should override to route to their children. 8616 * @param changedView The view whose visibility changed. Could be 'this' or 8617 * an ancestor view. 8618 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 8619 * {@link #INVISIBLE} or {@link #GONE}. 8620 */ 8621 protected void dispatchVisibilityChanged(@NonNull View changedView, 8622 @Visibility int visibility) { 8623 onVisibilityChanged(changedView, visibility); 8624 } 8625 8626 /** 8627 * Called when the visibility of the view or an ancestor of the view is changed. 8628 * @param changedView The view whose visibility changed. Could be 'this' or 8629 * an ancestor view. 8630 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 8631 * {@link #INVISIBLE} or {@link #GONE}. 8632 */ 8633 protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) { 8634 if (visibility == VISIBLE) { 8635 if (mAttachInfo != null) { 8636 initialAwakenScrollBars(); 8637 } else { 8638 mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 8639 } 8640 } 8641 } 8642 8643 /** 8644 * Dispatch a hint about whether this view is displayed. For instance, when 8645 * a View moves out of the screen, it might receives a display hint indicating 8646 * the view is not displayed. Applications should not <em>rely</em> on this hint 8647 * as there is no guarantee that they will receive one. 8648 * 8649 * @param hint A hint about whether or not this view is displayed: 8650 * {@link #VISIBLE} or {@link #INVISIBLE}. 8651 */ 8652 public void dispatchDisplayHint(@Visibility int hint) { 8653 onDisplayHint(hint); 8654 } 8655 8656 /** 8657 * Gives this view a hint about whether is displayed or not. For instance, when 8658 * a View moves out of the screen, it might receives a display hint indicating 8659 * the view is not displayed. Applications should not <em>rely</em> on this hint 8660 * as there is no guarantee that they will receive one. 8661 * 8662 * @param hint A hint about whether or not this view is displayed: 8663 * {@link #VISIBLE} or {@link #INVISIBLE}. 8664 */ 8665 protected void onDisplayHint(@Visibility int hint) { 8666 } 8667 8668 /** 8669 * Dispatch a window visibility change down the view hierarchy. 8670 * ViewGroups should override to route to their children. 8671 * 8672 * @param visibility The new visibility of the window. 8673 * 8674 * @see #onWindowVisibilityChanged(int) 8675 */ 8676 public void dispatchWindowVisibilityChanged(@Visibility int visibility) { 8677 onWindowVisibilityChanged(visibility); 8678 } 8679 8680 /** 8681 * Called when the window containing has change its visibility 8682 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 8683 * that this tells you whether or not your window is being made visible 8684 * to the window manager; this does <em>not</em> tell you whether or not 8685 * your window is obscured by other windows on the screen, even if it 8686 * is itself visible. 8687 * 8688 * @param visibility The new visibility of the window. 8689 */ 8690 protected void onWindowVisibilityChanged(@Visibility int visibility) { 8691 if (visibility == VISIBLE) { 8692 initialAwakenScrollBars(); 8693 } 8694 } 8695 8696 /** 8697 * Returns the current visibility of the window this view is attached to 8698 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 8699 * 8700 * @return Returns the current visibility of the view's window. 8701 */ 8702 @Visibility 8703 public int getWindowVisibility() { 8704 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 8705 } 8706 8707 /** 8708 * Retrieve the overall visible display size in which the window this view is 8709 * attached to has been positioned in. This takes into account screen 8710 * decorations above the window, for both cases where the window itself 8711 * is being position inside of them or the window is being placed under 8712 * then and covered insets are used for the window to position its content 8713 * inside. In effect, this tells you the available area where content can 8714 * be placed and remain visible to users. 8715 * 8716 * <p>This function requires an IPC back to the window manager to retrieve 8717 * the requested information, so should not be used in performance critical 8718 * code like drawing. 8719 * 8720 * @param outRect Filled in with the visible display frame. If the view 8721 * is not attached to a window, this is simply the raw display size. 8722 */ 8723 public void getWindowVisibleDisplayFrame(Rect outRect) { 8724 if (mAttachInfo != null) { 8725 try { 8726 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 8727 } catch (RemoteException e) { 8728 return; 8729 } 8730 // XXX This is really broken, and probably all needs to be done 8731 // in the window manager, and we need to know more about whether 8732 // we want the area behind or in front of the IME. 8733 final Rect insets = mAttachInfo.mVisibleInsets; 8734 outRect.left += insets.left; 8735 outRect.top += insets.top; 8736 outRect.right -= insets.right; 8737 outRect.bottom -= insets.bottom; 8738 return; 8739 } 8740 // The view is not attached to a display so we don't have a context. 8741 // Make a best guess about the display size. 8742 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 8743 d.getRectSize(outRect); 8744 } 8745 8746 /** 8747 * Dispatch a notification about a resource configuration change down 8748 * the view hierarchy. 8749 * ViewGroups should override to route to their children. 8750 * 8751 * @param newConfig The new resource configuration. 8752 * 8753 * @see #onConfigurationChanged(android.content.res.Configuration) 8754 */ 8755 public void dispatchConfigurationChanged(Configuration newConfig) { 8756 onConfigurationChanged(newConfig); 8757 } 8758 8759 /** 8760 * Called when the current configuration of the resources being used 8761 * by the application have changed. You can use this to decide when 8762 * to reload resources that can changed based on orientation and other 8763 * configuration characterstics. You only need to use this if you are 8764 * not relying on the normal {@link android.app.Activity} mechanism of 8765 * recreating the activity instance upon a configuration change. 8766 * 8767 * @param newConfig The new resource configuration. 8768 */ 8769 protected void onConfigurationChanged(Configuration newConfig) { 8770 } 8771 8772 /** 8773 * Private function to aggregate all per-view attributes in to the view 8774 * root. 8775 */ 8776 void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) { 8777 performCollectViewAttributes(attachInfo, visibility); 8778 } 8779 8780 void performCollectViewAttributes(AttachInfo attachInfo, int visibility) { 8781 if ((visibility & VISIBILITY_MASK) == VISIBLE) { 8782 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 8783 attachInfo.mKeepScreenOn = true; 8784 } 8785 attachInfo.mSystemUiVisibility |= mSystemUiVisibility; 8786 ListenerInfo li = mListenerInfo; 8787 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 8788 attachInfo.mHasSystemUiListeners = true; 8789 } 8790 } 8791 } 8792 8793 void needGlobalAttributesUpdate(boolean force) { 8794 final AttachInfo ai = mAttachInfo; 8795 if (ai != null && !ai.mRecomputeGlobalAttributes) { 8796 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 8797 || ai.mHasSystemUiListeners) { 8798 ai.mRecomputeGlobalAttributes = true; 8799 } 8800 } 8801 } 8802 8803 /** 8804 * Returns whether the device is currently in touch mode. Touch mode is entered 8805 * once the user begins interacting with the device by touch, and affects various 8806 * things like whether focus is always visible to the user. 8807 * 8808 * @return Whether the device is in touch mode. 8809 */ 8810 @ViewDebug.ExportedProperty 8811 public boolean isInTouchMode() { 8812 if (mAttachInfo != null) { 8813 return mAttachInfo.mInTouchMode; 8814 } else { 8815 return ViewRootImpl.isInTouchMode(); 8816 } 8817 } 8818 8819 /** 8820 * Returns the context the view is running in, through which it can 8821 * access the current theme, resources, etc. 8822 * 8823 * @return The view's Context. 8824 */ 8825 @ViewDebug.CapturedViewProperty 8826 public final Context getContext() { 8827 return mContext; 8828 } 8829 8830 /** 8831 * Handle a key event before it is processed by any input method 8832 * associated with the view hierarchy. This can be used to intercept 8833 * key events in special situations before the IME consumes them; a 8834 * typical example would be handling the BACK key to update the application's 8835 * UI instead of allowing the IME to see it and close itself. 8836 * 8837 * @param keyCode The value in event.getKeyCode(). 8838 * @param event Description of the key event. 8839 * @return If you handled the event, return true. If you want to allow the 8840 * event to be handled by the next receiver, return false. 8841 */ 8842 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 8843 return false; 8844 } 8845 8846 /** 8847 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 8848 * KeyEvent.Callback.onKeyDown()}: perform press of the view 8849 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 8850 * is released, if the view is enabled and clickable. 8851 * 8852 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8853 * although some may elect to do so in some situations. Do not rely on this to 8854 * catch software key presses. 8855 * 8856 * @param keyCode A key code that represents the button pressed, from 8857 * {@link android.view.KeyEvent}. 8858 * @param event The KeyEvent object that defines the button action. 8859 */ 8860 public boolean onKeyDown(int keyCode, KeyEvent event) { 8861 boolean result = false; 8862 8863 if (KeyEvent.isConfirmKey(keyCode)) { 8864 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 8865 return true; 8866 } 8867 // Long clickable items don't necessarily have to be clickable 8868 if (((mViewFlags & CLICKABLE) == CLICKABLE || 8869 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 8870 (event.getRepeatCount() == 0)) { 8871 setPressed(true); 8872 checkForLongClick(0); 8873 return true; 8874 } 8875 } 8876 return result; 8877 } 8878 8879 /** 8880 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 8881 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 8882 * the event). 8883 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8884 * although some may elect to do so in some situations. Do not rely on this to 8885 * catch software key presses. 8886 */ 8887 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 8888 return false; 8889 } 8890 8891 /** 8892 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 8893 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 8894 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 8895 * {@link KeyEvent#KEYCODE_ENTER} is released. 8896 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8897 * although some may elect to do so in some situations. Do not rely on this to 8898 * catch software key presses. 8899 * 8900 * @param keyCode A key code that represents the button pressed, from 8901 * {@link android.view.KeyEvent}. 8902 * @param event The KeyEvent object that defines the button action. 8903 */ 8904 public boolean onKeyUp(int keyCode, KeyEvent event) { 8905 if (KeyEvent.isConfirmKey(keyCode)) { 8906 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 8907 return true; 8908 } 8909 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 8910 setPressed(false); 8911 8912 if (!mHasPerformedLongPress) { 8913 // This is a tap, so remove the longpress check 8914 removeLongPressCallback(); 8915 return performClick(); 8916 } 8917 } 8918 } 8919 return false; 8920 } 8921 8922 /** 8923 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 8924 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 8925 * the event). 8926 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8927 * although some may elect to do so in some situations. Do not rely on this to 8928 * catch software key presses. 8929 * 8930 * @param keyCode A key code that represents the button pressed, from 8931 * {@link android.view.KeyEvent}. 8932 * @param repeatCount The number of times the action was made. 8933 * @param event The KeyEvent object that defines the button action. 8934 */ 8935 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 8936 return false; 8937 } 8938 8939 /** 8940 * Called on the focused view when a key shortcut event is not handled. 8941 * Override this method to implement local key shortcuts for the View. 8942 * Key shortcuts can also be implemented by setting the 8943 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 8944 * 8945 * @param keyCode The value in event.getKeyCode(). 8946 * @param event Description of the key event. 8947 * @return If you handled the event, return true. If you want to allow the 8948 * event to be handled by the next receiver, return false. 8949 */ 8950 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 8951 return false; 8952 } 8953 8954 /** 8955 * Check whether the called view is a text editor, in which case it 8956 * would make sense to automatically display a soft input window for 8957 * it. Subclasses should override this if they implement 8958 * {@link #onCreateInputConnection(EditorInfo)} to return true if 8959 * a call on that method would return a non-null InputConnection, and 8960 * they are really a first-class editor that the user would normally 8961 * start typing on when the go into a window containing your view. 8962 * 8963 * <p>The default implementation always returns false. This does 8964 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 8965 * will not be called or the user can not otherwise perform edits on your 8966 * view; it is just a hint to the system that this is not the primary 8967 * purpose of this view. 8968 * 8969 * @return Returns true if this view is a text editor, else false. 8970 */ 8971 public boolean onCheckIsTextEditor() { 8972 return false; 8973 } 8974 8975 /** 8976 * Create a new InputConnection for an InputMethod to interact 8977 * with the view. The default implementation returns null, since it doesn't 8978 * support input methods. You can override this to implement such support. 8979 * This is only needed for views that take focus and text input. 8980 * 8981 * <p>When implementing this, you probably also want to implement 8982 * {@link #onCheckIsTextEditor()} to indicate you will return a 8983 * non-null InputConnection.</p> 8984 * 8985 * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo} 8986 * object correctly and in its entirety, so that the connected IME can rely 8987 * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart} 8988 * and {@link android.view.inputmethod.EditorInfo#initialSelEnd} members 8989 * must be filled in with the correct cursor position for IMEs to work correctly 8990 * with your application.</p> 8991 * 8992 * @param outAttrs Fill in with attribute information about the connection. 8993 */ 8994 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 8995 return null; 8996 } 8997 8998 /** 8999 * Called by the {@link android.view.inputmethod.InputMethodManager} 9000 * when a view who is not the current 9001 * input connection target is trying to make a call on the manager. The 9002 * default implementation returns false; you can override this to return 9003 * true for certain views if you are performing InputConnection proxying 9004 * to them. 9005 * @param view The View that is making the InputMethodManager call. 9006 * @return Return true to allow the call, false to reject. 9007 */ 9008 public boolean checkInputConnectionProxy(View view) { 9009 return false; 9010 } 9011 9012 /** 9013 * Show the context menu for this view. It is not safe to hold on to the 9014 * menu after returning from this method. 9015 * 9016 * You should normally not overload this method. Overload 9017 * {@link #onCreateContextMenu(ContextMenu)} or define an 9018 * {@link OnCreateContextMenuListener} to add items to the context menu. 9019 * 9020 * @param menu The context menu to populate 9021 */ 9022 public void createContextMenu(ContextMenu menu) { 9023 ContextMenuInfo menuInfo = getContextMenuInfo(); 9024 9025 // Sets the current menu info so all items added to menu will have 9026 // my extra info set. 9027 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 9028 9029 onCreateContextMenu(menu); 9030 ListenerInfo li = mListenerInfo; 9031 if (li != null && li.mOnCreateContextMenuListener != null) { 9032 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 9033 } 9034 9035 // Clear the extra information so subsequent items that aren't mine don't 9036 // have my extra info. 9037 ((MenuBuilder)menu).setCurrentMenuInfo(null); 9038 9039 if (mParent != null) { 9040 mParent.createContextMenu(menu); 9041 } 9042 } 9043 9044 /** 9045 * Views should implement this if they have extra information to associate 9046 * with the context menu. The return result is supplied as a parameter to 9047 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 9048 * callback. 9049 * 9050 * @return Extra information about the item for which the context menu 9051 * should be shown. This information will vary across different 9052 * subclasses of View. 9053 */ 9054 protected ContextMenuInfo getContextMenuInfo() { 9055 return null; 9056 } 9057 9058 /** 9059 * Views should implement this if the view itself is going to add items to 9060 * the context menu. 9061 * 9062 * @param menu the context menu to populate 9063 */ 9064 protected void onCreateContextMenu(ContextMenu menu) { 9065 } 9066 9067 /** 9068 * Implement this method to handle trackball motion events. The 9069 * <em>relative</em> movement of the trackball since the last event 9070 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 9071 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 9072 * that a movement of 1 corresponds to the user pressing one DPAD key (so 9073 * they will often be fractional values, representing the more fine-grained 9074 * movement information available from a trackball). 9075 * 9076 * @param event The motion event. 9077 * @return True if the event was handled, false otherwise. 9078 */ 9079 public boolean onTrackballEvent(MotionEvent event) { 9080 return false; 9081 } 9082 9083 /** 9084 * Implement this method to handle generic motion events. 9085 * <p> 9086 * Generic motion events describe joystick movements, mouse hovers, track pad 9087 * touches, scroll wheel movements and other input events. The 9088 * {@link MotionEvent#getSource() source} of the motion event specifies 9089 * the class of input that was received. Implementations of this method 9090 * must examine the bits in the source before processing the event. 9091 * The following code example shows how this is done. 9092 * </p><p> 9093 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 9094 * are delivered to the view under the pointer. All other generic motion events are 9095 * delivered to the focused view. 9096 * </p> 9097 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 9098 * if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) { 9099 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 9100 * // process the joystick movement... 9101 * return true; 9102 * } 9103 * } 9104 * if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) { 9105 * switch (event.getAction()) { 9106 * case MotionEvent.ACTION_HOVER_MOVE: 9107 * // process the mouse hover movement... 9108 * return true; 9109 * case MotionEvent.ACTION_SCROLL: 9110 * // process the scroll wheel movement... 9111 * return true; 9112 * } 9113 * } 9114 * return super.onGenericMotionEvent(event); 9115 * }</pre> 9116 * 9117 * @param event The generic motion event being processed. 9118 * @return True if the event was handled, false otherwise. 9119 */ 9120 public boolean onGenericMotionEvent(MotionEvent event) { 9121 return false; 9122 } 9123 9124 /** 9125 * Implement this method to handle hover events. 9126 * <p> 9127 * This method is called whenever a pointer is hovering into, over, or out of the 9128 * bounds of a view and the view is not currently being touched. 9129 * Hover events are represented as pointer events with action 9130 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 9131 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 9132 * </p> 9133 * <ul> 9134 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 9135 * when the pointer enters the bounds of the view.</li> 9136 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 9137 * when the pointer has already entered the bounds of the view and has moved.</li> 9138 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 9139 * when the pointer has exited the bounds of the view or when the pointer is 9140 * about to go down due to a button click, tap, or similar user action that 9141 * causes the view to be touched.</li> 9142 * </ul> 9143 * <p> 9144 * The view should implement this method to return true to indicate that it is 9145 * handling the hover event, such as by changing its drawable state. 9146 * </p><p> 9147 * The default implementation calls {@link #setHovered} to update the hovered state 9148 * of the view when a hover enter or hover exit event is received, if the view 9149 * is enabled and is clickable. The default implementation also sends hover 9150 * accessibility events. 9151 * </p> 9152 * 9153 * @param event The motion event that describes the hover. 9154 * @return True if the view handled the hover event. 9155 * 9156 * @see #isHovered 9157 * @see #setHovered 9158 * @see #onHoverChanged 9159 */ 9160 public boolean onHoverEvent(MotionEvent event) { 9161 // The root view may receive hover (or touch) events that are outside the bounds of 9162 // the window. This code ensures that we only send accessibility events for 9163 // hovers that are actually within the bounds of the root view. 9164 final int action = event.getActionMasked(); 9165 if (!mSendingHoverAccessibilityEvents) { 9166 if ((action == MotionEvent.ACTION_HOVER_ENTER 9167 || action == MotionEvent.ACTION_HOVER_MOVE) 9168 && !hasHoveredChild() 9169 && pointInView(event.getX(), event.getY())) { 9170 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 9171 mSendingHoverAccessibilityEvents = true; 9172 } 9173 } else { 9174 if (action == MotionEvent.ACTION_HOVER_EXIT 9175 || (action == MotionEvent.ACTION_MOVE 9176 && !pointInView(event.getX(), event.getY()))) { 9177 mSendingHoverAccessibilityEvents = false; 9178 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 9179 } 9180 } 9181 9182 if (isHoverable()) { 9183 switch (action) { 9184 case MotionEvent.ACTION_HOVER_ENTER: 9185 setHovered(true); 9186 break; 9187 case MotionEvent.ACTION_HOVER_EXIT: 9188 setHovered(false); 9189 break; 9190 } 9191 9192 // Dispatch the event to onGenericMotionEvent before returning true. 9193 // This is to provide compatibility with existing applications that 9194 // handled HOVER_MOVE events in onGenericMotionEvent and that would 9195 // break because of the new default handling for hoverable views 9196 // in onHoverEvent. 9197 // Note that onGenericMotionEvent will be called by default when 9198 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 9199 dispatchGenericMotionEventInternal(event); 9200 // The event was already handled by calling setHovered(), so always 9201 // return true. 9202 return true; 9203 } 9204 9205 return false; 9206 } 9207 9208 /** 9209 * Returns true if the view should handle {@link #onHoverEvent} 9210 * by calling {@link #setHovered} to change its hovered state. 9211 * 9212 * @return True if the view is hoverable. 9213 */ 9214 private boolean isHoverable() { 9215 final int viewFlags = mViewFlags; 9216 if ((viewFlags & ENABLED_MASK) == DISABLED) { 9217 return false; 9218 } 9219 9220 return (viewFlags & CLICKABLE) == CLICKABLE 9221 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 9222 } 9223 9224 /** 9225 * Returns true if the view is currently hovered. 9226 * 9227 * @return True if the view is currently hovered. 9228 * 9229 * @see #setHovered 9230 * @see #onHoverChanged 9231 */ 9232 @ViewDebug.ExportedProperty 9233 public boolean isHovered() { 9234 return (mPrivateFlags & PFLAG_HOVERED) != 0; 9235 } 9236 9237 /** 9238 * Sets whether the view is currently hovered. 9239 * <p> 9240 * Calling this method also changes the drawable state of the view. This 9241 * enables the view to react to hover by using different drawable resources 9242 * to change its appearance. 9243 * </p><p> 9244 * The {@link #onHoverChanged} method is called when the hovered state changes. 9245 * </p> 9246 * 9247 * @param hovered True if the view is hovered. 9248 * 9249 * @see #isHovered 9250 * @see #onHoverChanged 9251 */ 9252 public void setHovered(boolean hovered) { 9253 if (hovered) { 9254 if ((mPrivateFlags & PFLAG_HOVERED) == 0) { 9255 mPrivateFlags |= PFLAG_HOVERED; 9256 refreshDrawableState(); 9257 onHoverChanged(true); 9258 } 9259 } else { 9260 if ((mPrivateFlags & PFLAG_HOVERED) != 0) { 9261 mPrivateFlags &= ~PFLAG_HOVERED; 9262 refreshDrawableState(); 9263 onHoverChanged(false); 9264 } 9265 } 9266 } 9267 9268 /** 9269 * Implement this method to handle hover state changes. 9270 * <p> 9271 * This method is called whenever the hover state changes as a result of a 9272 * call to {@link #setHovered}. 9273 * </p> 9274 * 9275 * @param hovered The current hover state, as returned by {@link #isHovered}. 9276 * 9277 * @see #isHovered 9278 * @see #setHovered 9279 */ 9280 public void onHoverChanged(boolean hovered) { 9281 } 9282 9283 /** 9284 * Implement this method to handle touch screen motion events. 9285 * <p> 9286 * If this method is used to detect click actions, it is recommended that 9287 * the actions be performed by implementing and calling 9288 * {@link #performClick()}. This will ensure consistent system behavior, 9289 * including: 9290 * <ul> 9291 * <li>obeying click sound preferences 9292 * <li>dispatching OnClickListener calls 9293 * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when 9294 * accessibility features are enabled 9295 * </ul> 9296 * 9297 * @param event The motion event. 9298 * @return True if the event was handled, false otherwise. 9299 */ 9300 public boolean onTouchEvent(MotionEvent event) { 9301 final float x = event.getX(); 9302 final float y = event.getY(); 9303 final int viewFlags = mViewFlags; 9304 9305 if ((viewFlags & ENABLED_MASK) == DISABLED) { 9306 if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { 9307 setPressed(false); 9308 } 9309 // A disabled view that is clickable still consumes the touch 9310 // events, it just doesn't respond to them. 9311 return (((viewFlags & CLICKABLE) == CLICKABLE || 9312 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); 9313 } 9314 9315 if (mTouchDelegate != null) { 9316 if (mTouchDelegate.onTouchEvent(event)) { 9317 return true; 9318 } 9319 } 9320 9321 if (((viewFlags & CLICKABLE) == CLICKABLE || 9322 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { 9323 switch (event.getAction()) { 9324 case MotionEvent.ACTION_UP: 9325 boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; 9326 if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { 9327 // take focus if we don't have it already and we should in 9328 // touch mode. 9329 boolean focusTaken = false; 9330 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 9331 focusTaken = requestFocus(); 9332 } 9333 9334 if (prepressed) { 9335 // The button is being released before we actually 9336 // showed it as pressed. Make it show the pressed 9337 // state now (before scheduling the click) to ensure 9338 // the user sees it. 9339 setPressed(true, x, y); 9340 } 9341 9342 if (!mHasPerformedLongPress) { 9343 // This is a tap, so remove the longpress check 9344 removeLongPressCallback(); 9345 9346 // Only perform take click actions if we were in the pressed state 9347 if (!focusTaken) { 9348 // Use a Runnable and post this rather than calling 9349 // performClick directly. This lets other visual state 9350 // of the view update before click actions start. 9351 if (mPerformClick == null) { 9352 mPerformClick = new PerformClick(); 9353 } 9354 if (!post(mPerformClick)) { 9355 performClick(); 9356 } 9357 } 9358 } 9359 9360 if (mUnsetPressedState == null) { 9361 mUnsetPressedState = new UnsetPressedState(); 9362 } 9363 9364 if (prepressed) { 9365 postDelayed(mUnsetPressedState, 9366 ViewConfiguration.getPressedStateDuration()); 9367 } else if (!post(mUnsetPressedState)) { 9368 // If the post failed, unpress right now 9369 mUnsetPressedState.run(); 9370 } 9371 9372 removeTapCallback(); 9373 } 9374 break; 9375 9376 case MotionEvent.ACTION_DOWN: 9377 mHasPerformedLongPress = false; 9378 9379 if (performButtonActionOnTouchDown(event)) { 9380 break; 9381 } 9382 9383 // Walk up the hierarchy to determine if we're inside a scrolling container. 9384 boolean isInScrollingContainer = isInScrollingContainer(); 9385 9386 // For views inside a scrolling container, delay the pressed feedback for 9387 // a short period in case this is a scroll. 9388 if (isInScrollingContainer) { 9389 mPrivateFlags |= PFLAG_PREPRESSED; 9390 if (mPendingCheckForTap == null) { 9391 mPendingCheckForTap = new CheckForTap(); 9392 } 9393 mPendingCheckForTap.x = event.getX(); 9394 mPendingCheckForTap.y = event.getY(); 9395 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 9396 } else { 9397 // Not inside a scrolling container, so show the feedback right away 9398 setPressed(true, x, y); 9399 checkForLongClick(0); 9400 } 9401 break; 9402 9403 case MotionEvent.ACTION_CANCEL: 9404 setPressed(false); 9405 removeTapCallback(); 9406 removeLongPressCallback(); 9407 break; 9408 9409 case MotionEvent.ACTION_MOVE: 9410 drawableHotspotChanged(x, y); 9411 9412 // Be lenient about moving outside of buttons 9413 if (!pointInView(x, y, mTouchSlop)) { 9414 // Outside button 9415 removeTapCallback(); 9416 if ((mPrivateFlags & PFLAG_PRESSED) != 0) { 9417 // Remove any future long press/tap checks 9418 removeLongPressCallback(); 9419 9420 setPressed(false); 9421 } 9422 } 9423 break; 9424 } 9425 9426 return true; 9427 } 9428 9429 return false; 9430 } 9431 9432 /** 9433 * @hide 9434 */ 9435 public boolean isInScrollingContainer() { 9436 ViewParent p = getParent(); 9437 while (p != null && p instanceof ViewGroup) { 9438 if (((ViewGroup) p).shouldDelayChildPressedState()) { 9439 return true; 9440 } 9441 p = p.getParent(); 9442 } 9443 return false; 9444 } 9445 9446 /** 9447 * Remove the longpress detection timer. 9448 */ 9449 private void removeLongPressCallback() { 9450 if (mPendingCheckForLongPress != null) { 9451 removeCallbacks(mPendingCheckForLongPress); 9452 } 9453 } 9454 9455 /** 9456 * Remove the pending click action 9457 */ 9458 private void removePerformClickCallback() { 9459 if (mPerformClick != null) { 9460 removeCallbacks(mPerformClick); 9461 } 9462 } 9463 9464 /** 9465 * Remove the prepress detection timer. 9466 */ 9467 private void removeUnsetPressCallback() { 9468 if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) { 9469 setPressed(false); 9470 removeCallbacks(mUnsetPressedState); 9471 } 9472 } 9473 9474 /** 9475 * Remove the tap detection timer. 9476 */ 9477 private void removeTapCallback() { 9478 if (mPendingCheckForTap != null) { 9479 mPrivateFlags &= ~PFLAG_PREPRESSED; 9480 removeCallbacks(mPendingCheckForTap); 9481 } 9482 } 9483 9484 /** 9485 * Cancels a pending long press. Your subclass can use this if you 9486 * want the context menu to come up if the user presses and holds 9487 * at the same place, but you don't want it to come up if they press 9488 * and then move around enough to cause scrolling. 9489 */ 9490 public void cancelLongPress() { 9491 removeLongPressCallback(); 9492 9493 /* 9494 * The prepressed state handled by the tap callback is a display 9495 * construct, but the tap callback will post a long press callback 9496 * less its own timeout. Remove it here. 9497 */ 9498 removeTapCallback(); 9499 } 9500 9501 /** 9502 * Remove the pending callback for sending a 9503 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 9504 */ 9505 private void removeSendViewScrolledAccessibilityEventCallback() { 9506 if (mSendViewScrolledAccessibilityEvent != null) { 9507 removeCallbacks(mSendViewScrolledAccessibilityEvent); 9508 mSendViewScrolledAccessibilityEvent.mIsPending = false; 9509 } 9510 } 9511 9512 /** 9513 * Sets the TouchDelegate for this View. 9514 */ 9515 public void setTouchDelegate(TouchDelegate delegate) { 9516 mTouchDelegate = delegate; 9517 } 9518 9519 /** 9520 * Gets the TouchDelegate for this View. 9521 */ 9522 public TouchDelegate getTouchDelegate() { 9523 return mTouchDelegate; 9524 } 9525 9526 /** 9527 * Request unbuffered dispatch of the given stream of MotionEvents to this View. 9528 * 9529 * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input 9530 * system not batch {@link MotionEvent}s but instead deliver them as soon as they're 9531 * available. This method should only be called for touch events. 9532 * 9533 * <p class="note">This api is not intended for most applications. Buffered dispatch 9534 * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent 9535 * streams will not improve your input latency. Side effects include: increased latency, 9536 * jittery scrolls and inability to take advantage of system resampling. Talk to your input 9537 * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for 9538 * you.</p> 9539 */ 9540 public final void requestUnbufferedDispatch(MotionEvent event) { 9541 final int action = event.getAction(); 9542 if (mAttachInfo == null 9543 || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE 9544 || !event.isTouchEvent()) { 9545 return; 9546 } 9547 mAttachInfo.mUnbufferedDispatchRequested = true; 9548 } 9549 9550 /** 9551 * Set flags controlling behavior of this view. 9552 * 9553 * @param flags Constant indicating the value which should be set 9554 * @param mask Constant indicating the bit range that should be changed 9555 */ 9556 void setFlags(int flags, int mask) { 9557 final boolean accessibilityEnabled = 9558 AccessibilityManager.getInstance(mContext).isEnabled(); 9559 final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility(); 9560 9561 int old = mViewFlags; 9562 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 9563 9564 int changed = mViewFlags ^ old; 9565 if (changed == 0) { 9566 return; 9567 } 9568 int privateFlags = mPrivateFlags; 9569 9570 /* Check if the FOCUSABLE bit has changed */ 9571 if (((changed & FOCUSABLE_MASK) != 0) && 9572 ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) { 9573 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 9574 && ((privateFlags & PFLAG_FOCUSED) != 0)) { 9575 /* Give up focus if we are no longer focusable */ 9576 clearFocus(); 9577 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 9578 && ((privateFlags & PFLAG_FOCUSED) == 0)) { 9579 /* 9580 * Tell the view system that we are now available to take focus 9581 * if no one else already has it. 9582 */ 9583 if (mParent != null) mParent.focusableViewAvailable(this); 9584 } 9585 } 9586 9587 final int newVisibility = flags & VISIBILITY_MASK; 9588 if (newVisibility == VISIBLE) { 9589 if ((changed & VISIBILITY_MASK) != 0) { 9590 /* 9591 * If this view is becoming visible, invalidate it in case it changed while 9592 * it was not visible. Marking it drawn ensures that the invalidation will 9593 * go through. 9594 */ 9595 mPrivateFlags |= PFLAG_DRAWN; 9596 invalidate(true); 9597 9598 needGlobalAttributesUpdate(true); 9599 9600 // a view becoming visible is worth notifying the parent 9601 // about in case nothing has focus. even if this specific view 9602 // isn't focusable, it may contain something that is, so let 9603 // the root view try to give this focus if nothing else does. 9604 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 9605 mParent.focusableViewAvailable(this); 9606 } 9607 } 9608 } 9609 9610 /* Check if the GONE bit has changed */ 9611 if ((changed & GONE) != 0) { 9612 needGlobalAttributesUpdate(false); 9613 requestLayout(); 9614 9615 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 9616 if (hasFocus()) clearFocus(); 9617 clearAccessibilityFocus(); 9618 destroyDrawingCache(); 9619 if (mParent instanceof View) { 9620 // GONE views noop invalidation, so invalidate the parent 9621 ((View) mParent).invalidate(true); 9622 } 9623 // Mark the view drawn to ensure that it gets invalidated properly the next 9624 // time it is visible and gets invalidated 9625 mPrivateFlags |= PFLAG_DRAWN; 9626 } 9627 if (mAttachInfo != null) { 9628 mAttachInfo.mViewVisibilityChanged = true; 9629 } 9630 } 9631 9632 /* Check if the VISIBLE bit has changed */ 9633 if ((changed & INVISIBLE) != 0) { 9634 needGlobalAttributesUpdate(false); 9635 /* 9636 * If this view is becoming invisible, set the DRAWN flag so that 9637 * the next invalidate() will not be skipped. 9638 */ 9639 mPrivateFlags |= PFLAG_DRAWN; 9640 9641 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) { 9642 // root view becoming invisible shouldn't clear focus and accessibility focus 9643 if (getRootView() != this) { 9644 if (hasFocus()) clearFocus(); 9645 clearAccessibilityFocus(); 9646 } 9647 } 9648 if (mAttachInfo != null) { 9649 mAttachInfo.mViewVisibilityChanged = true; 9650 } 9651 } 9652 9653 if ((changed & VISIBILITY_MASK) != 0) { 9654 // If the view is invisible, cleanup its display list to free up resources 9655 if (newVisibility != VISIBLE && mAttachInfo != null) { 9656 cleanupDraw(); 9657 } 9658 9659 if (mParent instanceof ViewGroup) { 9660 ((ViewGroup) mParent).onChildVisibilityChanged(this, 9661 (changed & VISIBILITY_MASK), newVisibility); 9662 ((View) mParent).invalidate(true); 9663 } else if (mParent != null) { 9664 mParent.invalidateChild(this, null); 9665 } 9666 dispatchVisibilityChanged(this, newVisibility); 9667 9668 notifySubtreeAccessibilityStateChangedIfNeeded(); 9669 } 9670 9671 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 9672 destroyDrawingCache(); 9673 } 9674 9675 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 9676 destroyDrawingCache(); 9677 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 9678 invalidateParentCaches(); 9679 } 9680 9681 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 9682 destroyDrawingCache(); 9683 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 9684 } 9685 9686 if ((changed & DRAW_MASK) != 0) { 9687 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 9688 if (mBackground != null) { 9689 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 9690 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 9691 } else { 9692 mPrivateFlags |= PFLAG_SKIP_DRAW; 9693 } 9694 } else { 9695 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 9696 } 9697 requestLayout(); 9698 invalidate(true); 9699 } 9700 9701 if ((changed & KEEP_SCREEN_ON) != 0) { 9702 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 9703 mParent.recomputeViewAttributes(this); 9704 } 9705 } 9706 9707 if (accessibilityEnabled) { 9708 if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0 9709 || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) { 9710 if (oldIncludeForAccessibility != includeForAccessibility()) { 9711 notifySubtreeAccessibilityStateChangedIfNeeded(); 9712 } else { 9713 notifyViewAccessibilityStateChangedIfNeeded( 9714 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9715 } 9716 } else if ((changed & ENABLED_MASK) != 0) { 9717 notifyViewAccessibilityStateChangedIfNeeded( 9718 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9719 } 9720 } 9721 } 9722 9723 /** 9724 * Change the view's z order in the tree, so it's on top of other sibling 9725 * views. This ordering change may affect layout, if the parent container 9726 * uses an order-dependent layout scheme (e.g., LinearLayout). Prior 9727 * to {@link android.os.Build.VERSION_CODES#KITKAT} this 9728 * method should be followed by calls to {@link #requestLayout()} and 9729 * {@link View#invalidate()} on the view's parent to force the parent to redraw 9730 * with the new child ordering. 9731 * 9732 * @see ViewGroup#bringChildToFront(View) 9733 */ 9734 public void bringToFront() { 9735 if (mParent != null) { 9736 mParent.bringChildToFront(this); 9737 } 9738 } 9739 9740 /** 9741 * This is called in response to an internal scroll in this view (i.e., the 9742 * view scrolled its own contents). This is typically as a result of 9743 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 9744 * called. 9745 * 9746 * @param l Current horizontal scroll origin. 9747 * @param t Current vertical scroll origin. 9748 * @param oldl Previous horizontal scroll origin. 9749 * @param oldt Previous vertical scroll origin. 9750 */ 9751 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 9752 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 9753 postSendViewScrolledAccessibilityEventCallback(); 9754 } 9755 9756 mBackgroundSizeChanged = true; 9757 9758 final AttachInfo ai = mAttachInfo; 9759 if (ai != null) { 9760 ai.mViewScrollChanged = true; 9761 } 9762 } 9763 9764 /** 9765 * Interface definition for a callback to be invoked when the layout bounds of a view 9766 * changes due to layout processing. 9767 */ 9768 public interface OnLayoutChangeListener { 9769 /** 9770 * Called when the layout bounds of a view changes due to layout processing. 9771 * 9772 * @param v The view whose bounds have changed. 9773 * @param left The new value of the view's left property. 9774 * @param top The new value of the view's top property. 9775 * @param right The new value of the view's right property. 9776 * @param bottom The new value of the view's bottom property. 9777 * @param oldLeft The previous value of the view's left property. 9778 * @param oldTop The previous value of the view's top property. 9779 * @param oldRight The previous value of the view's right property. 9780 * @param oldBottom The previous value of the view's bottom property. 9781 */ 9782 void onLayoutChange(View v, int left, int top, int right, int bottom, 9783 int oldLeft, int oldTop, int oldRight, int oldBottom); 9784 } 9785 9786 /** 9787 * This is called during layout when the size of this view has changed. If 9788 * you were just added to the view hierarchy, you're called with the old 9789 * values of 0. 9790 * 9791 * @param w Current width of this view. 9792 * @param h Current height of this view. 9793 * @param oldw Old width of this view. 9794 * @param oldh Old height of this view. 9795 */ 9796 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 9797 } 9798 9799 /** 9800 * Called by draw to draw the child views. This may be overridden 9801 * by derived classes to gain control just before its children are drawn 9802 * (but after its own view has been drawn). 9803 * @param canvas the canvas on which to draw the view 9804 */ 9805 protected void dispatchDraw(Canvas canvas) { 9806 9807 } 9808 9809 /** 9810 * Gets the parent of this view. Note that the parent is a 9811 * ViewParent and not necessarily a View. 9812 * 9813 * @return Parent of this view. 9814 */ 9815 public final ViewParent getParent() { 9816 return mParent; 9817 } 9818 9819 /** 9820 * Set the horizontal scrolled position of your view. This will cause a call to 9821 * {@link #onScrollChanged(int, int, int, int)} and the view will be 9822 * invalidated. 9823 * @param value the x position to scroll to 9824 */ 9825 public void setScrollX(int value) { 9826 scrollTo(value, mScrollY); 9827 } 9828 9829 /** 9830 * Set the vertical scrolled position of your view. This will cause a call to 9831 * {@link #onScrollChanged(int, int, int, int)} and the view will be 9832 * invalidated. 9833 * @param value the y position to scroll to 9834 */ 9835 public void setScrollY(int value) { 9836 scrollTo(mScrollX, value); 9837 } 9838 9839 /** 9840 * Return the scrolled left position of this view. This is the left edge of 9841 * the displayed part of your view. You do not need to draw any pixels 9842 * farther left, since those are outside of the frame of your view on 9843 * screen. 9844 * 9845 * @return The left edge of the displayed part of your view, in pixels. 9846 */ 9847 public final int getScrollX() { 9848 return mScrollX; 9849 } 9850 9851 /** 9852 * Return the scrolled top position of this view. This is the top edge of 9853 * the displayed part of your view. You do not need to draw any pixels above 9854 * it, since those are outside of the frame of your view on screen. 9855 * 9856 * @return The top edge of the displayed part of your view, in pixels. 9857 */ 9858 public final int getScrollY() { 9859 return mScrollY; 9860 } 9861 9862 /** 9863 * Return the width of the your view. 9864 * 9865 * @return The width of your view, in pixels. 9866 */ 9867 @ViewDebug.ExportedProperty(category = "layout") 9868 public final int getWidth() { 9869 return mRight - mLeft; 9870 } 9871 9872 /** 9873 * Return the height of your view. 9874 * 9875 * @return The height of your view, in pixels. 9876 */ 9877 @ViewDebug.ExportedProperty(category = "layout") 9878 public final int getHeight() { 9879 return mBottom - mTop; 9880 } 9881 9882 /** 9883 * Return the visible drawing bounds of your view. Fills in the output 9884 * rectangle with the values from getScrollX(), getScrollY(), 9885 * getWidth(), and getHeight(). These bounds do not account for any 9886 * transformation properties currently set on the view, such as 9887 * {@link #setScaleX(float)} or {@link #setRotation(float)}. 9888 * 9889 * @param outRect The (scrolled) drawing bounds of the view. 9890 */ 9891 public void getDrawingRect(Rect outRect) { 9892 outRect.left = mScrollX; 9893 outRect.top = mScrollY; 9894 outRect.right = mScrollX + (mRight - mLeft); 9895 outRect.bottom = mScrollY + (mBottom - mTop); 9896 } 9897 9898 /** 9899 * Like {@link #getMeasuredWidthAndState()}, but only returns the 9900 * raw width component (that is the result is masked by 9901 * {@link #MEASURED_SIZE_MASK}). 9902 * 9903 * @return The raw measured width of this view. 9904 */ 9905 public final int getMeasuredWidth() { 9906 return mMeasuredWidth & MEASURED_SIZE_MASK; 9907 } 9908 9909 /** 9910 * Return the full width measurement information for this view as computed 9911 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 9912 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 9913 * This should be used during measurement and layout calculations only. Use 9914 * {@link #getWidth()} to see how wide a view is after layout. 9915 * 9916 * @return The measured width of this view as a bit mask. 9917 */ 9918 public final int getMeasuredWidthAndState() { 9919 return mMeasuredWidth; 9920 } 9921 9922 /** 9923 * Like {@link #getMeasuredHeightAndState()}, but only returns the 9924 * raw width component (that is the result is masked by 9925 * {@link #MEASURED_SIZE_MASK}). 9926 * 9927 * @return The raw measured height of this view. 9928 */ 9929 public final int getMeasuredHeight() { 9930 return mMeasuredHeight & MEASURED_SIZE_MASK; 9931 } 9932 9933 /** 9934 * Return the full height measurement information for this view as computed 9935 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 9936 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 9937 * This should be used during measurement and layout calculations only. Use 9938 * {@link #getHeight()} to see how wide a view is after layout. 9939 * 9940 * @return The measured width of this view as a bit mask. 9941 */ 9942 public final int getMeasuredHeightAndState() { 9943 return mMeasuredHeight; 9944 } 9945 9946 /** 9947 * Return only the state bits of {@link #getMeasuredWidthAndState()} 9948 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 9949 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 9950 * and the height component is at the shifted bits 9951 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 9952 */ 9953 public final int getMeasuredState() { 9954 return (mMeasuredWidth&MEASURED_STATE_MASK) 9955 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 9956 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 9957 } 9958 9959 /** 9960 * The transform matrix of this view, which is calculated based on the current 9961 * rotation, scale, and pivot properties. 9962 * 9963 * @see #getRotation() 9964 * @see #getScaleX() 9965 * @see #getScaleY() 9966 * @see #getPivotX() 9967 * @see #getPivotY() 9968 * @return The current transform matrix for the view 9969 */ 9970 public Matrix getMatrix() { 9971 ensureTransformationInfo(); 9972 final Matrix matrix = mTransformationInfo.mMatrix; 9973 mRenderNode.getMatrix(matrix); 9974 return matrix; 9975 } 9976 9977 /** 9978 * Returns true if the transform matrix is the identity matrix. 9979 * Recomputes the matrix if necessary. 9980 * 9981 * @return True if the transform matrix is the identity matrix, false otherwise. 9982 */ 9983 final boolean hasIdentityMatrix() { 9984 return mRenderNode.hasIdentityMatrix(); 9985 } 9986 9987 void ensureTransformationInfo() { 9988 if (mTransformationInfo == null) { 9989 mTransformationInfo = new TransformationInfo(); 9990 } 9991 } 9992 9993 /** 9994 * Utility method to retrieve the inverse of the current mMatrix property. 9995 * We cache the matrix to avoid recalculating it when transform properties 9996 * have not changed. 9997 * 9998 * @return The inverse of the current matrix of this view. 9999 * @hide 10000 */ 10001 public final Matrix getInverseMatrix() { 10002 ensureTransformationInfo(); 10003 if (mTransformationInfo.mInverseMatrix == null) { 10004 mTransformationInfo.mInverseMatrix = new Matrix(); 10005 } 10006 final Matrix matrix = mTransformationInfo.mInverseMatrix; 10007 mRenderNode.getInverseMatrix(matrix); 10008 return matrix; 10009 } 10010 10011 /** 10012 * Gets the distance along the Z axis from the camera to this view. 10013 * 10014 * @see #setCameraDistance(float) 10015 * 10016 * @return The distance along the Z axis. 10017 */ 10018 public float getCameraDistance() { 10019 final float dpi = mResources.getDisplayMetrics().densityDpi; 10020 return -(mRenderNode.getCameraDistance() * dpi); 10021 } 10022 10023 /** 10024 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 10025 * views are drawn) from the camera to this view. The camera's distance 10026 * affects 3D transformations, for instance rotations around the X and Y 10027 * axis. If the rotationX or rotationY properties are changed and this view is 10028 * large (more than half the size of the screen), it is recommended to always 10029 * use a camera distance that's greater than the height (X axis rotation) or 10030 * the width (Y axis rotation) of this view.</p> 10031 * 10032 * <p>The distance of the camera from the view plane can have an affect on the 10033 * perspective distortion of the view when it is rotated around the x or y axis. 10034 * For example, a large distance will result in a large viewing angle, and there 10035 * will not be much perspective distortion of the view as it rotates. A short 10036 * distance may cause much more perspective distortion upon rotation, and can 10037 * also result in some drawing artifacts if the rotated view ends up partially 10038 * behind the camera (which is why the recommendation is to use a distance at 10039 * least as far as the size of the view, if the view is to be rotated.)</p> 10040 * 10041 * <p>The distance is expressed in "depth pixels." The default distance depends 10042 * on the screen density. For instance, on a medium density display, the 10043 * default distance is 1280. On a high density display, the default distance 10044 * is 1920.</p> 10045 * 10046 * <p>If you want to specify a distance that leads to visually consistent 10047 * results across various densities, use the following formula:</p> 10048 * <pre> 10049 * float scale = context.getResources().getDisplayMetrics().density; 10050 * view.setCameraDistance(distance * scale); 10051 * </pre> 10052 * 10053 * <p>The density scale factor of a high density display is 1.5, 10054 * and 1920 = 1280 * 1.5.</p> 10055 * 10056 * @param distance The distance in "depth pixels", if negative the opposite 10057 * value is used 10058 * 10059 * @see #setRotationX(float) 10060 * @see #setRotationY(float) 10061 */ 10062 public void setCameraDistance(float distance) { 10063 final float dpi = mResources.getDisplayMetrics().densityDpi; 10064 10065 invalidateViewProperty(true, false); 10066 mRenderNode.setCameraDistance(-Math.abs(distance) / dpi); 10067 invalidateViewProperty(false, false); 10068 10069 invalidateParentIfNeededAndWasQuickRejected(); 10070 } 10071 10072 /** 10073 * The degrees that the view is rotated around the pivot point. 10074 * 10075 * @see #setRotation(float) 10076 * @see #getPivotX() 10077 * @see #getPivotY() 10078 * 10079 * @return The degrees of rotation. 10080 */ 10081 @ViewDebug.ExportedProperty(category = "drawing") 10082 public float getRotation() { 10083 return mRenderNode.getRotation(); 10084 } 10085 10086 /** 10087 * Sets the degrees that the view is rotated around the pivot point. Increasing values 10088 * result in clockwise rotation. 10089 * 10090 * @param rotation The degrees of rotation. 10091 * 10092 * @see #getRotation() 10093 * @see #getPivotX() 10094 * @see #getPivotY() 10095 * @see #setRotationX(float) 10096 * @see #setRotationY(float) 10097 * 10098 * @attr ref android.R.styleable#View_rotation 10099 */ 10100 public void setRotation(float rotation) { 10101 if (rotation != getRotation()) { 10102 // Double-invalidation is necessary to capture view's old and new areas 10103 invalidateViewProperty(true, false); 10104 mRenderNode.setRotation(rotation); 10105 invalidateViewProperty(false, true); 10106 10107 invalidateParentIfNeededAndWasQuickRejected(); 10108 notifySubtreeAccessibilityStateChangedIfNeeded(); 10109 } 10110 } 10111 10112 /** 10113 * The degrees that the view is rotated around the vertical axis through the pivot point. 10114 * 10115 * @see #getPivotX() 10116 * @see #getPivotY() 10117 * @see #setRotationY(float) 10118 * 10119 * @return The degrees of Y rotation. 10120 */ 10121 @ViewDebug.ExportedProperty(category = "drawing") 10122 public float getRotationY() { 10123 return mRenderNode.getRotationY(); 10124 } 10125 10126 /** 10127 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 10128 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 10129 * down the y axis. 10130 * 10131 * When rotating large views, it is recommended to adjust the camera distance 10132 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 10133 * 10134 * @param rotationY The degrees of Y rotation. 10135 * 10136 * @see #getRotationY() 10137 * @see #getPivotX() 10138 * @see #getPivotY() 10139 * @see #setRotation(float) 10140 * @see #setRotationX(float) 10141 * @see #setCameraDistance(float) 10142 * 10143 * @attr ref android.R.styleable#View_rotationY 10144 */ 10145 public void setRotationY(float rotationY) { 10146 if (rotationY != getRotationY()) { 10147 invalidateViewProperty(true, false); 10148 mRenderNode.setRotationY(rotationY); 10149 invalidateViewProperty(false, true); 10150 10151 invalidateParentIfNeededAndWasQuickRejected(); 10152 notifySubtreeAccessibilityStateChangedIfNeeded(); 10153 } 10154 } 10155 10156 /** 10157 * The degrees that the view is rotated around the horizontal axis through the pivot point. 10158 * 10159 * @see #getPivotX() 10160 * @see #getPivotY() 10161 * @see #setRotationX(float) 10162 * 10163 * @return The degrees of X rotation. 10164 */ 10165 @ViewDebug.ExportedProperty(category = "drawing") 10166 public float getRotationX() { 10167 return mRenderNode.getRotationX(); 10168 } 10169 10170 /** 10171 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 10172 * Increasing values result in clockwise rotation from the viewpoint of looking down the 10173 * x axis. 10174 * 10175 * When rotating large views, it is recommended to adjust the camera distance 10176 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 10177 * 10178 * @param rotationX The degrees of X rotation. 10179 * 10180 * @see #getRotationX() 10181 * @see #getPivotX() 10182 * @see #getPivotY() 10183 * @see #setRotation(float) 10184 * @see #setRotationY(float) 10185 * @see #setCameraDistance(float) 10186 * 10187 * @attr ref android.R.styleable#View_rotationX 10188 */ 10189 public void setRotationX(float rotationX) { 10190 if (rotationX != getRotationX()) { 10191 invalidateViewProperty(true, false); 10192 mRenderNode.setRotationX(rotationX); 10193 invalidateViewProperty(false, true); 10194 10195 invalidateParentIfNeededAndWasQuickRejected(); 10196 notifySubtreeAccessibilityStateChangedIfNeeded(); 10197 } 10198 } 10199 10200 /** 10201 * The amount that the view is scaled in x around the pivot point, as a proportion of 10202 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 10203 * 10204 * <p>By default, this is 1.0f. 10205 * 10206 * @see #getPivotX() 10207 * @see #getPivotY() 10208 * @return The scaling factor. 10209 */ 10210 @ViewDebug.ExportedProperty(category = "drawing") 10211 public float getScaleX() { 10212 return mRenderNode.getScaleX(); 10213 } 10214 10215 /** 10216 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 10217 * the view's unscaled width. A value of 1 means that no scaling is applied. 10218 * 10219 * @param scaleX The scaling factor. 10220 * @see #getPivotX() 10221 * @see #getPivotY() 10222 * 10223 * @attr ref android.R.styleable#View_scaleX 10224 */ 10225 public void setScaleX(float scaleX) { 10226 if (scaleX != getScaleX()) { 10227 invalidateViewProperty(true, false); 10228 mRenderNode.setScaleX(scaleX); 10229 invalidateViewProperty(false, true); 10230 10231 invalidateParentIfNeededAndWasQuickRejected(); 10232 notifySubtreeAccessibilityStateChangedIfNeeded(); 10233 } 10234 } 10235 10236 /** 10237 * The amount that the view is scaled in y around the pivot point, as a proportion of 10238 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 10239 * 10240 * <p>By default, this is 1.0f. 10241 * 10242 * @see #getPivotX() 10243 * @see #getPivotY() 10244 * @return The scaling factor. 10245 */ 10246 @ViewDebug.ExportedProperty(category = "drawing") 10247 public float getScaleY() { 10248 return mRenderNode.getScaleY(); 10249 } 10250 10251 /** 10252 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 10253 * the view's unscaled width. A value of 1 means that no scaling is applied. 10254 * 10255 * @param scaleY The scaling factor. 10256 * @see #getPivotX() 10257 * @see #getPivotY() 10258 * 10259 * @attr ref android.R.styleable#View_scaleY 10260 */ 10261 public void setScaleY(float scaleY) { 10262 if (scaleY != getScaleY()) { 10263 invalidateViewProperty(true, false); 10264 mRenderNode.setScaleY(scaleY); 10265 invalidateViewProperty(false, true); 10266 10267 invalidateParentIfNeededAndWasQuickRejected(); 10268 notifySubtreeAccessibilityStateChangedIfNeeded(); 10269 } 10270 } 10271 10272 /** 10273 * The x location of the point around which the view is {@link #setRotation(float) rotated} 10274 * and {@link #setScaleX(float) scaled}. 10275 * 10276 * @see #getRotation() 10277 * @see #getScaleX() 10278 * @see #getScaleY() 10279 * @see #getPivotY() 10280 * @return The x location of the pivot point. 10281 * 10282 * @attr ref android.R.styleable#View_transformPivotX 10283 */ 10284 @ViewDebug.ExportedProperty(category = "drawing") 10285 public float getPivotX() { 10286 return mRenderNode.getPivotX(); 10287 } 10288 10289 /** 10290 * Sets the x location of the point around which the view is 10291 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 10292 * By default, the pivot point is centered on the object. 10293 * Setting this property disables this behavior and causes the view to use only the 10294 * explicitly set pivotX and pivotY values. 10295 * 10296 * @param pivotX The x location of the pivot point. 10297 * @see #getRotation() 10298 * @see #getScaleX() 10299 * @see #getScaleY() 10300 * @see #getPivotY() 10301 * 10302 * @attr ref android.R.styleable#View_transformPivotX 10303 */ 10304 public void setPivotX(float pivotX) { 10305 if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) { 10306 invalidateViewProperty(true, false); 10307 mRenderNode.setPivotX(pivotX); 10308 invalidateViewProperty(false, true); 10309 10310 invalidateParentIfNeededAndWasQuickRejected(); 10311 } 10312 } 10313 10314 /** 10315 * The y location of the point around which the view is {@link #setRotation(float) rotated} 10316 * and {@link #setScaleY(float) scaled}. 10317 * 10318 * @see #getRotation() 10319 * @see #getScaleX() 10320 * @see #getScaleY() 10321 * @see #getPivotY() 10322 * @return The y location of the pivot point. 10323 * 10324 * @attr ref android.R.styleable#View_transformPivotY 10325 */ 10326 @ViewDebug.ExportedProperty(category = "drawing") 10327 public float getPivotY() { 10328 return mRenderNode.getPivotY(); 10329 } 10330 10331 /** 10332 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 10333 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 10334 * Setting this property disables this behavior and causes the view to use only the 10335 * explicitly set pivotX and pivotY values. 10336 * 10337 * @param pivotY The y location of the pivot point. 10338 * @see #getRotation() 10339 * @see #getScaleX() 10340 * @see #getScaleY() 10341 * @see #getPivotY() 10342 * 10343 * @attr ref android.R.styleable#View_transformPivotY 10344 */ 10345 public void setPivotY(float pivotY) { 10346 if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) { 10347 invalidateViewProperty(true, false); 10348 mRenderNode.setPivotY(pivotY); 10349 invalidateViewProperty(false, true); 10350 10351 invalidateParentIfNeededAndWasQuickRejected(); 10352 } 10353 } 10354 10355 /** 10356 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 10357 * completely transparent and 1 means the view is completely opaque. 10358 * 10359 * <p>By default this is 1.0f. 10360 * @return The opacity of the view. 10361 */ 10362 @ViewDebug.ExportedProperty(category = "drawing") 10363 public float getAlpha() { 10364 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 10365 } 10366 10367 /** 10368 * Returns whether this View has content which overlaps. 10369 * 10370 * <p>This function, intended to be overridden by specific View types, is an optimization when 10371 * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to 10372 * an offscreen buffer and then composited into place, which can be expensive. If the view has 10373 * no overlapping rendering, the view can draw each primitive with the appropriate alpha value 10374 * directly. An example of overlapping rendering is a TextView with a background image, such as 10375 * a Button. An example of non-overlapping rendering is a TextView with no background, or an 10376 * ImageView with only the foreground image. The default implementation returns true; subclasses 10377 * should override if they have cases which can be optimized.</p> 10378 * 10379 * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas} 10380 * necessitates that a View return true if it uses the methods internally without passing the 10381 * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p> 10382 * 10383 * @return true if the content in this view might overlap, false otherwise. 10384 */ 10385 @ViewDebug.ExportedProperty(category = "drawing") 10386 public boolean hasOverlappingRendering() { 10387 return true; 10388 } 10389 10390 /** 10391 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is 10392 * completely transparent and 1 means the view is completely opaque.</p> 10393 * 10394 * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant 10395 * performance implications, especially for large views. It is best to use the alpha property 10396 * sparingly and transiently, as in the case of fading animations.</p> 10397 * 10398 * <p>For a view with a frequently changing alpha, such as during a fading animation, it is 10399 * strongly recommended for performance reasons to either override 10400 * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a 10401 * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p> 10402 * 10403 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 10404 * responsible for applying the opacity itself.</p> 10405 * 10406 * <p>Note that if the view is backed by a 10407 * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a 10408 * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than 10409 * 1.0 will supercede the alpha of the layer paint.</p> 10410 * 10411 * @param alpha The opacity of the view. 10412 * 10413 * @see #hasOverlappingRendering() 10414 * @see #setLayerType(int, android.graphics.Paint) 10415 * 10416 * @attr ref android.R.styleable#View_alpha 10417 */ 10418 public void setAlpha(float alpha) { 10419 ensureTransformationInfo(); 10420 if (mTransformationInfo.mAlpha != alpha) { 10421 mTransformationInfo.mAlpha = alpha; 10422 if (onSetAlpha((int) (alpha * 255))) { 10423 mPrivateFlags |= PFLAG_ALPHA_SET; 10424 // subclass is handling alpha - don't optimize rendering cache invalidation 10425 invalidateParentCaches(); 10426 invalidate(true); 10427 } else { 10428 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10429 invalidateViewProperty(true, false); 10430 mRenderNode.setAlpha(getFinalAlpha()); 10431 notifyViewAccessibilityStateChangedIfNeeded( 10432 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 10433 } 10434 } 10435 } 10436 10437 /** 10438 * Faster version of setAlpha() which performs the same steps except there are 10439 * no calls to invalidate(). The caller of this function should perform proper invalidation 10440 * on the parent and this object. The return value indicates whether the subclass handles 10441 * alpha (the return value for onSetAlpha()). 10442 * 10443 * @param alpha The new value for the alpha property 10444 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 10445 * the new value for the alpha property is different from the old value 10446 */ 10447 boolean setAlphaNoInvalidation(float alpha) { 10448 ensureTransformationInfo(); 10449 if (mTransformationInfo.mAlpha != alpha) { 10450 mTransformationInfo.mAlpha = alpha; 10451 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 10452 if (subclassHandlesAlpha) { 10453 mPrivateFlags |= PFLAG_ALPHA_SET; 10454 return true; 10455 } else { 10456 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10457 mRenderNode.setAlpha(getFinalAlpha()); 10458 } 10459 } 10460 return false; 10461 } 10462 10463 /** 10464 * This property is hidden and intended only for use by the Fade transition, which 10465 * animates it to produce a visual translucency that does not side-effect (or get 10466 * affected by) the real alpha property. This value is composited with the other 10467 * alpha value (and the AlphaAnimation value, when that is present) to produce 10468 * a final visual translucency result, which is what is passed into the DisplayList. 10469 * 10470 * @hide 10471 */ 10472 public void setTransitionAlpha(float alpha) { 10473 ensureTransformationInfo(); 10474 if (mTransformationInfo.mTransitionAlpha != alpha) { 10475 mTransformationInfo.mTransitionAlpha = alpha; 10476 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10477 invalidateViewProperty(true, false); 10478 mRenderNode.setAlpha(getFinalAlpha()); 10479 } 10480 } 10481 10482 /** 10483 * Calculates the visual alpha of this view, which is a combination of the actual 10484 * alpha value and the transitionAlpha value (if set). 10485 */ 10486 private float getFinalAlpha() { 10487 if (mTransformationInfo != null) { 10488 return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha; 10489 } 10490 return 1; 10491 } 10492 10493 /** 10494 * This property is hidden and intended only for use by the Fade transition, which 10495 * animates it to produce a visual translucency that does not side-effect (or get 10496 * affected by) the real alpha property. This value is composited with the other 10497 * alpha value (and the AlphaAnimation value, when that is present) to produce 10498 * a final visual translucency result, which is what is passed into the DisplayList. 10499 * 10500 * @hide 10501 */ 10502 @ViewDebug.ExportedProperty(category = "drawing") 10503 public float getTransitionAlpha() { 10504 return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1; 10505 } 10506 10507 /** 10508 * Top position of this view relative to its parent. 10509 * 10510 * @return The top of this view, in pixels. 10511 */ 10512 @ViewDebug.CapturedViewProperty 10513 public final int getTop() { 10514 return mTop; 10515 } 10516 10517 /** 10518 * Sets the top position of this view relative to its parent. This method is meant to be called 10519 * by the layout system and should not generally be called otherwise, because the property 10520 * may be changed at any time by the layout. 10521 * 10522 * @param top The top of this view, in pixels. 10523 */ 10524 public final void setTop(int top) { 10525 if (top != mTop) { 10526 final boolean matrixIsIdentity = hasIdentityMatrix(); 10527 if (matrixIsIdentity) { 10528 if (mAttachInfo != null) { 10529 int minTop; 10530 int yLoc; 10531 if (top < mTop) { 10532 minTop = top; 10533 yLoc = top - mTop; 10534 } else { 10535 minTop = mTop; 10536 yLoc = 0; 10537 } 10538 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 10539 } 10540 } else { 10541 // Double-invalidation is necessary to capture view's old and new areas 10542 invalidate(true); 10543 } 10544 10545 int width = mRight - mLeft; 10546 int oldHeight = mBottom - mTop; 10547 10548 mTop = top; 10549 mRenderNode.setTop(mTop); 10550 10551 sizeChange(width, mBottom - mTop, width, oldHeight); 10552 10553 if (!matrixIsIdentity) { 10554 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10555 invalidate(true); 10556 } 10557 mBackgroundSizeChanged = true; 10558 invalidateParentIfNeeded(); 10559 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10560 // View was rejected last time it was drawn by its parent; this may have changed 10561 invalidateParentIfNeeded(); 10562 } 10563 } 10564 } 10565 10566 /** 10567 * Bottom position of this view relative to its parent. 10568 * 10569 * @return The bottom of this view, in pixels. 10570 */ 10571 @ViewDebug.CapturedViewProperty 10572 public final int getBottom() { 10573 return mBottom; 10574 } 10575 10576 /** 10577 * True if this view has changed since the last time being drawn. 10578 * 10579 * @return The dirty state of this view. 10580 */ 10581 public boolean isDirty() { 10582 return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0; 10583 } 10584 10585 /** 10586 * Sets the bottom position of this view relative to its parent. This method is meant to be 10587 * called by the layout system and should not generally be called otherwise, because the 10588 * property may be changed at any time by the layout. 10589 * 10590 * @param bottom The bottom of this view, in pixels. 10591 */ 10592 public final void setBottom(int bottom) { 10593 if (bottom != mBottom) { 10594 final boolean matrixIsIdentity = hasIdentityMatrix(); 10595 if (matrixIsIdentity) { 10596 if (mAttachInfo != null) { 10597 int maxBottom; 10598 if (bottom < mBottom) { 10599 maxBottom = mBottom; 10600 } else { 10601 maxBottom = bottom; 10602 } 10603 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 10604 } 10605 } else { 10606 // Double-invalidation is necessary to capture view's old and new areas 10607 invalidate(true); 10608 } 10609 10610 int width = mRight - mLeft; 10611 int oldHeight = mBottom - mTop; 10612 10613 mBottom = bottom; 10614 mRenderNode.setBottom(mBottom); 10615 10616 sizeChange(width, mBottom - mTop, width, oldHeight); 10617 10618 if (!matrixIsIdentity) { 10619 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10620 invalidate(true); 10621 } 10622 mBackgroundSizeChanged = true; 10623 invalidateParentIfNeeded(); 10624 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10625 // View was rejected last time it was drawn by its parent; this may have changed 10626 invalidateParentIfNeeded(); 10627 } 10628 } 10629 } 10630 10631 /** 10632 * Left position of this view relative to its parent. 10633 * 10634 * @return The left edge of this view, in pixels. 10635 */ 10636 @ViewDebug.CapturedViewProperty 10637 public final int getLeft() { 10638 return mLeft; 10639 } 10640 10641 /** 10642 * Sets the left position of this view relative to its parent. This method is meant to be called 10643 * by the layout system and should not generally be called otherwise, because the property 10644 * may be changed at any time by the layout. 10645 * 10646 * @param left The left of this view, in pixels. 10647 */ 10648 public final void setLeft(int left) { 10649 if (left != mLeft) { 10650 final boolean matrixIsIdentity = hasIdentityMatrix(); 10651 if (matrixIsIdentity) { 10652 if (mAttachInfo != null) { 10653 int minLeft; 10654 int xLoc; 10655 if (left < mLeft) { 10656 minLeft = left; 10657 xLoc = left - mLeft; 10658 } else { 10659 minLeft = mLeft; 10660 xLoc = 0; 10661 } 10662 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 10663 } 10664 } else { 10665 // Double-invalidation is necessary to capture view's old and new areas 10666 invalidate(true); 10667 } 10668 10669 int oldWidth = mRight - mLeft; 10670 int height = mBottom - mTop; 10671 10672 mLeft = left; 10673 mRenderNode.setLeft(left); 10674 10675 sizeChange(mRight - mLeft, height, oldWidth, height); 10676 10677 if (!matrixIsIdentity) { 10678 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10679 invalidate(true); 10680 } 10681 mBackgroundSizeChanged = true; 10682 invalidateParentIfNeeded(); 10683 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10684 // View was rejected last time it was drawn by its parent; this may have changed 10685 invalidateParentIfNeeded(); 10686 } 10687 } 10688 } 10689 10690 /** 10691 * Right position of this view relative to its parent. 10692 * 10693 * @return The right edge of this view, in pixels. 10694 */ 10695 @ViewDebug.CapturedViewProperty 10696 public final int getRight() { 10697 return mRight; 10698 } 10699 10700 /** 10701 * Sets the right position of this view relative to its parent. This method is meant to be called 10702 * by the layout system and should not generally be called otherwise, because the property 10703 * may be changed at any time by the layout. 10704 * 10705 * @param right The right of this view, in pixels. 10706 */ 10707 public final void setRight(int right) { 10708 if (right != mRight) { 10709 final boolean matrixIsIdentity = hasIdentityMatrix(); 10710 if (matrixIsIdentity) { 10711 if (mAttachInfo != null) { 10712 int maxRight; 10713 if (right < mRight) { 10714 maxRight = mRight; 10715 } else { 10716 maxRight = right; 10717 } 10718 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 10719 } 10720 } else { 10721 // Double-invalidation is necessary to capture view's old and new areas 10722 invalidate(true); 10723 } 10724 10725 int oldWidth = mRight - mLeft; 10726 int height = mBottom - mTop; 10727 10728 mRight = right; 10729 mRenderNode.setRight(mRight); 10730 10731 sizeChange(mRight - mLeft, height, oldWidth, height); 10732 10733 if (!matrixIsIdentity) { 10734 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10735 invalidate(true); 10736 } 10737 mBackgroundSizeChanged = true; 10738 invalidateParentIfNeeded(); 10739 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10740 // View was rejected last time it was drawn by its parent; this may have changed 10741 invalidateParentIfNeeded(); 10742 } 10743 } 10744 } 10745 10746 /** 10747 * The visual x position of this view, in pixels. This is equivalent to the 10748 * {@link #setTranslationX(float) translationX} property plus the current 10749 * {@link #getLeft() left} property. 10750 * 10751 * @return The visual x position of this view, in pixels. 10752 */ 10753 @ViewDebug.ExportedProperty(category = "drawing") 10754 public float getX() { 10755 return mLeft + getTranslationX(); 10756 } 10757 10758 /** 10759 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 10760 * {@link #setTranslationX(float) translationX} property to be the difference between 10761 * the x value passed in and the current {@link #getLeft() left} property. 10762 * 10763 * @param x The visual x position of this view, in pixels. 10764 */ 10765 public void setX(float x) { 10766 setTranslationX(x - mLeft); 10767 } 10768 10769 /** 10770 * The visual y position of this view, in pixels. This is equivalent to the 10771 * {@link #setTranslationY(float) translationY} property plus the current 10772 * {@link #getTop() top} property. 10773 * 10774 * @return The visual y position of this view, in pixels. 10775 */ 10776 @ViewDebug.ExportedProperty(category = "drawing") 10777 public float getY() { 10778 return mTop + getTranslationY(); 10779 } 10780 10781 /** 10782 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 10783 * {@link #setTranslationY(float) translationY} property to be the difference between 10784 * the y value passed in and the current {@link #getTop() top} property. 10785 * 10786 * @param y The visual y position of this view, in pixels. 10787 */ 10788 public void setY(float y) { 10789 setTranslationY(y - mTop); 10790 } 10791 10792 /** 10793 * The visual z position of this view, in pixels. This is equivalent to the 10794 * {@link #setTranslationZ(float) translationZ} property plus the current 10795 * {@link #getElevation() elevation} property. 10796 * 10797 * @return The visual z position of this view, in pixels. 10798 */ 10799 @ViewDebug.ExportedProperty(category = "drawing") 10800 public float getZ() { 10801 return getElevation() + getTranslationZ(); 10802 } 10803 10804 /** 10805 * Sets the visual z position of this view, in pixels. This is equivalent to setting the 10806 * {@link #setTranslationZ(float) translationZ} property to be the difference between 10807 * the x value passed in and the current {@link #getElevation() elevation} property. 10808 * 10809 * @param z The visual z position of this view, in pixels. 10810 */ 10811 public void setZ(float z) { 10812 setTranslationZ(z - getElevation()); 10813 } 10814 10815 /** 10816 * The base elevation of this view relative to its parent, in pixels. 10817 * 10818 * @return The base depth position of the view, in pixels. 10819 */ 10820 @ViewDebug.ExportedProperty(category = "drawing") 10821 public float getElevation() { 10822 return mRenderNode.getElevation(); 10823 } 10824 10825 /** 10826 * Sets the base elevation of this view, in pixels. 10827 * 10828 * @attr ref android.R.styleable#View_elevation 10829 */ 10830 public void setElevation(float elevation) { 10831 if (elevation != getElevation()) { 10832 invalidateViewProperty(true, false); 10833 mRenderNode.setElevation(elevation); 10834 invalidateViewProperty(false, true); 10835 10836 invalidateParentIfNeededAndWasQuickRejected(); 10837 } 10838 } 10839 10840 /** 10841 * The horizontal location of this view relative to its {@link #getLeft() left} position. 10842 * This position is post-layout, in addition to wherever the object's 10843 * layout placed it. 10844 * 10845 * @return The horizontal position of this view relative to its left position, in pixels. 10846 */ 10847 @ViewDebug.ExportedProperty(category = "drawing") 10848 public float getTranslationX() { 10849 return mRenderNode.getTranslationX(); 10850 } 10851 10852 /** 10853 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 10854 * This effectively positions the object post-layout, in addition to wherever the object's 10855 * layout placed it. 10856 * 10857 * @param translationX The horizontal position of this view relative to its left position, 10858 * in pixels. 10859 * 10860 * @attr ref android.R.styleable#View_translationX 10861 */ 10862 public void setTranslationX(float translationX) { 10863 if (translationX != getTranslationX()) { 10864 invalidateViewProperty(true, false); 10865 mRenderNode.setTranslationX(translationX); 10866 invalidateViewProperty(false, true); 10867 10868 invalidateParentIfNeededAndWasQuickRejected(); 10869 notifySubtreeAccessibilityStateChangedIfNeeded(); 10870 } 10871 } 10872 10873 /** 10874 * The vertical location of this view relative to its {@link #getTop() top} position. 10875 * This position is post-layout, in addition to wherever the object's 10876 * layout placed it. 10877 * 10878 * @return The vertical position of this view relative to its top position, 10879 * in pixels. 10880 */ 10881 @ViewDebug.ExportedProperty(category = "drawing") 10882 public float getTranslationY() { 10883 return mRenderNode.getTranslationY(); 10884 } 10885 10886 /** 10887 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 10888 * This effectively positions the object post-layout, in addition to wherever the object's 10889 * layout placed it. 10890 * 10891 * @param translationY The vertical position of this view relative to its top position, 10892 * in pixels. 10893 * 10894 * @attr ref android.R.styleable#View_translationY 10895 */ 10896 public void setTranslationY(float translationY) { 10897 if (translationY != getTranslationY()) { 10898 invalidateViewProperty(true, false); 10899 mRenderNode.setTranslationY(translationY); 10900 invalidateViewProperty(false, true); 10901 10902 invalidateParentIfNeededAndWasQuickRejected(); 10903 } 10904 } 10905 10906 /** 10907 * The depth location of this view relative to its {@link #getElevation() elevation}. 10908 * 10909 * @return The depth of this view relative to its elevation. 10910 */ 10911 @ViewDebug.ExportedProperty(category = "drawing") 10912 public float getTranslationZ() { 10913 return mRenderNode.getTranslationZ(); 10914 } 10915 10916 /** 10917 * Sets the depth location of this view relative to its {@link #getElevation() elevation}. 10918 * 10919 * @attr ref android.R.styleable#View_translationZ 10920 */ 10921 public void setTranslationZ(float translationZ) { 10922 if (translationZ != getTranslationZ()) { 10923 invalidateViewProperty(true, false); 10924 mRenderNode.setTranslationZ(translationZ); 10925 invalidateViewProperty(false, true); 10926 10927 invalidateParentIfNeededAndWasQuickRejected(); 10928 } 10929 } 10930 10931 /** @hide */ 10932 public void setAnimationMatrix(Matrix matrix) { 10933 invalidateViewProperty(true, false); 10934 mRenderNode.setAnimationMatrix(matrix); 10935 invalidateViewProperty(false, true); 10936 10937 invalidateParentIfNeededAndWasQuickRejected(); 10938 } 10939 10940 /** 10941 * Returns the current StateListAnimator if exists. 10942 * 10943 * @return StateListAnimator or null if it does not exists 10944 * @see #setStateListAnimator(android.animation.StateListAnimator) 10945 */ 10946 public StateListAnimator getStateListAnimator() { 10947 return mStateListAnimator; 10948 } 10949 10950 /** 10951 * Attaches the provided StateListAnimator to this View. 10952 * <p> 10953 * Any previously attached StateListAnimator will be detached. 10954 * 10955 * @param stateListAnimator The StateListAnimator to update the view 10956 * @see {@link android.animation.StateListAnimator} 10957 */ 10958 public void setStateListAnimator(StateListAnimator stateListAnimator) { 10959 if (mStateListAnimator == stateListAnimator) { 10960 return; 10961 } 10962 if (mStateListAnimator != null) { 10963 mStateListAnimator.setTarget(null); 10964 } 10965 mStateListAnimator = stateListAnimator; 10966 if (stateListAnimator != null) { 10967 stateListAnimator.setTarget(this); 10968 if (isAttachedToWindow()) { 10969 stateListAnimator.setState(getDrawableState()); 10970 } 10971 } 10972 } 10973 10974 /** 10975 * Returns whether the Outline should be used to clip the contents of the View. 10976 * <p> 10977 * Note that this flag will only be respected if the View's Outline returns true from 10978 * {@link Outline#canClip()}. 10979 * 10980 * @see #setOutlineProvider(ViewOutlineProvider) 10981 * @see #setClipToOutline(boolean) 10982 */ 10983 public final boolean getClipToOutline() { 10984 return mRenderNode.getClipToOutline(); 10985 } 10986 10987 /** 10988 * Sets whether the View's Outline should be used to clip the contents of the View. 10989 * <p> 10990 * Only a single non-rectangular clip can be applied on a View at any time. 10991 * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float) 10992 * circular reveal} animation take priority over Outline clipping, and 10993 * child Outline clipping takes priority over Outline clipping done by a 10994 * parent. 10995 * <p> 10996 * Note that this flag will only be respected if the View's Outline returns true from 10997 * {@link Outline#canClip()}. 10998 * 10999 * @see #setOutlineProvider(ViewOutlineProvider) 11000 * @see #getClipToOutline() 11001 */ 11002 public void setClipToOutline(boolean clipToOutline) { 11003 damageInParent(); 11004 if (getClipToOutline() != clipToOutline) { 11005 mRenderNode.setClipToOutline(clipToOutline); 11006 } 11007 } 11008 11009 // correspond to the enum values of View_outlineProvider 11010 private static final int PROVIDER_BACKGROUND = 0; 11011 private static final int PROVIDER_NONE = 1; 11012 private static final int PROVIDER_BOUNDS = 2; 11013 private static final int PROVIDER_PADDED_BOUNDS = 3; 11014 private void setOutlineProviderFromAttribute(int providerInt) { 11015 switch (providerInt) { 11016 case PROVIDER_BACKGROUND: 11017 setOutlineProvider(ViewOutlineProvider.BACKGROUND); 11018 break; 11019 case PROVIDER_NONE: 11020 setOutlineProvider(null); 11021 break; 11022 case PROVIDER_BOUNDS: 11023 setOutlineProvider(ViewOutlineProvider.BOUNDS); 11024 break; 11025 case PROVIDER_PADDED_BOUNDS: 11026 setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS); 11027 break; 11028 } 11029 } 11030 11031 /** 11032 * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines 11033 * the shape of the shadow it casts, and enables outline clipping. 11034 * <p> 11035 * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline 11036 * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the 11037 * outline provider with this method allows this behavior to be overridden. 11038 * <p> 11039 * If the ViewOutlineProvider is null, if querying it for an outline returns false, 11040 * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast. 11041 * <p> 11042 * Only outlines that return true from {@link Outline#canClip()} may be used for clipping. 11043 * 11044 * @see #setClipToOutline(boolean) 11045 * @see #getClipToOutline() 11046 * @see #getOutlineProvider() 11047 */ 11048 public void setOutlineProvider(ViewOutlineProvider provider) { 11049 mOutlineProvider = provider; 11050 invalidateOutline(); 11051 } 11052 11053 /** 11054 * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline 11055 * that defines the shape of the shadow it casts, and enables outline clipping. 11056 * 11057 * @see #setOutlineProvider(ViewOutlineProvider) 11058 */ 11059 public ViewOutlineProvider getOutlineProvider() { 11060 return mOutlineProvider; 11061 } 11062 11063 /** 11064 * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider} 11065 * 11066 * @see #setOutlineProvider(ViewOutlineProvider) 11067 */ 11068 public void invalidateOutline() { 11069 // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow() 11070 if (mAttachInfo == null) return; 11071 11072 if (mOutlineProvider == null) { 11073 // no provider, remove outline 11074 mRenderNode.setOutline(null); 11075 } else { 11076 final Outline outline = mAttachInfo.mTmpOutline; 11077 outline.setEmpty(); 11078 outline.setAlpha(1.0f); 11079 11080 mOutlineProvider.getOutline(this, outline); 11081 mRenderNode.setOutline(outline); 11082 } 11083 11084 notifySubtreeAccessibilityStateChangedIfNeeded(); 11085 invalidateViewProperty(false, false); 11086 } 11087 11088 /** 11089 * HierarchyViewer only 11090 * 11091 * @hide 11092 */ 11093 @ViewDebug.ExportedProperty(category = "drawing") 11094 public boolean hasShadow() { 11095 return mRenderNode.hasShadow(); 11096 } 11097 11098 11099 /** @hide */ 11100 public void setRevealClip(boolean shouldClip, float x, float y, float radius) { 11101 mRenderNode.setRevealClip(shouldClip, x, y, radius); 11102 invalidateViewProperty(false, false); 11103 } 11104 11105 /** 11106 * Hit rectangle in parent's coordinates 11107 * 11108 * @param outRect The hit rectangle of the view. 11109 */ 11110 public void getHitRect(Rect outRect) { 11111 if (hasIdentityMatrix() || mAttachInfo == null) { 11112 outRect.set(mLeft, mTop, mRight, mBottom); 11113 } else { 11114 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 11115 tmpRect.set(0, 0, getWidth(), getHeight()); 11116 getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect) 11117 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 11118 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 11119 } 11120 } 11121 11122 /** 11123 * Determines whether the given point, in local coordinates is inside the view. 11124 */ 11125 /*package*/ final boolean pointInView(float localX, float localY) { 11126 return localX >= 0 && localX < (mRight - mLeft) 11127 && localY >= 0 && localY < (mBottom - mTop); 11128 } 11129 11130 /** 11131 * Utility method to determine whether the given point, in local coordinates, 11132 * is inside the view, where the area of the view is expanded by the slop factor. 11133 * This method is called while processing touch-move events to determine if the event 11134 * is still within the view. 11135 * 11136 * @hide 11137 */ 11138 public boolean pointInView(float localX, float localY, float slop) { 11139 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 11140 localY < ((mBottom - mTop) + slop); 11141 } 11142 11143 /** 11144 * When a view has focus and the user navigates away from it, the next view is searched for 11145 * starting from the rectangle filled in by this method. 11146 * 11147 * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)}) 11148 * of the view. However, if your view maintains some idea of internal selection, 11149 * such as a cursor, or a selected row or column, you should override this method and 11150 * fill in a more specific rectangle. 11151 * 11152 * @param r The rectangle to fill in, in this view's coordinates. 11153 */ 11154 public void getFocusedRect(Rect r) { 11155 getDrawingRect(r); 11156 } 11157 11158 /** 11159 * If some part of this view is not clipped by any of its parents, then 11160 * return that area in r in global (root) coordinates. To convert r to local 11161 * coordinates (without taking possible View rotations into account), offset 11162 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 11163 * If the view is completely clipped or translated out, return false. 11164 * 11165 * @param r If true is returned, r holds the global coordinates of the 11166 * visible portion of this view. 11167 * @param globalOffset If true is returned, globalOffset holds the dx,dy 11168 * between this view and its root. globalOffet may be null. 11169 * @return true if r is non-empty (i.e. part of the view is visible at the 11170 * root level. 11171 */ 11172 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 11173 int width = mRight - mLeft; 11174 int height = mBottom - mTop; 11175 if (width > 0 && height > 0) { 11176 r.set(0, 0, width, height); 11177 if (globalOffset != null) { 11178 globalOffset.set(-mScrollX, -mScrollY); 11179 } 11180 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 11181 } 11182 return false; 11183 } 11184 11185 public final boolean getGlobalVisibleRect(Rect r) { 11186 return getGlobalVisibleRect(r, null); 11187 } 11188 11189 public final boolean getLocalVisibleRect(Rect r) { 11190 final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point(); 11191 if (getGlobalVisibleRect(r, offset)) { 11192 r.offset(-offset.x, -offset.y); // make r local 11193 return true; 11194 } 11195 return false; 11196 } 11197 11198 /** 11199 * Offset this view's vertical location by the specified number of pixels. 11200 * 11201 * @param offset the number of pixels to offset the view by 11202 */ 11203 public void offsetTopAndBottom(int offset) { 11204 if (offset != 0) { 11205 final boolean matrixIsIdentity = hasIdentityMatrix(); 11206 if (matrixIsIdentity) { 11207 if (isHardwareAccelerated()) { 11208 invalidateViewProperty(false, false); 11209 } else { 11210 final ViewParent p = mParent; 11211 if (p != null && mAttachInfo != null) { 11212 final Rect r = mAttachInfo.mTmpInvalRect; 11213 int minTop; 11214 int maxBottom; 11215 int yLoc; 11216 if (offset < 0) { 11217 minTop = mTop + offset; 11218 maxBottom = mBottom; 11219 yLoc = offset; 11220 } else { 11221 minTop = mTop; 11222 maxBottom = mBottom + offset; 11223 yLoc = 0; 11224 } 11225 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 11226 p.invalidateChild(this, r); 11227 } 11228 } 11229 } else { 11230 invalidateViewProperty(false, false); 11231 } 11232 11233 mTop += offset; 11234 mBottom += offset; 11235 mRenderNode.offsetTopAndBottom(offset); 11236 if (isHardwareAccelerated()) { 11237 invalidateViewProperty(false, false); 11238 } else { 11239 if (!matrixIsIdentity) { 11240 invalidateViewProperty(false, true); 11241 } 11242 invalidateParentIfNeeded(); 11243 } 11244 notifySubtreeAccessibilityStateChangedIfNeeded(); 11245 } 11246 } 11247 11248 /** 11249 * Offset this view's horizontal location by the specified amount of pixels. 11250 * 11251 * @param offset the number of pixels to offset the view by 11252 */ 11253 public void offsetLeftAndRight(int offset) { 11254 if (offset != 0) { 11255 final boolean matrixIsIdentity = hasIdentityMatrix(); 11256 if (matrixIsIdentity) { 11257 if (isHardwareAccelerated()) { 11258 invalidateViewProperty(false, false); 11259 } else { 11260 final ViewParent p = mParent; 11261 if (p != null && mAttachInfo != null) { 11262 final Rect r = mAttachInfo.mTmpInvalRect; 11263 int minLeft; 11264 int maxRight; 11265 if (offset < 0) { 11266 minLeft = mLeft + offset; 11267 maxRight = mRight; 11268 } else { 11269 minLeft = mLeft; 11270 maxRight = mRight + offset; 11271 } 11272 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 11273 p.invalidateChild(this, r); 11274 } 11275 } 11276 } else { 11277 invalidateViewProperty(false, false); 11278 } 11279 11280 mLeft += offset; 11281 mRight += offset; 11282 mRenderNode.offsetLeftAndRight(offset); 11283 if (isHardwareAccelerated()) { 11284 invalidateViewProperty(false, false); 11285 } else { 11286 if (!matrixIsIdentity) { 11287 invalidateViewProperty(false, true); 11288 } 11289 invalidateParentIfNeeded(); 11290 } 11291 notifySubtreeAccessibilityStateChangedIfNeeded(); 11292 } 11293 } 11294 11295 /** 11296 * Get the LayoutParams associated with this view. All views should have 11297 * layout parameters. These supply parameters to the <i>parent</i> of this 11298 * view specifying how it should be arranged. There are many subclasses of 11299 * ViewGroup.LayoutParams, and these correspond to the different subclasses 11300 * of ViewGroup that are responsible for arranging their children. 11301 * 11302 * This method may return null if this View is not attached to a parent 11303 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 11304 * was not invoked successfully. When a View is attached to a parent 11305 * ViewGroup, this method must not return null. 11306 * 11307 * @return The LayoutParams associated with this view, or null if no 11308 * parameters have been set yet 11309 */ 11310 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 11311 public ViewGroup.LayoutParams getLayoutParams() { 11312 return mLayoutParams; 11313 } 11314 11315 /** 11316 * Set the layout parameters associated with this view. These supply 11317 * parameters to the <i>parent</i> of this view specifying how it should be 11318 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 11319 * correspond to the different subclasses of ViewGroup that are responsible 11320 * for arranging their children. 11321 * 11322 * @param params The layout parameters for this view, cannot be null 11323 */ 11324 public void setLayoutParams(ViewGroup.LayoutParams params) { 11325 if (params == null) { 11326 throw new NullPointerException("Layout parameters cannot be null"); 11327 } 11328 mLayoutParams = params; 11329 resolveLayoutParams(); 11330 if (mParent instanceof ViewGroup) { 11331 ((ViewGroup) mParent).onSetLayoutParams(this, params); 11332 } 11333 requestLayout(); 11334 } 11335 11336 /** 11337 * Resolve the layout parameters depending on the resolved layout direction 11338 * 11339 * @hide 11340 */ 11341 public void resolveLayoutParams() { 11342 if (mLayoutParams != null) { 11343 mLayoutParams.resolveLayoutDirection(getLayoutDirection()); 11344 } 11345 } 11346 11347 /** 11348 * Set the scrolled position of your view. This will cause a call to 11349 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11350 * invalidated. 11351 * @param x the x position to scroll to 11352 * @param y the y position to scroll to 11353 */ 11354 public void scrollTo(int x, int y) { 11355 if (mScrollX != x || mScrollY != y) { 11356 int oldX = mScrollX; 11357 int oldY = mScrollY; 11358 mScrollX = x; 11359 mScrollY = y; 11360 invalidateParentCaches(); 11361 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 11362 if (!awakenScrollBars()) { 11363 postInvalidateOnAnimation(); 11364 } 11365 } 11366 } 11367 11368 /** 11369 * Move the scrolled position of your view. This will cause a call to 11370 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11371 * invalidated. 11372 * @param x the amount of pixels to scroll by horizontally 11373 * @param y the amount of pixels to scroll by vertically 11374 */ 11375 public void scrollBy(int x, int y) { 11376 scrollTo(mScrollX + x, mScrollY + y); 11377 } 11378 11379 /** 11380 * <p>Trigger the scrollbars to draw. When invoked this method starts an 11381 * animation to fade the scrollbars out after a default delay. If a subclass 11382 * provides animated scrolling, the start delay should equal the duration 11383 * of the scrolling animation.</p> 11384 * 11385 * <p>The animation starts only if at least one of the scrollbars is 11386 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 11387 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11388 * this method returns true, and false otherwise. If the animation is 11389 * started, this method calls {@link #invalidate()}; in that case the 11390 * caller should not call {@link #invalidate()}.</p> 11391 * 11392 * <p>This method should be invoked every time a subclass directly updates 11393 * the scroll parameters.</p> 11394 * 11395 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 11396 * and {@link #scrollTo(int, int)}.</p> 11397 * 11398 * @return true if the animation is played, false otherwise 11399 * 11400 * @see #awakenScrollBars(int) 11401 * @see #scrollBy(int, int) 11402 * @see #scrollTo(int, int) 11403 * @see #isHorizontalScrollBarEnabled() 11404 * @see #isVerticalScrollBarEnabled() 11405 * @see #setHorizontalScrollBarEnabled(boolean) 11406 * @see #setVerticalScrollBarEnabled(boolean) 11407 */ 11408 protected boolean awakenScrollBars() { 11409 return mScrollCache != null && 11410 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 11411 } 11412 11413 /** 11414 * Trigger the scrollbars to draw. 11415 * This method differs from awakenScrollBars() only in its default duration. 11416 * initialAwakenScrollBars() will show the scroll bars for longer than 11417 * usual to give the user more of a chance to notice them. 11418 * 11419 * @return true if the animation is played, false otherwise. 11420 */ 11421 private boolean initialAwakenScrollBars() { 11422 return mScrollCache != null && 11423 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 11424 } 11425 11426 /** 11427 * <p> 11428 * Trigger the scrollbars to draw. When invoked this method starts an 11429 * animation to fade the scrollbars out after a fixed delay. If a subclass 11430 * provides animated scrolling, the start delay should equal the duration of 11431 * the scrolling animation. 11432 * </p> 11433 * 11434 * <p> 11435 * The animation starts only if at least one of the scrollbars is enabled, 11436 * as specified by {@link #isHorizontalScrollBarEnabled()} and 11437 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11438 * this method returns true, and false otherwise. If the animation is 11439 * started, this method calls {@link #invalidate()}; in that case the caller 11440 * should not call {@link #invalidate()}. 11441 * </p> 11442 * 11443 * <p> 11444 * This method should be invoked everytime a subclass directly updates the 11445 * scroll parameters. 11446 * </p> 11447 * 11448 * @param startDelay the delay, in milliseconds, after which the animation 11449 * should start; when the delay is 0, the animation starts 11450 * immediately 11451 * @return true if the animation is played, false otherwise 11452 * 11453 * @see #scrollBy(int, int) 11454 * @see #scrollTo(int, int) 11455 * @see #isHorizontalScrollBarEnabled() 11456 * @see #isVerticalScrollBarEnabled() 11457 * @see #setHorizontalScrollBarEnabled(boolean) 11458 * @see #setVerticalScrollBarEnabled(boolean) 11459 */ 11460 protected boolean awakenScrollBars(int startDelay) { 11461 return awakenScrollBars(startDelay, true); 11462 } 11463 11464 /** 11465 * <p> 11466 * Trigger the scrollbars to draw. When invoked this method starts an 11467 * animation to fade the scrollbars out after a fixed delay. If a subclass 11468 * provides animated scrolling, the start delay should equal the duration of 11469 * the scrolling animation. 11470 * </p> 11471 * 11472 * <p> 11473 * The animation starts only if at least one of the scrollbars is enabled, 11474 * as specified by {@link #isHorizontalScrollBarEnabled()} and 11475 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11476 * this method returns true, and false otherwise. If the animation is 11477 * started, this method calls {@link #invalidate()} if the invalidate parameter 11478 * is set to true; in that case the caller 11479 * should not call {@link #invalidate()}. 11480 * </p> 11481 * 11482 * <p> 11483 * This method should be invoked everytime a subclass directly updates the 11484 * scroll parameters. 11485 * </p> 11486 * 11487 * @param startDelay the delay, in milliseconds, after which the animation 11488 * should start; when the delay is 0, the animation starts 11489 * immediately 11490 * 11491 * @param invalidate Wheter this method should call invalidate 11492 * 11493 * @return true if the animation is played, false otherwise 11494 * 11495 * @see #scrollBy(int, int) 11496 * @see #scrollTo(int, int) 11497 * @see #isHorizontalScrollBarEnabled() 11498 * @see #isVerticalScrollBarEnabled() 11499 * @see #setHorizontalScrollBarEnabled(boolean) 11500 * @see #setVerticalScrollBarEnabled(boolean) 11501 */ 11502 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 11503 final ScrollabilityCache scrollCache = mScrollCache; 11504 11505 if (scrollCache == null || !scrollCache.fadeScrollBars) { 11506 return false; 11507 } 11508 11509 if (scrollCache.scrollBar == null) { 11510 scrollCache.scrollBar = new ScrollBarDrawable(); 11511 } 11512 11513 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 11514 11515 if (invalidate) { 11516 // Invalidate to show the scrollbars 11517 postInvalidateOnAnimation(); 11518 } 11519 11520 if (scrollCache.state == ScrollabilityCache.OFF) { 11521 // FIXME: this is copied from WindowManagerService. 11522 // We should get this value from the system when it 11523 // is possible to do so. 11524 final int KEY_REPEAT_FIRST_DELAY = 750; 11525 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 11526 } 11527 11528 // Tell mScrollCache when we should start fading. This may 11529 // extend the fade start time if one was already scheduled 11530 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 11531 scrollCache.fadeStartTime = fadeStartTime; 11532 scrollCache.state = ScrollabilityCache.ON; 11533 11534 // Schedule our fader to run, unscheduling any old ones first 11535 if (mAttachInfo != null) { 11536 mAttachInfo.mHandler.removeCallbacks(scrollCache); 11537 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 11538 } 11539 11540 return true; 11541 } 11542 11543 return false; 11544 } 11545 11546 /** 11547 * Do not invalidate views which are not visible and which are not running an animation. They 11548 * will not get drawn and they should not set dirty flags as if they will be drawn 11549 */ 11550 private boolean skipInvalidate() { 11551 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 11552 (!(mParent instanceof ViewGroup) || 11553 !((ViewGroup) mParent).isViewTransitioning(this)); 11554 } 11555 11556 /** 11557 * Mark the area defined by dirty as needing to be drawn. If the view is 11558 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 11559 * point in the future. 11560 * <p> 11561 * This must be called from a UI thread. To call from a non-UI thread, call 11562 * {@link #postInvalidate()}. 11563 * <p> 11564 * <b>WARNING:</b> In API 19 and below, this method may be destructive to 11565 * {@code dirty}. 11566 * 11567 * @param dirty the rectangle representing the bounds of the dirty region 11568 */ 11569 public void invalidate(Rect dirty) { 11570 final int scrollX = mScrollX; 11571 final int scrollY = mScrollY; 11572 invalidateInternal(dirty.left - scrollX, dirty.top - scrollY, 11573 dirty.right - scrollX, dirty.bottom - scrollY, true, false); 11574 } 11575 11576 /** 11577 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The 11578 * coordinates of the dirty rect are relative to the view. If the view is 11579 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 11580 * point in the future. 11581 * <p> 11582 * This must be called from a UI thread. To call from a non-UI thread, call 11583 * {@link #postInvalidate()}. 11584 * 11585 * @param l the left position of the dirty region 11586 * @param t the top position of the dirty region 11587 * @param r the right position of the dirty region 11588 * @param b the bottom position of the dirty region 11589 */ 11590 public void invalidate(int l, int t, int r, int b) { 11591 final int scrollX = mScrollX; 11592 final int scrollY = mScrollY; 11593 invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false); 11594 } 11595 11596 /** 11597 * Invalidate the whole view. If the view is visible, 11598 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 11599 * the future. 11600 * <p> 11601 * This must be called from a UI thread. To call from a non-UI thread, call 11602 * {@link #postInvalidate()}. 11603 */ 11604 public void invalidate() { 11605 invalidate(true); 11606 } 11607 11608 /** 11609 * This is where the invalidate() work actually happens. A full invalidate() 11610 * causes the drawing cache to be invalidated, but this function can be 11611 * called with invalidateCache set to false to skip that invalidation step 11612 * for cases that do not need it (for example, a component that remains at 11613 * the same dimensions with the same content). 11614 * 11615 * @param invalidateCache Whether the drawing cache for this view should be 11616 * invalidated as well. This is usually true for a full 11617 * invalidate, but may be set to false if the View's contents or 11618 * dimensions have not changed. 11619 */ 11620 void invalidate(boolean invalidateCache) { 11621 invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true); 11622 } 11623 11624 void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache, 11625 boolean fullInvalidate) { 11626 if (mGhostView != null) { 11627 mGhostView.invalidate(invalidateCache); 11628 return; 11629 } 11630 11631 if (skipInvalidate()) { 11632 return; 11633 } 11634 11635 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) 11636 || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) 11637 || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED 11638 || (fullInvalidate && isOpaque() != mLastIsOpaque)) { 11639 if (fullInvalidate) { 11640 mLastIsOpaque = isOpaque(); 11641 mPrivateFlags &= ~PFLAG_DRAWN; 11642 } 11643 11644 mPrivateFlags |= PFLAG_DIRTY; 11645 11646 if (invalidateCache) { 11647 mPrivateFlags |= PFLAG_INVALIDATED; 11648 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 11649 } 11650 11651 // Propagate the damage rectangle to the parent view. 11652 final AttachInfo ai = mAttachInfo; 11653 final ViewParent p = mParent; 11654 if (p != null && ai != null && l < r && t < b) { 11655 final Rect damage = ai.mTmpInvalRect; 11656 damage.set(l, t, r, b); 11657 p.invalidateChild(this, damage); 11658 } 11659 11660 // Damage the entire projection receiver, if necessary. 11661 if (mBackground != null && mBackground.isProjected()) { 11662 final View receiver = getProjectionReceiver(); 11663 if (receiver != null) { 11664 receiver.damageInParent(); 11665 } 11666 } 11667 11668 // Damage the entire IsolatedZVolume receiving this view's shadow. 11669 if (isHardwareAccelerated() && getZ() != 0) { 11670 damageShadowReceiver(); 11671 } 11672 } 11673 } 11674 11675 /** 11676 * @return this view's projection receiver, or {@code null} if none exists 11677 */ 11678 private View getProjectionReceiver() { 11679 ViewParent p = getParent(); 11680 while (p != null && p instanceof View) { 11681 final View v = (View) p; 11682 if (v.isProjectionReceiver()) { 11683 return v; 11684 } 11685 p = p.getParent(); 11686 } 11687 11688 return null; 11689 } 11690 11691 /** 11692 * @return whether the view is a projection receiver 11693 */ 11694 private boolean isProjectionReceiver() { 11695 return mBackground != null; 11696 } 11697 11698 /** 11699 * Damage area of the screen that can be covered by this View's shadow. 11700 * 11701 * This method will guarantee that any changes to shadows cast by a View 11702 * are damaged on the screen for future redraw. 11703 */ 11704 private void damageShadowReceiver() { 11705 final AttachInfo ai = mAttachInfo; 11706 if (ai != null) { 11707 ViewParent p = getParent(); 11708 if (p != null && p instanceof ViewGroup) { 11709 final ViewGroup vg = (ViewGroup) p; 11710 vg.damageInParent(); 11711 } 11712 } 11713 } 11714 11715 /** 11716 * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to 11717 * set any flags or handle all of the cases handled by the default invalidation methods. 11718 * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate 11719 * dirty rect. This method calls into fast invalidation methods in ViewGroup that 11720 * walk up the hierarchy, transforming the dirty rect as necessary. 11721 * 11722 * The method also handles normal invalidation logic if display list properties are not 11723 * being used in this view. The invalidateParent and forceRedraw flags are used by that 11724 * backup approach, to handle these cases used in the various property-setting methods. 11725 * 11726 * @param invalidateParent Force a call to invalidateParentCaches() if display list properties 11727 * are not being used in this view 11728 * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display 11729 * list properties are not being used in this view 11730 */ 11731 void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) { 11732 if (!isHardwareAccelerated() 11733 || !mRenderNode.isValid() 11734 || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) { 11735 if (invalidateParent) { 11736 invalidateParentCaches(); 11737 } 11738 if (forceRedraw) { 11739 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 11740 } 11741 invalidate(false); 11742 } else { 11743 damageInParent(); 11744 } 11745 if (isHardwareAccelerated() && invalidateParent && getZ() != 0) { 11746 damageShadowReceiver(); 11747 } 11748 } 11749 11750 /** 11751 * Tells the parent view to damage this view's bounds. 11752 * 11753 * @hide 11754 */ 11755 protected void damageInParent() { 11756 final AttachInfo ai = mAttachInfo; 11757 final ViewParent p = mParent; 11758 if (p != null && ai != null) { 11759 final Rect r = ai.mTmpInvalRect; 11760 r.set(0, 0, mRight - mLeft, mBottom - mTop); 11761 if (mParent instanceof ViewGroup) { 11762 ((ViewGroup) mParent).damageChild(this, r); 11763 } else { 11764 mParent.invalidateChild(this, r); 11765 } 11766 } 11767 } 11768 11769 /** 11770 * Utility method to transform a given Rect by the current matrix of this view. 11771 */ 11772 void transformRect(final Rect rect) { 11773 if (!getMatrix().isIdentity()) { 11774 RectF boundingRect = mAttachInfo.mTmpTransformRect; 11775 boundingRect.set(rect); 11776 getMatrix().mapRect(boundingRect); 11777 rect.set((int) Math.floor(boundingRect.left), 11778 (int) Math.floor(boundingRect.top), 11779 (int) Math.ceil(boundingRect.right), 11780 (int) Math.ceil(boundingRect.bottom)); 11781 } 11782 } 11783 11784 /** 11785 * Used to indicate that the parent of this view should clear its caches. This functionality 11786 * is used to force the parent to rebuild its display list (when hardware-accelerated), 11787 * which is necessary when various parent-managed properties of the view change, such as 11788 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 11789 * clears the parent caches and does not causes an invalidate event. 11790 * 11791 * @hide 11792 */ 11793 protected void invalidateParentCaches() { 11794 if (mParent instanceof View) { 11795 ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED; 11796 } 11797 } 11798 11799 /** 11800 * Used to indicate that the parent of this view should be invalidated. This functionality 11801 * is used to force the parent to rebuild its display list (when hardware-accelerated), 11802 * which is necessary when various parent-managed properties of the view change, such as 11803 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 11804 * an invalidation event to the parent. 11805 * 11806 * @hide 11807 */ 11808 protected void invalidateParentIfNeeded() { 11809 if (isHardwareAccelerated() && mParent instanceof View) { 11810 ((View) mParent).invalidate(true); 11811 } 11812 } 11813 11814 /** 11815 * @hide 11816 */ 11817 protected void invalidateParentIfNeededAndWasQuickRejected() { 11818 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) { 11819 // View was rejected last time it was drawn by its parent; this may have changed 11820 invalidateParentIfNeeded(); 11821 } 11822 } 11823 11824 /** 11825 * Indicates whether this View is opaque. An opaque View guarantees that it will 11826 * draw all the pixels overlapping its bounds using a fully opaque color. 11827 * 11828 * Subclasses of View should override this method whenever possible to indicate 11829 * whether an instance is opaque. Opaque Views are treated in a special way by 11830 * the View hierarchy, possibly allowing it to perform optimizations during 11831 * invalidate/draw passes. 11832 * 11833 * @return True if this View is guaranteed to be fully opaque, false otherwise. 11834 */ 11835 @ViewDebug.ExportedProperty(category = "drawing") 11836 public boolean isOpaque() { 11837 return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK && 11838 getFinalAlpha() >= 1.0f; 11839 } 11840 11841 /** 11842 * @hide 11843 */ 11844 protected void computeOpaqueFlags() { 11845 // Opaque if: 11846 // - Has a background 11847 // - Background is opaque 11848 // - Doesn't have scrollbars or scrollbars overlay 11849 11850 if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) { 11851 mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND; 11852 } else { 11853 mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND; 11854 } 11855 11856 final int flags = mViewFlags; 11857 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 11858 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY || 11859 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) { 11860 mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS; 11861 } else { 11862 mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS; 11863 } 11864 } 11865 11866 /** 11867 * @hide 11868 */ 11869 protected boolean hasOpaqueScrollbars() { 11870 return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS; 11871 } 11872 11873 /** 11874 * @return A handler associated with the thread running the View. This 11875 * handler can be used to pump events in the UI events queue. 11876 */ 11877 public Handler getHandler() { 11878 final AttachInfo attachInfo = mAttachInfo; 11879 if (attachInfo != null) { 11880 return attachInfo.mHandler; 11881 } 11882 return null; 11883 } 11884 11885 /** 11886 * Gets the view root associated with the View. 11887 * @return The view root, or null if none. 11888 * @hide 11889 */ 11890 public ViewRootImpl getViewRootImpl() { 11891 if (mAttachInfo != null) { 11892 return mAttachInfo.mViewRootImpl; 11893 } 11894 return null; 11895 } 11896 11897 /** 11898 * @hide 11899 */ 11900 public HardwareRenderer getHardwareRenderer() { 11901 return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null; 11902 } 11903 11904 /** 11905 * <p>Causes the Runnable to be added to the message queue. 11906 * The runnable will be run on the user interface thread.</p> 11907 * 11908 * @param action The Runnable that will be executed. 11909 * 11910 * @return Returns true if the Runnable was successfully placed in to the 11911 * message queue. Returns false on failure, usually because the 11912 * looper processing the message queue is exiting. 11913 * 11914 * @see #postDelayed 11915 * @see #removeCallbacks 11916 */ 11917 public boolean post(Runnable action) { 11918 final AttachInfo attachInfo = mAttachInfo; 11919 if (attachInfo != null) { 11920 return attachInfo.mHandler.post(action); 11921 } 11922 // Assume that post will succeed later 11923 ViewRootImpl.getRunQueue().post(action); 11924 return true; 11925 } 11926 11927 /** 11928 * <p>Causes the Runnable to be added to the message queue, to be run 11929 * after the specified amount of time elapses. 11930 * The runnable will be run on the user interface thread.</p> 11931 * 11932 * @param action The Runnable that will be executed. 11933 * @param delayMillis The delay (in milliseconds) until the Runnable 11934 * will be executed. 11935 * 11936 * @return true if the Runnable was successfully placed in to the 11937 * message queue. Returns false on failure, usually because the 11938 * looper processing the message queue is exiting. Note that a 11939 * result of true does not mean the Runnable will be processed -- 11940 * if the looper is quit before the delivery time of the message 11941 * occurs then the message will be dropped. 11942 * 11943 * @see #post 11944 * @see #removeCallbacks 11945 */ 11946 public boolean postDelayed(Runnable action, long delayMillis) { 11947 final AttachInfo attachInfo = mAttachInfo; 11948 if (attachInfo != null) { 11949 return attachInfo.mHandler.postDelayed(action, delayMillis); 11950 } 11951 // Assume that post will succeed later 11952 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 11953 return true; 11954 } 11955 11956 /** 11957 * <p>Causes the Runnable to execute on the next animation time step. 11958 * The runnable will be run on the user interface thread.</p> 11959 * 11960 * @param action The Runnable that will be executed. 11961 * 11962 * @see #postOnAnimationDelayed 11963 * @see #removeCallbacks 11964 */ 11965 public void postOnAnimation(Runnable action) { 11966 final AttachInfo attachInfo = mAttachInfo; 11967 if (attachInfo != null) { 11968 attachInfo.mViewRootImpl.mChoreographer.postCallback( 11969 Choreographer.CALLBACK_ANIMATION, action, null); 11970 } else { 11971 // Assume that post will succeed later 11972 ViewRootImpl.getRunQueue().post(action); 11973 } 11974 } 11975 11976 /** 11977 * <p>Causes the Runnable to execute on the next animation time step, 11978 * after the specified amount of time elapses. 11979 * The runnable will be run on the user interface thread.</p> 11980 * 11981 * @param action The Runnable that will be executed. 11982 * @param delayMillis The delay (in milliseconds) until the Runnable 11983 * will be executed. 11984 * 11985 * @see #postOnAnimation 11986 * @see #removeCallbacks 11987 */ 11988 public void postOnAnimationDelayed(Runnable action, long delayMillis) { 11989 final AttachInfo attachInfo = mAttachInfo; 11990 if (attachInfo != null) { 11991 attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 11992 Choreographer.CALLBACK_ANIMATION, action, null, delayMillis); 11993 } else { 11994 // Assume that post will succeed later 11995 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 11996 } 11997 } 11998 11999 /** 12000 * <p>Removes the specified Runnable from the message queue.</p> 12001 * 12002 * @param action The Runnable to remove from the message handling queue 12003 * 12004 * @return true if this view could ask the Handler to remove the Runnable, 12005 * false otherwise. When the returned value is true, the Runnable 12006 * may or may not have been actually removed from the message queue 12007 * (for instance, if the Runnable was not in the queue already.) 12008 * 12009 * @see #post 12010 * @see #postDelayed 12011 * @see #postOnAnimation 12012 * @see #postOnAnimationDelayed 12013 */ 12014 public boolean removeCallbacks(Runnable action) { 12015 if (action != null) { 12016 final AttachInfo attachInfo = mAttachInfo; 12017 if (attachInfo != null) { 12018 attachInfo.mHandler.removeCallbacks(action); 12019 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 12020 Choreographer.CALLBACK_ANIMATION, action, null); 12021 } 12022 // Assume that post will succeed later 12023 ViewRootImpl.getRunQueue().removeCallbacks(action); 12024 } 12025 return true; 12026 } 12027 12028 /** 12029 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 12030 * Use this to invalidate the View from a non-UI thread.</p> 12031 * 12032 * <p>This method can be invoked from outside of the UI thread 12033 * only when this View is attached to a window.</p> 12034 * 12035 * @see #invalidate() 12036 * @see #postInvalidateDelayed(long) 12037 */ 12038 public void postInvalidate() { 12039 postInvalidateDelayed(0); 12040 } 12041 12042 /** 12043 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 12044 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 12045 * 12046 * <p>This method can be invoked from outside of the UI thread 12047 * only when this View is attached to a window.</p> 12048 * 12049 * @param left The left coordinate of the rectangle to invalidate. 12050 * @param top The top coordinate of the rectangle to invalidate. 12051 * @param right The right coordinate of the rectangle to invalidate. 12052 * @param bottom The bottom coordinate of the rectangle to invalidate. 12053 * 12054 * @see #invalidate(int, int, int, int) 12055 * @see #invalidate(Rect) 12056 * @see #postInvalidateDelayed(long, int, int, int, int) 12057 */ 12058 public void postInvalidate(int left, int top, int right, int bottom) { 12059 postInvalidateDelayed(0, left, top, right, bottom); 12060 } 12061 12062 /** 12063 * <p>Cause an invalidate to happen on a subsequent cycle through the event 12064 * loop. Waits for the specified amount of time.</p> 12065 * 12066 * <p>This method can be invoked from outside of the UI thread 12067 * only when this View is attached to a window.</p> 12068 * 12069 * @param delayMilliseconds the duration in milliseconds to delay the 12070 * invalidation by 12071 * 12072 * @see #invalidate() 12073 * @see #postInvalidate() 12074 */ 12075 public void postInvalidateDelayed(long delayMilliseconds) { 12076 // We try only with the AttachInfo because there's no point in invalidating 12077 // if we are not attached to our window 12078 final AttachInfo attachInfo = mAttachInfo; 12079 if (attachInfo != null) { 12080 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); 12081 } 12082 } 12083 12084 /** 12085 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 12086 * through the event loop. Waits for the specified amount of time.</p> 12087 * 12088 * <p>This method can be invoked from outside of the UI thread 12089 * only when this View is attached to a window.</p> 12090 * 12091 * @param delayMilliseconds the duration in milliseconds to delay the 12092 * invalidation by 12093 * @param left The left coordinate of the rectangle to invalidate. 12094 * @param top The top coordinate of the rectangle to invalidate. 12095 * @param right The right coordinate of the rectangle to invalidate. 12096 * @param bottom The bottom coordinate of the rectangle to invalidate. 12097 * 12098 * @see #invalidate(int, int, int, int) 12099 * @see #invalidate(Rect) 12100 * @see #postInvalidate(int, int, int, int) 12101 */ 12102 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 12103 int right, int bottom) { 12104 12105 // We try only with the AttachInfo because there's no point in invalidating 12106 // if we are not attached to our window 12107 final AttachInfo attachInfo = mAttachInfo; 12108 if (attachInfo != null) { 12109 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 12110 info.target = this; 12111 info.left = left; 12112 info.top = top; 12113 info.right = right; 12114 info.bottom = bottom; 12115 12116 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); 12117 } 12118 } 12119 12120 /** 12121 * <p>Cause an invalidate to happen on the next animation time step, typically the 12122 * next display frame.</p> 12123 * 12124 * <p>This method can be invoked from outside of the UI thread 12125 * only when this View is attached to a window.</p> 12126 * 12127 * @see #invalidate() 12128 */ 12129 public void postInvalidateOnAnimation() { 12130 // We try only with the AttachInfo because there's no point in invalidating 12131 // if we are not attached to our window 12132 final AttachInfo attachInfo = mAttachInfo; 12133 if (attachInfo != null) { 12134 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); 12135 } 12136 } 12137 12138 /** 12139 * <p>Cause an invalidate of the specified area to happen on the next animation 12140 * time step, typically the next display frame.</p> 12141 * 12142 * <p>This method can be invoked from outside of the UI thread 12143 * only when this View is attached to a window.</p> 12144 * 12145 * @param left The left coordinate of the rectangle to invalidate. 12146 * @param top The top coordinate of the rectangle to invalidate. 12147 * @param right The right coordinate of the rectangle to invalidate. 12148 * @param bottom The bottom coordinate of the rectangle to invalidate. 12149 * 12150 * @see #invalidate(int, int, int, int) 12151 * @see #invalidate(Rect) 12152 */ 12153 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { 12154 // We try only with the AttachInfo because there's no point in invalidating 12155 // if we are not attached to our window 12156 final AttachInfo attachInfo = mAttachInfo; 12157 if (attachInfo != null) { 12158 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 12159 info.target = this; 12160 info.left = left; 12161 info.top = top; 12162 info.right = right; 12163 info.bottom = bottom; 12164 12165 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); 12166 } 12167 } 12168 12169 /** 12170 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 12171 * This event is sent at most once every 12172 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 12173 */ 12174 private void postSendViewScrolledAccessibilityEventCallback() { 12175 if (mSendViewScrolledAccessibilityEvent == null) { 12176 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 12177 } 12178 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 12179 mSendViewScrolledAccessibilityEvent.mIsPending = true; 12180 postDelayed(mSendViewScrolledAccessibilityEvent, 12181 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 12182 } 12183 } 12184 12185 /** 12186 * Called by a parent to request that a child update its values for mScrollX 12187 * and mScrollY if necessary. This will typically be done if the child is 12188 * animating a scroll using a {@link android.widget.Scroller Scroller} 12189 * object. 12190 */ 12191 public void computeScroll() { 12192 } 12193 12194 /** 12195 * <p>Indicate whether the horizontal edges are faded when the view is 12196 * scrolled horizontally.</p> 12197 * 12198 * @return true if the horizontal edges should are faded on scroll, false 12199 * otherwise 12200 * 12201 * @see #setHorizontalFadingEdgeEnabled(boolean) 12202 * 12203 * @attr ref android.R.styleable#View_requiresFadingEdge 12204 */ 12205 public boolean isHorizontalFadingEdgeEnabled() { 12206 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 12207 } 12208 12209 /** 12210 * <p>Define whether the horizontal edges should be faded when this view 12211 * is scrolled horizontally.</p> 12212 * 12213 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 12214 * be faded when the view is scrolled 12215 * horizontally 12216 * 12217 * @see #isHorizontalFadingEdgeEnabled() 12218 * 12219 * @attr ref android.R.styleable#View_requiresFadingEdge 12220 */ 12221 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 12222 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 12223 if (horizontalFadingEdgeEnabled) { 12224 initScrollCache(); 12225 } 12226 12227 mViewFlags ^= FADING_EDGE_HORIZONTAL; 12228 } 12229 } 12230 12231 /** 12232 * <p>Indicate whether the vertical edges are faded when the view is 12233 * scrolled horizontally.</p> 12234 * 12235 * @return true if the vertical edges should are faded on scroll, false 12236 * otherwise 12237 * 12238 * @see #setVerticalFadingEdgeEnabled(boolean) 12239 * 12240 * @attr ref android.R.styleable#View_requiresFadingEdge 12241 */ 12242 public boolean isVerticalFadingEdgeEnabled() { 12243 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 12244 } 12245 12246 /** 12247 * <p>Define whether the vertical edges should be faded when this view 12248 * is scrolled vertically.</p> 12249 * 12250 * @param verticalFadingEdgeEnabled true if the vertical edges should 12251 * be faded when the view is scrolled 12252 * vertically 12253 * 12254 * @see #isVerticalFadingEdgeEnabled() 12255 * 12256 * @attr ref android.R.styleable#View_requiresFadingEdge 12257 */ 12258 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 12259 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 12260 if (verticalFadingEdgeEnabled) { 12261 initScrollCache(); 12262 } 12263 12264 mViewFlags ^= FADING_EDGE_VERTICAL; 12265 } 12266 } 12267 12268 /** 12269 * Returns the strength, or intensity, of the top faded edge. The strength is 12270 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12271 * returns 0.0 or 1.0 but no value in between. 12272 * 12273 * Subclasses should override this method to provide a smoother fade transition 12274 * when scrolling occurs. 12275 * 12276 * @return the intensity of the top fade as a float between 0.0f and 1.0f 12277 */ 12278 protected float getTopFadingEdgeStrength() { 12279 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 12280 } 12281 12282 /** 12283 * Returns the strength, or intensity, of the bottom faded edge. The strength is 12284 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12285 * returns 0.0 or 1.0 but no value in between. 12286 * 12287 * Subclasses should override this method to provide a smoother fade transition 12288 * when scrolling occurs. 12289 * 12290 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 12291 */ 12292 protected float getBottomFadingEdgeStrength() { 12293 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 12294 computeVerticalScrollRange() ? 1.0f : 0.0f; 12295 } 12296 12297 /** 12298 * Returns the strength, or intensity, of the left faded edge. The strength is 12299 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12300 * returns 0.0 or 1.0 but no value in between. 12301 * 12302 * Subclasses should override this method to provide a smoother fade transition 12303 * when scrolling occurs. 12304 * 12305 * @return the intensity of the left fade as a float between 0.0f and 1.0f 12306 */ 12307 protected float getLeftFadingEdgeStrength() { 12308 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 12309 } 12310 12311 /** 12312 * Returns the strength, or intensity, of the right faded edge. The strength is 12313 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12314 * returns 0.0 or 1.0 but no value in between. 12315 * 12316 * Subclasses should override this method to provide a smoother fade transition 12317 * when scrolling occurs. 12318 * 12319 * @return the intensity of the right fade as a float between 0.0f and 1.0f 12320 */ 12321 protected float getRightFadingEdgeStrength() { 12322 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 12323 computeHorizontalScrollRange() ? 1.0f : 0.0f; 12324 } 12325 12326 /** 12327 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 12328 * scrollbar is not drawn by default.</p> 12329 * 12330 * @return true if the horizontal scrollbar should be painted, false 12331 * otherwise 12332 * 12333 * @see #setHorizontalScrollBarEnabled(boolean) 12334 */ 12335 public boolean isHorizontalScrollBarEnabled() { 12336 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 12337 } 12338 12339 /** 12340 * <p>Define whether the horizontal scrollbar should be drawn or not. The 12341 * scrollbar is not drawn by default.</p> 12342 * 12343 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 12344 * be painted 12345 * 12346 * @see #isHorizontalScrollBarEnabled() 12347 */ 12348 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 12349 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 12350 mViewFlags ^= SCROLLBARS_HORIZONTAL; 12351 computeOpaqueFlags(); 12352 resolvePadding(); 12353 } 12354 } 12355 12356 /** 12357 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 12358 * scrollbar is not drawn by default.</p> 12359 * 12360 * @return true if the vertical scrollbar should be painted, false 12361 * otherwise 12362 * 12363 * @see #setVerticalScrollBarEnabled(boolean) 12364 */ 12365 public boolean isVerticalScrollBarEnabled() { 12366 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 12367 } 12368 12369 /** 12370 * <p>Define whether the vertical scrollbar should be drawn or not. The 12371 * scrollbar is not drawn by default.</p> 12372 * 12373 * @param verticalScrollBarEnabled true if the vertical scrollbar should 12374 * be painted 12375 * 12376 * @see #isVerticalScrollBarEnabled() 12377 */ 12378 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 12379 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 12380 mViewFlags ^= SCROLLBARS_VERTICAL; 12381 computeOpaqueFlags(); 12382 resolvePadding(); 12383 } 12384 } 12385 12386 /** 12387 * @hide 12388 */ 12389 protected void recomputePadding() { 12390 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 12391 } 12392 12393 /** 12394 * Define whether scrollbars will fade when the view is not scrolling. 12395 * 12396 * @param fadeScrollbars wheter to enable fading 12397 * 12398 * @attr ref android.R.styleable#View_fadeScrollbars 12399 */ 12400 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 12401 initScrollCache(); 12402 final ScrollabilityCache scrollabilityCache = mScrollCache; 12403 scrollabilityCache.fadeScrollBars = fadeScrollbars; 12404 if (fadeScrollbars) { 12405 scrollabilityCache.state = ScrollabilityCache.OFF; 12406 } else { 12407 scrollabilityCache.state = ScrollabilityCache.ON; 12408 } 12409 } 12410 12411 /** 12412 * 12413 * Returns true if scrollbars will fade when this view is not scrolling 12414 * 12415 * @return true if scrollbar fading is enabled 12416 * 12417 * @attr ref android.R.styleable#View_fadeScrollbars 12418 */ 12419 public boolean isScrollbarFadingEnabled() { 12420 return mScrollCache != null && mScrollCache.fadeScrollBars; 12421 } 12422 12423 /** 12424 * 12425 * Returns the delay before scrollbars fade. 12426 * 12427 * @return the delay before scrollbars fade 12428 * 12429 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 12430 */ 12431 public int getScrollBarDefaultDelayBeforeFade() { 12432 return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() : 12433 mScrollCache.scrollBarDefaultDelayBeforeFade; 12434 } 12435 12436 /** 12437 * Define the delay before scrollbars fade. 12438 * 12439 * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade 12440 * 12441 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 12442 */ 12443 public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) { 12444 getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade; 12445 } 12446 12447 /** 12448 * 12449 * Returns the scrollbar fade duration. 12450 * 12451 * @return the scrollbar fade duration 12452 * 12453 * @attr ref android.R.styleable#View_scrollbarFadeDuration 12454 */ 12455 public int getScrollBarFadeDuration() { 12456 return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() : 12457 mScrollCache.scrollBarFadeDuration; 12458 } 12459 12460 /** 12461 * Define the scrollbar fade duration. 12462 * 12463 * @param scrollBarFadeDuration - the scrollbar fade duration 12464 * 12465 * @attr ref android.R.styleable#View_scrollbarFadeDuration 12466 */ 12467 public void setScrollBarFadeDuration(int scrollBarFadeDuration) { 12468 getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration; 12469 } 12470 12471 /** 12472 * 12473 * Returns the scrollbar size. 12474 * 12475 * @return the scrollbar size 12476 * 12477 * @attr ref android.R.styleable#View_scrollbarSize 12478 */ 12479 public int getScrollBarSize() { 12480 return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() : 12481 mScrollCache.scrollBarSize; 12482 } 12483 12484 /** 12485 * Define the scrollbar size. 12486 * 12487 * @param scrollBarSize - the scrollbar size 12488 * 12489 * @attr ref android.R.styleable#View_scrollbarSize 12490 */ 12491 public void setScrollBarSize(int scrollBarSize) { 12492 getScrollCache().scrollBarSize = scrollBarSize; 12493 } 12494 12495 /** 12496 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 12497 * inset. When inset, they add to the padding of the view. And the scrollbars 12498 * can be drawn inside the padding area or on the edge of the view. For example, 12499 * if a view has a background drawable and you want to draw the scrollbars 12500 * inside the padding specified by the drawable, you can use 12501 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 12502 * appear at the edge of the view, ignoring the padding, then you can use 12503 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 12504 * @param style the style of the scrollbars. Should be one of 12505 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 12506 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 12507 * @see #SCROLLBARS_INSIDE_OVERLAY 12508 * @see #SCROLLBARS_INSIDE_INSET 12509 * @see #SCROLLBARS_OUTSIDE_OVERLAY 12510 * @see #SCROLLBARS_OUTSIDE_INSET 12511 * 12512 * @attr ref android.R.styleable#View_scrollbarStyle 12513 */ 12514 public void setScrollBarStyle(@ScrollBarStyle int style) { 12515 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 12516 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 12517 computeOpaqueFlags(); 12518 resolvePadding(); 12519 } 12520 } 12521 12522 /** 12523 * <p>Returns the current scrollbar style.</p> 12524 * @return the current scrollbar style 12525 * @see #SCROLLBARS_INSIDE_OVERLAY 12526 * @see #SCROLLBARS_INSIDE_INSET 12527 * @see #SCROLLBARS_OUTSIDE_OVERLAY 12528 * @see #SCROLLBARS_OUTSIDE_INSET 12529 * 12530 * @attr ref android.R.styleable#View_scrollbarStyle 12531 */ 12532 @ViewDebug.ExportedProperty(mapping = { 12533 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 12534 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 12535 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 12536 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 12537 }) 12538 @ScrollBarStyle 12539 public int getScrollBarStyle() { 12540 return mViewFlags & SCROLLBARS_STYLE_MASK; 12541 } 12542 12543 /** 12544 * <p>Compute the horizontal range that the horizontal scrollbar 12545 * represents.</p> 12546 * 12547 * <p>The range is expressed in arbitrary units that must be the same as the 12548 * units used by {@link #computeHorizontalScrollExtent()} and 12549 * {@link #computeHorizontalScrollOffset()}.</p> 12550 * 12551 * <p>The default range is the drawing width of this view.</p> 12552 * 12553 * @return the total horizontal range represented by the horizontal 12554 * scrollbar 12555 * 12556 * @see #computeHorizontalScrollExtent() 12557 * @see #computeHorizontalScrollOffset() 12558 * @see android.widget.ScrollBarDrawable 12559 */ 12560 protected int computeHorizontalScrollRange() { 12561 return getWidth(); 12562 } 12563 12564 /** 12565 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 12566 * within the horizontal range. This value is used to compute the position 12567 * of the thumb within the scrollbar's track.</p> 12568 * 12569 * <p>The range is expressed in arbitrary units that must be the same as the 12570 * units used by {@link #computeHorizontalScrollRange()} and 12571 * {@link #computeHorizontalScrollExtent()}.</p> 12572 * 12573 * <p>The default offset is the scroll offset of this view.</p> 12574 * 12575 * @return the horizontal offset of the scrollbar's thumb 12576 * 12577 * @see #computeHorizontalScrollRange() 12578 * @see #computeHorizontalScrollExtent() 12579 * @see android.widget.ScrollBarDrawable 12580 */ 12581 protected int computeHorizontalScrollOffset() { 12582 return mScrollX; 12583 } 12584 12585 /** 12586 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 12587 * within the horizontal range. This value is used to compute the length 12588 * of the thumb within the scrollbar's track.</p> 12589 * 12590 * <p>The range is expressed in arbitrary units that must be the same as the 12591 * units used by {@link #computeHorizontalScrollRange()} and 12592 * {@link #computeHorizontalScrollOffset()}.</p> 12593 * 12594 * <p>The default extent is the drawing width of this view.</p> 12595 * 12596 * @return the horizontal extent of the scrollbar's thumb 12597 * 12598 * @see #computeHorizontalScrollRange() 12599 * @see #computeHorizontalScrollOffset() 12600 * @see android.widget.ScrollBarDrawable 12601 */ 12602 protected int computeHorizontalScrollExtent() { 12603 return getWidth(); 12604 } 12605 12606 /** 12607 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 12608 * 12609 * <p>The range is expressed in arbitrary units that must be the same as the 12610 * units used by {@link #computeVerticalScrollExtent()} and 12611 * {@link #computeVerticalScrollOffset()}.</p> 12612 * 12613 * @return the total vertical range represented by the vertical scrollbar 12614 * 12615 * <p>The default range is the drawing height of this view.</p> 12616 * 12617 * @see #computeVerticalScrollExtent() 12618 * @see #computeVerticalScrollOffset() 12619 * @see android.widget.ScrollBarDrawable 12620 */ 12621 protected int computeVerticalScrollRange() { 12622 return getHeight(); 12623 } 12624 12625 /** 12626 * <p>Compute the vertical offset of the vertical scrollbar's thumb 12627 * within the horizontal range. This value is used to compute the position 12628 * of the thumb within the scrollbar's track.</p> 12629 * 12630 * <p>The range is expressed in arbitrary units that must be the same as the 12631 * units used by {@link #computeVerticalScrollRange()} and 12632 * {@link #computeVerticalScrollExtent()}.</p> 12633 * 12634 * <p>The default offset is the scroll offset of this view.</p> 12635 * 12636 * @return the vertical offset of the scrollbar's thumb 12637 * 12638 * @see #computeVerticalScrollRange() 12639 * @see #computeVerticalScrollExtent() 12640 * @see android.widget.ScrollBarDrawable 12641 */ 12642 protected int computeVerticalScrollOffset() { 12643 return mScrollY; 12644 } 12645 12646 /** 12647 * <p>Compute the vertical extent of the vertical scrollbar's thumb 12648 * within the vertical range. This value is used to compute the length 12649 * of the thumb within the scrollbar's track.</p> 12650 * 12651 * <p>The range is expressed in arbitrary units that must be the same as the 12652 * units used by {@link #computeVerticalScrollRange()} and 12653 * {@link #computeVerticalScrollOffset()}.</p> 12654 * 12655 * <p>The default extent is the drawing height of this view.</p> 12656 * 12657 * @return the vertical extent of the scrollbar's thumb 12658 * 12659 * @see #computeVerticalScrollRange() 12660 * @see #computeVerticalScrollOffset() 12661 * @see android.widget.ScrollBarDrawable 12662 */ 12663 protected int computeVerticalScrollExtent() { 12664 return getHeight(); 12665 } 12666 12667 /** 12668 * Check if this view can be scrolled horizontally in a certain direction. 12669 * 12670 * @param direction Negative to check scrolling left, positive to check scrolling right. 12671 * @return true if this view can be scrolled in the specified direction, false otherwise. 12672 */ 12673 public boolean canScrollHorizontally(int direction) { 12674 final int offset = computeHorizontalScrollOffset(); 12675 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 12676 if (range == 0) return false; 12677 if (direction < 0) { 12678 return offset > 0; 12679 } else { 12680 return offset < range - 1; 12681 } 12682 } 12683 12684 /** 12685 * Check if this view can be scrolled vertically in a certain direction. 12686 * 12687 * @param direction Negative to check scrolling up, positive to check scrolling down. 12688 * @return true if this view can be scrolled in the specified direction, false otherwise. 12689 */ 12690 public boolean canScrollVertically(int direction) { 12691 final int offset = computeVerticalScrollOffset(); 12692 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 12693 if (range == 0) return false; 12694 if (direction < 0) { 12695 return offset > 0; 12696 } else { 12697 return offset < range - 1; 12698 } 12699 } 12700 12701 /** 12702 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 12703 * scrollbars are painted only if they have been awakened first.</p> 12704 * 12705 * @param canvas the canvas on which to draw the scrollbars 12706 * 12707 * @see #awakenScrollBars(int) 12708 */ 12709 protected final void onDrawScrollBars(Canvas canvas) { 12710 // scrollbars are drawn only when the animation is running 12711 final ScrollabilityCache cache = mScrollCache; 12712 if (cache != null) { 12713 12714 int state = cache.state; 12715 12716 if (state == ScrollabilityCache.OFF) { 12717 return; 12718 } 12719 12720 boolean invalidate = false; 12721 12722 if (state == ScrollabilityCache.FADING) { 12723 // We're fading -- get our fade interpolation 12724 if (cache.interpolatorValues == null) { 12725 cache.interpolatorValues = new float[1]; 12726 } 12727 12728 float[] values = cache.interpolatorValues; 12729 12730 // Stops the animation if we're done 12731 if (cache.scrollBarInterpolator.timeToValues(values) == 12732 Interpolator.Result.FREEZE_END) { 12733 cache.state = ScrollabilityCache.OFF; 12734 } else { 12735 cache.scrollBar.setAlpha(Math.round(values[0])); 12736 } 12737 12738 // This will make the scroll bars inval themselves after 12739 // drawing. We only want this when we're fading so that 12740 // we prevent excessive redraws 12741 invalidate = true; 12742 } else { 12743 // We're just on -- but we may have been fading before so 12744 // reset alpha 12745 cache.scrollBar.setAlpha(255); 12746 } 12747 12748 12749 final int viewFlags = mViewFlags; 12750 12751 final boolean drawHorizontalScrollBar = 12752 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 12753 final boolean drawVerticalScrollBar = 12754 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 12755 && !isVerticalScrollBarHidden(); 12756 12757 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 12758 final int width = mRight - mLeft; 12759 final int height = mBottom - mTop; 12760 12761 final ScrollBarDrawable scrollBar = cache.scrollBar; 12762 12763 final int scrollX = mScrollX; 12764 final int scrollY = mScrollY; 12765 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 12766 12767 int left; 12768 int top; 12769 int right; 12770 int bottom; 12771 12772 if (drawHorizontalScrollBar) { 12773 int size = scrollBar.getSize(false); 12774 if (size <= 0) { 12775 size = cache.scrollBarSize; 12776 } 12777 12778 scrollBar.setParameters(computeHorizontalScrollRange(), 12779 computeHorizontalScrollOffset(), 12780 computeHorizontalScrollExtent(), false); 12781 final int verticalScrollBarGap = drawVerticalScrollBar ? 12782 getVerticalScrollbarWidth() : 0; 12783 top = scrollY + height - size - (mUserPaddingBottom & inside); 12784 left = scrollX + (mPaddingLeft & inside); 12785 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 12786 bottom = top + size; 12787 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 12788 if (invalidate) { 12789 invalidate(left, top, right, bottom); 12790 } 12791 } 12792 12793 if (drawVerticalScrollBar) { 12794 int size = scrollBar.getSize(true); 12795 if (size <= 0) { 12796 size = cache.scrollBarSize; 12797 } 12798 12799 scrollBar.setParameters(computeVerticalScrollRange(), 12800 computeVerticalScrollOffset(), 12801 computeVerticalScrollExtent(), true); 12802 int verticalScrollbarPosition = mVerticalScrollbarPosition; 12803 if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) { 12804 verticalScrollbarPosition = isLayoutRtl() ? 12805 SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT; 12806 } 12807 switch (verticalScrollbarPosition) { 12808 default: 12809 case SCROLLBAR_POSITION_RIGHT: 12810 left = scrollX + width - size - (mUserPaddingRight & inside); 12811 break; 12812 case SCROLLBAR_POSITION_LEFT: 12813 left = scrollX + (mUserPaddingLeft & inside); 12814 break; 12815 } 12816 top = scrollY + (mPaddingTop & inside); 12817 right = left + size; 12818 bottom = scrollY + height - (mUserPaddingBottom & inside); 12819 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 12820 if (invalidate) { 12821 invalidate(left, top, right, bottom); 12822 } 12823 } 12824 } 12825 } 12826 } 12827 12828 /** 12829 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 12830 * FastScroller is visible. 12831 * @return whether to temporarily hide the vertical scrollbar 12832 * @hide 12833 */ 12834 protected boolean isVerticalScrollBarHidden() { 12835 return false; 12836 } 12837 12838 /** 12839 * <p>Draw the horizontal scrollbar if 12840 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 12841 * 12842 * @param canvas the canvas on which to draw the scrollbar 12843 * @param scrollBar the scrollbar's drawable 12844 * 12845 * @see #isHorizontalScrollBarEnabled() 12846 * @see #computeHorizontalScrollRange() 12847 * @see #computeHorizontalScrollExtent() 12848 * @see #computeHorizontalScrollOffset() 12849 * @see android.widget.ScrollBarDrawable 12850 * @hide 12851 */ 12852 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 12853 int l, int t, int r, int b) { 12854 scrollBar.setBounds(l, t, r, b); 12855 scrollBar.draw(canvas); 12856 } 12857 12858 /** 12859 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 12860 * returns true.</p> 12861 * 12862 * @param canvas the canvas on which to draw the scrollbar 12863 * @param scrollBar the scrollbar's drawable 12864 * 12865 * @see #isVerticalScrollBarEnabled() 12866 * @see #computeVerticalScrollRange() 12867 * @see #computeVerticalScrollExtent() 12868 * @see #computeVerticalScrollOffset() 12869 * @see android.widget.ScrollBarDrawable 12870 * @hide 12871 */ 12872 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 12873 int l, int t, int r, int b) { 12874 scrollBar.setBounds(l, t, r, b); 12875 scrollBar.draw(canvas); 12876 } 12877 12878 /** 12879 * Implement this to do your drawing. 12880 * 12881 * @param canvas the canvas on which the background will be drawn 12882 */ 12883 protected void onDraw(Canvas canvas) { 12884 } 12885 12886 /* 12887 * Caller is responsible for calling requestLayout if necessary. 12888 * (This allows addViewInLayout to not request a new layout.) 12889 */ 12890 void assignParent(ViewParent parent) { 12891 if (mParent == null) { 12892 mParent = parent; 12893 } else if (parent == null) { 12894 mParent = null; 12895 } else { 12896 throw new RuntimeException("view " + this + " being added, but" 12897 + " it already has a parent"); 12898 } 12899 } 12900 12901 /** 12902 * This is called when the view is attached to a window. At this point it 12903 * has a Surface and will start drawing. Note that this function is 12904 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 12905 * however it may be called any time before the first onDraw -- including 12906 * before or after {@link #onMeasure(int, int)}. 12907 * 12908 * @see #onDetachedFromWindow() 12909 */ 12910 protected void onAttachedToWindow() { 12911 if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 12912 mParent.requestTransparentRegion(this); 12913 } 12914 12915 if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { 12916 initialAwakenScrollBars(); 12917 mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 12918 } 12919 12920 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 12921 12922 jumpDrawablesToCurrentState(); 12923 12924 resetSubtreeAccessibilityStateChanged(); 12925 12926 invalidateOutline(); 12927 12928 if (isFocused()) { 12929 InputMethodManager imm = InputMethodManager.peekInstance(); 12930 imm.focusIn(this); 12931 } 12932 } 12933 12934 /** 12935 * Resolve all RTL related properties. 12936 * 12937 * @return true if resolution of RTL properties has been done 12938 * 12939 * @hide 12940 */ 12941 public boolean resolveRtlPropertiesIfNeeded() { 12942 if (!needRtlPropertiesResolution()) return false; 12943 12944 // Order is important here: LayoutDirection MUST be resolved first 12945 if (!isLayoutDirectionResolved()) { 12946 resolveLayoutDirection(); 12947 resolveLayoutParams(); 12948 } 12949 // ... then we can resolve the others properties depending on the resolved LayoutDirection. 12950 if (!isTextDirectionResolved()) { 12951 resolveTextDirection(); 12952 } 12953 if (!isTextAlignmentResolved()) { 12954 resolveTextAlignment(); 12955 } 12956 // Should resolve Drawables before Padding because we need the layout direction of the 12957 // Drawable to correctly resolve Padding. 12958 if (!isDrawablesResolved()) { 12959 resolveDrawables(); 12960 } 12961 if (!isPaddingResolved()) { 12962 resolvePadding(); 12963 } 12964 onRtlPropertiesChanged(getLayoutDirection()); 12965 return true; 12966 } 12967 12968 /** 12969 * Reset resolution of all RTL related properties. 12970 * 12971 * @hide 12972 */ 12973 public void resetRtlProperties() { 12974 resetResolvedLayoutDirection(); 12975 resetResolvedTextDirection(); 12976 resetResolvedTextAlignment(); 12977 resetResolvedPadding(); 12978 resetResolvedDrawables(); 12979 } 12980 12981 /** 12982 * @see #onScreenStateChanged(int) 12983 */ 12984 void dispatchScreenStateChanged(int screenState) { 12985 onScreenStateChanged(screenState); 12986 } 12987 12988 /** 12989 * This method is called whenever the state of the screen this view is 12990 * attached to changes. A state change will usually occurs when the screen 12991 * turns on or off (whether it happens automatically or the user does it 12992 * manually.) 12993 * 12994 * @param screenState The new state of the screen. Can be either 12995 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF} 12996 */ 12997 public void onScreenStateChanged(int screenState) { 12998 } 12999 13000 /** 13001 * Return true if the application tag in the AndroidManifest has set "supportRtl" to true 13002 */ 13003 private boolean hasRtlSupport() { 13004 return mContext.getApplicationInfo().hasRtlSupport(); 13005 } 13006 13007 /** 13008 * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or 13009 * RTL not supported) 13010 */ 13011 private boolean isRtlCompatibilityMode() { 13012 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 13013 return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport(); 13014 } 13015 13016 /** 13017 * @return true if RTL properties need resolution. 13018 * 13019 */ 13020 private boolean needRtlPropertiesResolution() { 13021 return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED; 13022 } 13023 13024 /** 13025 * Called when any RTL property (layout direction or text direction or text alignment) has 13026 * been changed. 13027 * 13028 * Subclasses need to override this method to take care of cached information that depends on the 13029 * resolved layout direction, or to inform child views that inherit their layout direction. 13030 * 13031 * The default implementation does nothing. 13032 * 13033 * @param layoutDirection the direction of the layout 13034 * 13035 * @see #LAYOUT_DIRECTION_LTR 13036 * @see #LAYOUT_DIRECTION_RTL 13037 */ 13038 public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) { 13039 } 13040 13041 /** 13042 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 13043 * that the parent directionality can and will be resolved before its children. 13044 * 13045 * @return true if resolution has been done, false otherwise. 13046 * 13047 * @hide 13048 */ 13049 public boolean resolveLayoutDirection() { 13050 // Clear any previous layout direction resolution 13051 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 13052 13053 if (hasRtlSupport()) { 13054 // Set resolved depending on layout direction 13055 switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> 13056 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) { 13057 case LAYOUT_DIRECTION_INHERIT: 13058 // We cannot resolve yet. LTR is by default and let the resolution happen again 13059 // later to get the correct resolved value 13060 if (!canResolveLayoutDirection()) return false; 13061 13062 // Parent has not yet resolved, LTR is still the default 13063 try { 13064 if (!mParent.isLayoutDirectionResolved()) return false; 13065 13066 if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 13067 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 13068 } 13069 } catch (AbstractMethodError e) { 13070 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 13071 " does not fully implement ViewParent", e); 13072 } 13073 break; 13074 case LAYOUT_DIRECTION_RTL: 13075 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 13076 break; 13077 case LAYOUT_DIRECTION_LOCALE: 13078 if((LAYOUT_DIRECTION_RTL == 13079 TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) { 13080 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 13081 } 13082 break; 13083 default: 13084 // Nothing to do, LTR by default 13085 } 13086 } 13087 13088 // Set to resolved 13089 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 13090 return true; 13091 } 13092 13093 /** 13094 * Check if layout direction resolution can be done. 13095 * 13096 * @return true if layout direction resolution can be done otherwise return false. 13097 */ 13098 public boolean canResolveLayoutDirection() { 13099 switch (getRawLayoutDirection()) { 13100 case LAYOUT_DIRECTION_INHERIT: 13101 if (mParent != null) { 13102 try { 13103 return mParent.canResolveLayoutDirection(); 13104 } catch (AbstractMethodError e) { 13105 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 13106 " does not fully implement ViewParent", e); 13107 } 13108 } 13109 return false; 13110 13111 default: 13112 return true; 13113 } 13114 } 13115 13116 /** 13117 * Reset the resolved layout direction. Layout direction will be resolved during a call to 13118 * {@link #onMeasure(int, int)}. 13119 * 13120 * @hide 13121 */ 13122 public void resetResolvedLayoutDirection() { 13123 // Reset the current resolved bits 13124 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 13125 } 13126 13127 /** 13128 * @return true if the layout direction is inherited. 13129 * 13130 * @hide 13131 */ 13132 public boolean isLayoutDirectionInherited() { 13133 return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT); 13134 } 13135 13136 /** 13137 * @return true if layout direction has been resolved. 13138 */ 13139 public boolean isLayoutDirectionResolved() { 13140 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED; 13141 } 13142 13143 /** 13144 * Return if padding has been resolved 13145 * 13146 * @hide 13147 */ 13148 boolean isPaddingResolved() { 13149 return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED; 13150 } 13151 13152 /** 13153 * Resolves padding depending on layout direction, if applicable, and 13154 * recomputes internal padding values to adjust for scroll bars. 13155 * 13156 * @hide 13157 */ 13158 public void resolvePadding() { 13159 final int resolvedLayoutDirection = getLayoutDirection(); 13160 13161 if (!isRtlCompatibilityMode()) { 13162 // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account. 13163 // If start / end padding are defined, they will be resolved (hence overriding) to 13164 // left / right or right / left depending on the resolved layout direction. 13165 // If start / end padding are not defined, use the left / right ones. 13166 if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) { 13167 Rect padding = sThreadLocal.get(); 13168 if (padding == null) { 13169 padding = new Rect(); 13170 sThreadLocal.set(padding); 13171 } 13172 mBackground.getPadding(padding); 13173 if (!mLeftPaddingDefined) { 13174 mUserPaddingLeftInitial = padding.left; 13175 } 13176 if (!mRightPaddingDefined) { 13177 mUserPaddingRightInitial = padding.right; 13178 } 13179 } 13180 switch (resolvedLayoutDirection) { 13181 case LAYOUT_DIRECTION_RTL: 13182 if (mUserPaddingStart != UNDEFINED_PADDING) { 13183 mUserPaddingRight = mUserPaddingStart; 13184 } else { 13185 mUserPaddingRight = mUserPaddingRightInitial; 13186 } 13187 if (mUserPaddingEnd != UNDEFINED_PADDING) { 13188 mUserPaddingLeft = mUserPaddingEnd; 13189 } else { 13190 mUserPaddingLeft = mUserPaddingLeftInitial; 13191 } 13192 break; 13193 case LAYOUT_DIRECTION_LTR: 13194 default: 13195 if (mUserPaddingStart != UNDEFINED_PADDING) { 13196 mUserPaddingLeft = mUserPaddingStart; 13197 } else { 13198 mUserPaddingLeft = mUserPaddingLeftInitial; 13199 } 13200 if (mUserPaddingEnd != UNDEFINED_PADDING) { 13201 mUserPaddingRight = mUserPaddingEnd; 13202 } else { 13203 mUserPaddingRight = mUserPaddingRightInitial; 13204 } 13205 } 13206 13207 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 13208 } 13209 13210 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 13211 onRtlPropertiesChanged(resolvedLayoutDirection); 13212 13213 mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED; 13214 } 13215 13216 /** 13217 * Reset the resolved layout direction. 13218 * 13219 * @hide 13220 */ 13221 public void resetResolvedPadding() { 13222 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 13223 } 13224 13225 /** 13226 * This is called when the view is detached from a window. At this point it 13227 * no longer has a surface for drawing. 13228 * 13229 * @see #onAttachedToWindow() 13230 */ 13231 protected void onDetachedFromWindow() { 13232 } 13233 13234 /** 13235 * This is a framework-internal mirror of onDetachedFromWindow() that's called 13236 * after onDetachedFromWindow(). 13237 * 13238 * If you override this you *MUST* call super.onDetachedFromWindowInternal()! 13239 * The super method should be called at the end of the overriden method to ensure 13240 * subclasses are destroyed first 13241 * 13242 * @hide 13243 */ 13244 protected void onDetachedFromWindowInternal() { 13245 mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT; 13246 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 13247 13248 removeUnsetPressCallback(); 13249 removeLongPressCallback(); 13250 removePerformClickCallback(); 13251 removeSendViewScrolledAccessibilityEventCallback(); 13252 stopNestedScroll(); 13253 13254 // Anything that started animating right before detach should already 13255 // be in its final state when re-attached. 13256 jumpDrawablesToCurrentState(); 13257 13258 destroyDrawingCache(); 13259 13260 cleanupDraw(); 13261 mCurrentAnimation = null; 13262 } 13263 13264 private void cleanupDraw() { 13265 resetDisplayList(); 13266 if (mAttachInfo != null) { 13267 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 13268 } 13269 } 13270 13271 void invalidateInheritedLayoutMode(int layoutModeOfRoot) { 13272 } 13273 13274 /** 13275 * @return The number of times this view has been attached to a window 13276 */ 13277 protected int getWindowAttachCount() { 13278 return mWindowAttachCount; 13279 } 13280 13281 /** 13282 * Retrieve a unique token identifying the window this view is attached to. 13283 * @return Return the window's token for use in 13284 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 13285 */ 13286 public IBinder getWindowToken() { 13287 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 13288 } 13289 13290 /** 13291 * Retrieve the {@link WindowId} for the window this view is 13292 * currently attached to. 13293 */ 13294 public WindowId getWindowId() { 13295 if (mAttachInfo == null) { 13296 return null; 13297 } 13298 if (mAttachInfo.mWindowId == null) { 13299 try { 13300 mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId( 13301 mAttachInfo.mWindowToken); 13302 mAttachInfo.mWindowId = new WindowId( 13303 mAttachInfo.mIWindowId); 13304 } catch (RemoteException e) { 13305 } 13306 } 13307 return mAttachInfo.mWindowId; 13308 } 13309 13310 /** 13311 * Retrieve a unique token identifying the top-level "real" window of 13312 * the window that this view is attached to. That is, this is like 13313 * {@link #getWindowToken}, except if the window this view in is a panel 13314 * window (attached to another containing window), then the token of 13315 * the containing window is returned instead. 13316 * 13317 * @return Returns the associated window token, either 13318 * {@link #getWindowToken()} or the containing window's token. 13319 */ 13320 public IBinder getApplicationWindowToken() { 13321 AttachInfo ai = mAttachInfo; 13322 if (ai != null) { 13323 IBinder appWindowToken = ai.mPanelParentWindowToken; 13324 if (appWindowToken == null) { 13325 appWindowToken = ai.mWindowToken; 13326 } 13327 return appWindowToken; 13328 } 13329 return null; 13330 } 13331 13332 /** 13333 * Gets the logical display to which the view's window has been attached. 13334 * 13335 * @return The logical display, or null if the view is not currently attached to a window. 13336 */ 13337 public Display getDisplay() { 13338 return mAttachInfo != null ? mAttachInfo.mDisplay : null; 13339 } 13340 13341 /** 13342 * Retrieve private session object this view hierarchy is using to 13343 * communicate with the window manager. 13344 * @return the session object to communicate with the window manager 13345 */ 13346 /*package*/ IWindowSession getWindowSession() { 13347 return mAttachInfo != null ? mAttachInfo.mSession : null; 13348 } 13349 13350 /** 13351 * @param info the {@link android.view.View.AttachInfo} to associated with 13352 * this view 13353 */ 13354 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 13355 //System.out.println("Attached! " + this); 13356 mAttachInfo = info; 13357 if (mOverlay != null) { 13358 mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility); 13359 } 13360 mWindowAttachCount++; 13361 // We will need to evaluate the drawable state at least once. 13362 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 13363 if (mFloatingTreeObserver != null) { 13364 info.mTreeObserver.merge(mFloatingTreeObserver); 13365 mFloatingTreeObserver = null; 13366 } 13367 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) { 13368 mAttachInfo.mScrollContainers.add(this); 13369 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 13370 } 13371 performCollectViewAttributes(mAttachInfo, visibility); 13372 onAttachedToWindow(); 13373 13374 ListenerInfo li = mListenerInfo; 13375 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 13376 li != null ? li.mOnAttachStateChangeListeners : null; 13377 if (listeners != null && listeners.size() > 0) { 13378 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 13379 // perform the dispatching. The iterator is a safe guard against listeners that 13380 // could mutate the list by calling the various add/remove methods. This prevents 13381 // the array from being modified while we iterate it. 13382 for (OnAttachStateChangeListener listener : listeners) { 13383 listener.onViewAttachedToWindow(this); 13384 } 13385 } 13386 13387 int vis = info.mWindowVisibility; 13388 if (vis != GONE) { 13389 onWindowVisibilityChanged(vis); 13390 } 13391 if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) { 13392 // If nobody has evaluated the drawable state yet, then do it now. 13393 refreshDrawableState(); 13394 } 13395 needGlobalAttributesUpdate(false); 13396 } 13397 13398 void dispatchDetachedFromWindow() { 13399 AttachInfo info = mAttachInfo; 13400 if (info != null) { 13401 int vis = info.mWindowVisibility; 13402 if (vis != GONE) { 13403 onWindowVisibilityChanged(GONE); 13404 } 13405 } 13406 13407 onDetachedFromWindow(); 13408 onDetachedFromWindowInternal(); 13409 13410 ListenerInfo li = mListenerInfo; 13411 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 13412 li != null ? li.mOnAttachStateChangeListeners : null; 13413 if (listeners != null && listeners.size() > 0) { 13414 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 13415 // perform the dispatching. The iterator is a safe guard against listeners that 13416 // could mutate the list by calling the various add/remove methods. This prevents 13417 // the array from being modified while we iterate it. 13418 for (OnAttachStateChangeListener listener : listeners) { 13419 listener.onViewDetachedFromWindow(this); 13420 } 13421 } 13422 13423 if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 13424 mAttachInfo.mScrollContainers.remove(this); 13425 mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED; 13426 } 13427 13428 mAttachInfo = null; 13429 if (mOverlay != null) { 13430 mOverlay.getOverlayView().dispatchDetachedFromWindow(); 13431 } 13432 } 13433 13434 /** 13435 * Cancel any deferred high-level input events that were previously posted to the event queue. 13436 * 13437 * <p>Many views post high-level events such as click handlers to the event queue 13438 * to run deferred in order to preserve a desired user experience - clearing visible 13439 * pressed states before executing, etc. This method will abort any events of this nature 13440 * that are currently in flight.</p> 13441 * 13442 * <p>Custom views that generate their own high-level deferred input events should override 13443 * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p> 13444 * 13445 * <p>This will also cancel pending input events for any child views.</p> 13446 * 13447 * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases. 13448 * This will not impact newer events posted after this call that may occur as a result of 13449 * lower-level input events still waiting in the queue. If you are trying to prevent 13450 * double-submitted events for the duration of some sort of asynchronous transaction 13451 * you should also take other steps to protect against unexpected double inputs e.g. calling 13452 * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when 13453 * the transaction completes, tracking already submitted transaction IDs, etc.</p> 13454 */ 13455 public final void cancelPendingInputEvents() { 13456 dispatchCancelPendingInputEvents(); 13457 } 13458 13459 /** 13460 * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight. 13461 * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling. 13462 */ 13463 void dispatchCancelPendingInputEvents() { 13464 mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER; 13465 onCancelPendingInputEvents(); 13466 if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) { 13467 throw new SuperNotCalledException("View " + getClass().getSimpleName() + 13468 " did not call through to super.onCancelPendingInputEvents()"); 13469 } 13470 } 13471 13472 /** 13473 * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or 13474 * a parent view. 13475 * 13476 * <p>This method is responsible for removing any pending high-level input events that were 13477 * posted to the event queue to run later. Custom view classes that post their own deferred 13478 * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or 13479 * {@link android.os.Handler} should override this method, call 13480 * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate. 13481 * </p> 13482 */ 13483 public void onCancelPendingInputEvents() { 13484 removePerformClickCallback(); 13485 cancelLongPress(); 13486 mPrivateFlags3 |= PFLAG3_CALLED_SUPER; 13487 } 13488 13489 /** 13490 * Store this view hierarchy's frozen state into the given container. 13491 * 13492 * @param container The SparseArray in which to save the view's state. 13493 * 13494 * @see #restoreHierarchyState(android.util.SparseArray) 13495 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13496 * @see #onSaveInstanceState() 13497 */ 13498 public void saveHierarchyState(SparseArray<Parcelable> container) { 13499 dispatchSaveInstanceState(container); 13500 } 13501 13502 /** 13503 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 13504 * this view and its children. May be overridden to modify how freezing happens to a 13505 * view's children; for example, some views may want to not store state for their children. 13506 * 13507 * @param container The SparseArray in which to save the view's state. 13508 * 13509 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13510 * @see #saveHierarchyState(android.util.SparseArray) 13511 * @see #onSaveInstanceState() 13512 */ 13513 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 13514 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 13515 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 13516 Parcelable state = onSaveInstanceState(); 13517 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 13518 throw new IllegalStateException( 13519 "Derived class did not call super.onSaveInstanceState()"); 13520 } 13521 if (state != null) { 13522 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 13523 // + ": " + state); 13524 container.put(mID, state); 13525 } 13526 } 13527 } 13528 13529 /** 13530 * Hook allowing a view to generate a representation of its internal state 13531 * that can later be used to create a new instance with that same state. 13532 * This state should only contain information that is not persistent or can 13533 * not be reconstructed later. For example, you will never store your 13534 * current position on screen because that will be computed again when a 13535 * new instance of the view is placed in its view hierarchy. 13536 * <p> 13537 * Some examples of things you may store here: the current cursor position 13538 * in a text view (but usually not the text itself since that is stored in a 13539 * content provider or other persistent storage), the currently selected 13540 * item in a list view. 13541 * 13542 * @return Returns a Parcelable object containing the view's current dynamic 13543 * state, or null if there is nothing interesting to save. The 13544 * default implementation returns null. 13545 * @see #onRestoreInstanceState(android.os.Parcelable) 13546 * @see #saveHierarchyState(android.util.SparseArray) 13547 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13548 * @see #setSaveEnabled(boolean) 13549 */ 13550 protected Parcelable onSaveInstanceState() { 13551 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 13552 return BaseSavedState.EMPTY_STATE; 13553 } 13554 13555 /** 13556 * Restore this view hierarchy's frozen state from the given container. 13557 * 13558 * @param container The SparseArray which holds previously frozen states. 13559 * 13560 * @see #saveHierarchyState(android.util.SparseArray) 13561 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13562 * @see #onRestoreInstanceState(android.os.Parcelable) 13563 */ 13564 public void restoreHierarchyState(SparseArray<Parcelable> container) { 13565 dispatchRestoreInstanceState(container); 13566 } 13567 13568 /** 13569 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 13570 * state for this view and its children. May be overridden to modify how restoring 13571 * happens to a view's children; for example, some views may want to not store state 13572 * for their children. 13573 * 13574 * @param container The SparseArray which holds previously saved state. 13575 * 13576 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13577 * @see #restoreHierarchyState(android.util.SparseArray) 13578 * @see #onRestoreInstanceState(android.os.Parcelable) 13579 */ 13580 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 13581 if (mID != NO_ID) { 13582 Parcelable state = container.get(mID); 13583 if (state != null) { 13584 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 13585 // + ": " + state); 13586 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 13587 onRestoreInstanceState(state); 13588 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 13589 throw new IllegalStateException( 13590 "Derived class did not call super.onRestoreInstanceState()"); 13591 } 13592 } 13593 } 13594 } 13595 13596 /** 13597 * Hook allowing a view to re-apply a representation of its internal state that had previously 13598 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 13599 * null state. 13600 * 13601 * @param state The frozen state that had previously been returned by 13602 * {@link #onSaveInstanceState}. 13603 * 13604 * @see #onSaveInstanceState() 13605 * @see #restoreHierarchyState(android.util.SparseArray) 13606 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13607 */ 13608 protected void onRestoreInstanceState(Parcelable state) { 13609 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 13610 if (state != BaseSavedState.EMPTY_STATE && state != null) { 13611 throw new IllegalArgumentException("Wrong state class, expecting View State but " 13612 + "received " + state.getClass().toString() + " instead. This usually happens " 13613 + "when two views of different type have the same id in the same hierarchy. " 13614 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 13615 + "other views do not use the same id."); 13616 } 13617 } 13618 13619 /** 13620 * <p>Return the time at which the drawing of the view hierarchy started.</p> 13621 * 13622 * @return the drawing start time in milliseconds 13623 */ 13624 public long getDrawingTime() { 13625 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 13626 } 13627 13628 /** 13629 * <p>Enables or disables the duplication of the parent's state into this view. When 13630 * duplication is enabled, this view gets its drawable state from its parent rather 13631 * than from its own internal properties.</p> 13632 * 13633 * <p>Note: in the current implementation, setting this property to true after the 13634 * view was added to a ViewGroup might have no effect at all. This property should 13635 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 13636 * 13637 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 13638 * property is enabled, an exception will be thrown.</p> 13639 * 13640 * <p>Note: if the child view uses and updates additionnal states which are unknown to the 13641 * parent, these states should not be affected by this method.</p> 13642 * 13643 * @param enabled True to enable duplication of the parent's drawable state, false 13644 * to disable it. 13645 * 13646 * @see #getDrawableState() 13647 * @see #isDuplicateParentStateEnabled() 13648 */ 13649 public void setDuplicateParentStateEnabled(boolean enabled) { 13650 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 13651 } 13652 13653 /** 13654 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 13655 * 13656 * @return True if this view's drawable state is duplicated from the parent, 13657 * false otherwise 13658 * 13659 * @see #getDrawableState() 13660 * @see #setDuplicateParentStateEnabled(boolean) 13661 */ 13662 public boolean isDuplicateParentStateEnabled() { 13663 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 13664 } 13665 13666 /** 13667 * <p>Specifies the type of layer backing this view. The layer can be 13668 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13669 * {@link #LAYER_TYPE_HARDWARE}.</p> 13670 * 13671 * <p>A layer is associated with an optional {@link android.graphics.Paint} 13672 * instance that controls how the layer is composed on screen. The following 13673 * properties of the paint are taken into account when composing the layer:</p> 13674 * <ul> 13675 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 13676 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 13677 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 13678 * </ul> 13679 * 13680 * <p>If this view has an alpha value set to < 1.0 by calling 13681 * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded 13682 * by this view's alpha value.</p> 13683 * 13684 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE}, 13685 * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE} 13686 * for more information on when and how to use layers.</p> 13687 * 13688 * @param layerType The type of layer to use with this view, must be one of 13689 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13690 * {@link #LAYER_TYPE_HARDWARE} 13691 * @param paint The paint used to compose the layer. This argument is optional 13692 * and can be null. It is ignored when the layer type is 13693 * {@link #LAYER_TYPE_NONE} 13694 * 13695 * @see #getLayerType() 13696 * @see #LAYER_TYPE_NONE 13697 * @see #LAYER_TYPE_SOFTWARE 13698 * @see #LAYER_TYPE_HARDWARE 13699 * @see #setAlpha(float) 13700 * 13701 * @attr ref android.R.styleable#View_layerType 13702 */ 13703 public void setLayerType(int layerType, Paint paint) { 13704 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 13705 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 13706 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 13707 } 13708 13709 boolean typeChanged = mRenderNode.setLayerType(layerType); 13710 13711 if (!typeChanged) { 13712 setLayerPaint(paint); 13713 return; 13714 } 13715 13716 // Destroy any previous software drawing cache if needed 13717 if (mLayerType == LAYER_TYPE_SOFTWARE) { 13718 destroyDrawingCache(); 13719 } 13720 13721 mLayerType = layerType; 13722 final boolean layerDisabled = (mLayerType == LAYER_TYPE_NONE); 13723 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 13724 mRenderNode.setLayerPaint(mLayerPaint); 13725 13726 // draw() behaves differently if we are on a layer, so we need to 13727 // invalidate() here 13728 invalidateParentCaches(); 13729 invalidate(true); 13730 } 13731 13732 /** 13733 * Updates the {@link Paint} object used with the current layer (used only if the current 13734 * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint 13735 * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time 13736 * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to 13737 * ensure that the view gets redrawn immediately. 13738 * 13739 * <p>A layer is associated with an optional {@link android.graphics.Paint} 13740 * instance that controls how the layer is composed on screen. The following 13741 * properties of the paint are taken into account when composing the layer:</p> 13742 * <ul> 13743 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 13744 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 13745 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 13746 * </ul> 13747 * 13748 * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the 13749 * alpha value of the layer's paint is superceded by this view's alpha value.</p> 13750 * 13751 * @param paint The paint used to compose the layer. This argument is optional 13752 * and can be null. It is ignored when the layer type is 13753 * {@link #LAYER_TYPE_NONE} 13754 * 13755 * @see #setLayerType(int, android.graphics.Paint) 13756 */ 13757 public void setLayerPaint(Paint paint) { 13758 int layerType = getLayerType(); 13759 if (layerType != LAYER_TYPE_NONE) { 13760 mLayerPaint = paint == null ? new Paint() : paint; 13761 if (layerType == LAYER_TYPE_HARDWARE) { 13762 if (mRenderNode.setLayerPaint(mLayerPaint)) { 13763 invalidateViewProperty(false, false); 13764 } 13765 } else { 13766 invalidate(); 13767 } 13768 } 13769 } 13770 13771 /** 13772 * Indicates whether this view has a static layer. A view with layer type 13773 * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are 13774 * dynamic. 13775 */ 13776 boolean hasStaticLayer() { 13777 return true; 13778 } 13779 13780 /** 13781 * Indicates what type of layer is currently associated with this view. By default 13782 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 13783 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 13784 * for more information on the different types of layers. 13785 * 13786 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13787 * {@link #LAYER_TYPE_HARDWARE} 13788 * 13789 * @see #setLayerType(int, android.graphics.Paint) 13790 * @see #buildLayer() 13791 * @see #LAYER_TYPE_NONE 13792 * @see #LAYER_TYPE_SOFTWARE 13793 * @see #LAYER_TYPE_HARDWARE 13794 */ 13795 public int getLayerType() { 13796 return mLayerType; 13797 } 13798 13799 /** 13800 * Forces this view's layer to be created and this view to be rendered 13801 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 13802 * invoking this method will have no effect. 13803 * 13804 * This method can for instance be used to render a view into its layer before 13805 * starting an animation. If this view is complex, rendering into the layer 13806 * before starting the animation will avoid skipping frames. 13807 * 13808 * @throws IllegalStateException If this view is not attached to a window 13809 * 13810 * @see #setLayerType(int, android.graphics.Paint) 13811 */ 13812 public void buildLayer() { 13813 if (mLayerType == LAYER_TYPE_NONE) return; 13814 13815 final AttachInfo attachInfo = mAttachInfo; 13816 if (attachInfo == null) { 13817 throw new IllegalStateException("This view must be attached to a window first"); 13818 } 13819 13820 if (getWidth() == 0 || getHeight() == 0) { 13821 return; 13822 } 13823 13824 switch (mLayerType) { 13825 case LAYER_TYPE_HARDWARE: 13826 updateDisplayListIfDirty(); 13827 if (attachInfo.mHardwareRenderer != null && mRenderNode.isValid()) { 13828 attachInfo.mHardwareRenderer.buildLayer(mRenderNode); 13829 } 13830 break; 13831 case LAYER_TYPE_SOFTWARE: 13832 buildDrawingCache(true); 13833 break; 13834 } 13835 } 13836 13837 /** 13838 * If this View draws with a HardwareLayer, returns it. 13839 * Otherwise returns null 13840 * 13841 * TODO: Only TextureView uses this, can we eliminate it? 13842 */ 13843 HardwareLayer getHardwareLayer() { 13844 return null; 13845 } 13846 13847 /** 13848 * Destroys all hardware rendering resources. This method is invoked 13849 * when the system needs to reclaim resources. Upon execution of this 13850 * method, you should free any OpenGL resources created by the view. 13851 * 13852 * Note: you <strong>must</strong> call 13853 * <code>super.destroyHardwareResources()</code> when overriding 13854 * this method. 13855 * 13856 * @hide 13857 */ 13858 protected void destroyHardwareResources() { 13859 // Although the Layer will be destroyed by RenderNode, we want to release 13860 // the staging display list, which is also a signal to RenderNode that it's 13861 // safe to free its copy of the display list as it knows that we will 13862 // push an updated DisplayList if we try to draw again 13863 resetDisplayList(); 13864 } 13865 13866 /** 13867 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 13868 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 13869 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 13870 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 13871 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 13872 * null.</p> 13873 * 13874 * <p>Enabling the drawing cache is similar to 13875 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 13876 * acceleration is turned off. When hardware acceleration is turned on, enabling the 13877 * drawing cache has no effect on rendering because the system uses a different mechanism 13878 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 13879 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 13880 * for information on how to enable software and hardware layers.</p> 13881 * 13882 * <p>This API can be used to manually generate 13883 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 13884 * {@link #getDrawingCache()}.</p> 13885 * 13886 * @param enabled true to enable the drawing cache, false otherwise 13887 * 13888 * @see #isDrawingCacheEnabled() 13889 * @see #getDrawingCache() 13890 * @see #buildDrawingCache() 13891 * @see #setLayerType(int, android.graphics.Paint) 13892 */ 13893 public void setDrawingCacheEnabled(boolean enabled) { 13894 mCachingFailed = false; 13895 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 13896 } 13897 13898 /** 13899 * <p>Indicates whether the drawing cache is enabled for this view.</p> 13900 * 13901 * @return true if the drawing cache is enabled 13902 * 13903 * @see #setDrawingCacheEnabled(boolean) 13904 * @see #getDrawingCache() 13905 */ 13906 @ViewDebug.ExportedProperty(category = "drawing") 13907 public boolean isDrawingCacheEnabled() { 13908 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 13909 } 13910 13911 /** 13912 * Debugging utility which recursively outputs the dirty state of a view and its 13913 * descendants. 13914 * 13915 * @hide 13916 */ 13917 @SuppressWarnings({"UnusedDeclaration"}) 13918 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 13919 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) + 13920 ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" + 13921 (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) + 13922 ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")"); 13923 if (clear) { 13924 mPrivateFlags &= clearMask; 13925 } 13926 if (this instanceof ViewGroup) { 13927 ViewGroup parent = (ViewGroup) this; 13928 final int count = parent.getChildCount(); 13929 for (int i = 0; i < count; i++) { 13930 final View child = parent.getChildAt(i); 13931 child.outputDirtyFlags(indent + " ", clear, clearMask); 13932 } 13933 } 13934 } 13935 13936 /** 13937 * This method is used by ViewGroup to cause its children to restore or recreate their 13938 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 13939 * to recreate its own display list, which would happen if it went through the normal 13940 * draw/dispatchDraw mechanisms. 13941 * 13942 * @hide 13943 */ 13944 protected void dispatchGetDisplayList() {} 13945 13946 /** 13947 * A view that is not attached or hardware accelerated cannot create a display list. 13948 * This method checks these conditions and returns the appropriate result. 13949 * 13950 * @return true if view has the ability to create a display list, false otherwise. 13951 * 13952 * @hide 13953 */ 13954 public boolean canHaveDisplayList() { 13955 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 13956 } 13957 13958 private void updateDisplayListIfDirty() { 13959 final RenderNode renderNode = mRenderNode; 13960 if (!canHaveDisplayList()) { 13961 // can't populate RenderNode, don't try 13962 return; 13963 } 13964 13965 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 13966 || !renderNode.isValid() 13967 || (mRecreateDisplayList)) { 13968 // Don't need to recreate the display list, just need to tell our 13969 // children to restore/recreate theirs 13970 if (renderNode.isValid() 13971 && !mRecreateDisplayList) { 13972 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13973 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13974 dispatchGetDisplayList(); 13975 13976 return; // no work needed 13977 } 13978 13979 // If we got here, we're recreating it. Mark it as such to ensure that 13980 // we copy in child display lists into ours in drawChild() 13981 mRecreateDisplayList = true; 13982 13983 int width = mRight - mLeft; 13984 int height = mBottom - mTop; 13985 int layerType = getLayerType(); 13986 13987 final HardwareCanvas canvas = renderNode.start(width, height); 13988 canvas.setHighContrastText(mAttachInfo.mHighContrastText); 13989 13990 try { 13991 final HardwareLayer layer = getHardwareLayer(); 13992 if (layer != null && layer.isValid()) { 13993 canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint); 13994 } else if (layerType == LAYER_TYPE_SOFTWARE) { 13995 buildDrawingCache(true); 13996 Bitmap cache = getDrawingCache(true); 13997 if (cache != null) { 13998 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 13999 } 14000 } else { 14001 computeScroll(); 14002 14003 canvas.translate(-mScrollX, -mScrollY); 14004 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 14005 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14006 14007 // Fast path for layouts with no backgrounds 14008 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14009 dispatchDraw(canvas); 14010 if (mOverlay != null && !mOverlay.isEmpty()) { 14011 mOverlay.getOverlayView().draw(canvas); 14012 } 14013 } else { 14014 draw(canvas); 14015 } 14016 drawAccessibilityFocus(canvas); 14017 } 14018 } finally { 14019 renderNode.end(canvas); 14020 setDisplayListProperties(renderNode); 14021 } 14022 } else { 14023 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 14024 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14025 } 14026 } 14027 14028 /** 14029 * Returns a RenderNode with View draw content recorded, which can be 14030 * used to draw this view again without executing its draw method. 14031 * 14032 * @return A RenderNode ready to replay, or null if caching is not enabled. 14033 * 14034 * @hide 14035 */ 14036 public RenderNode getDisplayList() { 14037 updateDisplayListIfDirty(); 14038 return mRenderNode; 14039 } 14040 14041 private void resetDisplayList() { 14042 if (mRenderNode.isValid()) { 14043 mRenderNode.destroyDisplayListData(); 14044 } 14045 14046 if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) { 14047 mBackgroundRenderNode.destroyDisplayListData(); 14048 } 14049 } 14050 14051 /** 14052 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 14053 * 14054 * @return A non-scaled bitmap representing this view or null if cache is disabled. 14055 * 14056 * @see #getDrawingCache(boolean) 14057 */ 14058 public Bitmap getDrawingCache() { 14059 return getDrawingCache(false); 14060 } 14061 14062 /** 14063 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 14064 * is null when caching is disabled. If caching is enabled and the cache is not ready, 14065 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 14066 * draw from the cache when the cache is enabled. To benefit from the cache, you must 14067 * request the drawing cache by calling this method and draw it on screen if the 14068 * returned bitmap is not null.</p> 14069 * 14070 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 14071 * this method will create a bitmap of the same size as this view. Because this bitmap 14072 * will be drawn scaled by the parent ViewGroup, the result on screen might show 14073 * scaling artifacts. To avoid such artifacts, you should call this method by setting 14074 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 14075 * size than the view. This implies that your application must be able to handle this 14076 * size.</p> 14077 * 14078 * @param autoScale Indicates whether the generated bitmap should be scaled based on 14079 * the current density of the screen when the application is in compatibility 14080 * mode. 14081 * 14082 * @return A bitmap representing this view or null if cache is disabled. 14083 * 14084 * @see #setDrawingCacheEnabled(boolean) 14085 * @see #isDrawingCacheEnabled() 14086 * @see #buildDrawingCache(boolean) 14087 * @see #destroyDrawingCache() 14088 */ 14089 public Bitmap getDrawingCache(boolean autoScale) { 14090 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 14091 return null; 14092 } 14093 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 14094 buildDrawingCache(autoScale); 14095 } 14096 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 14097 } 14098 14099 /** 14100 * <p>Frees the resources used by the drawing cache. If you call 14101 * {@link #buildDrawingCache()} manually without calling 14102 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 14103 * should cleanup the cache with this method afterwards.</p> 14104 * 14105 * @see #setDrawingCacheEnabled(boolean) 14106 * @see #buildDrawingCache() 14107 * @see #getDrawingCache() 14108 */ 14109 public void destroyDrawingCache() { 14110 if (mDrawingCache != null) { 14111 mDrawingCache.recycle(); 14112 mDrawingCache = null; 14113 } 14114 if (mUnscaledDrawingCache != null) { 14115 mUnscaledDrawingCache.recycle(); 14116 mUnscaledDrawingCache = null; 14117 } 14118 } 14119 14120 /** 14121 * Setting a solid background color for the drawing cache's bitmaps will improve 14122 * performance and memory usage. Note, though that this should only be used if this 14123 * view will always be drawn on top of a solid color. 14124 * 14125 * @param color The background color to use for the drawing cache's bitmap 14126 * 14127 * @see #setDrawingCacheEnabled(boolean) 14128 * @see #buildDrawingCache() 14129 * @see #getDrawingCache() 14130 */ 14131 public void setDrawingCacheBackgroundColor(int color) { 14132 if (color != mDrawingCacheBackgroundColor) { 14133 mDrawingCacheBackgroundColor = color; 14134 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 14135 } 14136 } 14137 14138 /** 14139 * @see #setDrawingCacheBackgroundColor(int) 14140 * 14141 * @return The background color to used for the drawing cache's bitmap 14142 */ 14143 public int getDrawingCacheBackgroundColor() { 14144 return mDrawingCacheBackgroundColor; 14145 } 14146 14147 /** 14148 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 14149 * 14150 * @see #buildDrawingCache(boolean) 14151 */ 14152 public void buildDrawingCache() { 14153 buildDrawingCache(false); 14154 } 14155 14156 /** 14157 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 14158 * 14159 * <p>If you call {@link #buildDrawingCache()} manually without calling 14160 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 14161 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 14162 * 14163 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 14164 * this method will create a bitmap of the same size as this view. Because this bitmap 14165 * will be drawn scaled by the parent ViewGroup, the result on screen might show 14166 * scaling artifacts. To avoid such artifacts, you should call this method by setting 14167 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 14168 * size than the view. This implies that your application must be able to handle this 14169 * size.</p> 14170 * 14171 * <p>You should avoid calling this method when hardware acceleration is enabled. If 14172 * you do not need the drawing cache bitmap, calling this method will increase memory 14173 * usage and cause the view to be rendered in software once, thus negatively impacting 14174 * performance.</p> 14175 * 14176 * @see #getDrawingCache() 14177 * @see #destroyDrawingCache() 14178 */ 14179 public void buildDrawingCache(boolean autoScale) { 14180 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ? 14181 mDrawingCache == null : mUnscaledDrawingCache == null)) { 14182 mCachingFailed = false; 14183 14184 int width = mRight - mLeft; 14185 int height = mBottom - mTop; 14186 14187 final AttachInfo attachInfo = mAttachInfo; 14188 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 14189 14190 if (autoScale && scalingRequired) { 14191 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 14192 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 14193 } 14194 14195 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 14196 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 14197 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 14198 14199 final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4); 14200 final long drawingCacheSize = 14201 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize(); 14202 if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) { 14203 if (width > 0 && height > 0) { 14204 Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs " 14205 + projectedBitmapSize + " bytes, only " 14206 + drawingCacheSize + " available"); 14207 } 14208 destroyDrawingCache(); 14209 mCachingFailed = true; 14210 return; 14211 } 14212 14213 boolean clear = true; 14214 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 14215 14216 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 14217 Bitmap.Config quality; 14218 if (!opaque) { 14219 // Never pick ARGB_4444 because it looks awful 14220 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 14221 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 14222 case DRAWING_CACHE_QUALITY_AUTO: 14223 case DRAWING_CACHE_QUALITY_LOW: 14224 case DRAWING_CACHE_QUALITY_HIGH: 14225 default: 14226 quality = Bitmap.Config.ARGB_8888; 14227 break; 14228 } 14229 } else { 14230 // Optimization for translucent windows 14231 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 14232 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 14233 } 14234 14235 // Try to cleanup memory 14236 if (bitmap != null) bitmap.recycle(); 14237 14238 try { 14239 bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 14240 width, height, quality); 14241 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 14242 if (autoScale) { 14243 mDrawingCache = bitmap; 14244 } else { 14245 mUnscaledDrawingCache = bitmap; 14246 } 14247 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 14248 } catch (OutOfMemoryError e) { 14249 // If there is not enough memory to create the bitmap cache, just 14250 // ignore the issue as bitmap caches are not required to draw the 14251 // view hierarchy 14252 if (autoScale) { 14253 mDrawingCache = null; 14254 } else { 14255 mUnscaledDrawingCache = null; 14256 } 14257 mCachingFailed = true; 14258 return; 14259 } 14260 14261 clear = drawingCacheBackgroundColor != 0; 14262 } 14263 14264 Canvas canvas; 14265 if (attachInfo != null) { 14266 canvas = attachInfo.mCanvas; 14267 if (canvas == null) { 14268 canvas = new Canvas(); 14269 } 14270 canvas.setBitmap(bitmap); 14271 // Temporarily clobber the cached Canvas in case one of our children 14272 // is also using a drawing cache. Without this, the children would 14273 // steal the canvas by attaching their own bitmap to it and bad, bad 14274 // thing would happen (invisible views, corrupted drawings, etc.) 14275 attachInfo.mCanvas = null; 14276 } else { 14277 // This case should hopefully never or seldom happen 14278 canvas = new Canvas(bitmap); 14279 } 14280 14281 if (clear) { 14282 bitmap.eraseColor(drawingCacheBackgroundColor); 14283 } 14284 14285 computeScroll(); 14286 final int restoreCount = canvas.save(); 14287 14288 if (autoScale && scalingRequired) { 14289 final float scale = attachInfo.mApplicationScale; 14290 canvas.scale(scale, scale); 14291 } 14292 14293 canvas.translate(-mScrollX, -mScrollY); 14294 14295 mPrivateFlags |= PFLAG_DRAWN; 14296 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 14297 mLayerType != LAYER_TYPE_NONE) { 14298 mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID; 14299 } 14300 14301 // Fast path for layouts with no backgrounds 14302 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14303 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14304 dispatchDraw(canvas); 14305 if (mOverlay != null && !mOverlay.isEmpty()) { 14306 mOverlay.getOverlayView().draw(canvas); 14307 } 14308 } else { 14309 draw(canvas); 14310 } 14311 drawAccessibilityFocus(canvas); 14312 14313 canvas.restoreToCount(restoreCount); 14314 canvas.setBitmap(null); 14315 14316 if (attachInfo != null) { 14317 // Restore the cached Canvas for our siblings 14318 attachInfo.mCanvas = canvas; 14319 } 14320 } 14321 } 14322 14323 /** 14324 * Create a snapshot of the view into a bitmap. We should probably make 14325 * some form of this public, but should think about the API. 14326 */ 14327 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 14328 int width = mRight - mLeft; 14329 int height = mBottom - mTop; 14330 14331 final AttachInfo attachInfo = mAttachInfo; 14332 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 14333 width = (int) ((width * scale) + 0.5f); 14334 height = (int) ((height * scale) + 0.5f); 14335 14336 Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 14337 width > 0 ? width : 1, height > 0 ? height : 1, quality); 14338 if (bitmap == null) { 14339 throw new OutOfMemoryError(); 14340 } 14341 14342 Resources resources = getResources(); 14343 if (resources != null) { 14344 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 14345 } 14346 14347 Canvas canvas; 14348 if (attachInfo != null) { 14349 canvas = attachInfo.mCanvas; 14350 if (canvas == null) { 14351 canvas = new Canvas(); 14352 } 14353 canvas.setBitmap(bitmap); 14354 // Temporarily clobber the cached Canvas in case one of our children 14355 // is also using a drawing cache. Without this, the children would 14356 // steal the canvas by attaching their own bitmap to it and bad, bad 14357 // things would happen (invisible views, corrupted drawings, etc.) 14358 attachInfo.mCanvas = null; 14359 } else { 14360 // This case should hopefully never or seldom happen 14361 canvas = new Canvas(bitmap); 14362 } 14363 14364 if ((backgroundColor & 0xff000000) != 0) { 14365 bitmap.eraseColor(backgroundColor); 14366 } 14367 14368 computeScroll(); 14369 final int restoreCount = canvas.save(); 14370 canvas.scale(scale, scale); 14371 canvas.translate(-mScrollX, -mScrollY); 14372 14373 // Temporarily remove the dirty mask 14374 int flags = mPrivateFlags; 14375 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14376 14377 // Fast path for layouts with no backgrounds 14378 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14379 dispatchDraw(canvas); 14380 if (mOverlay != null && !mOverlay.isEmpty()) { 14381 mOverlay.getOverlayView().draw(canvas); 14382 } 14383 } else { 14384 draw(canvas); 14385 } 14386 drawAccessibilityFocus(canvas); 14387 14388 mPrivateFlags = flags; 14389 14390 canvas.restoreToCount(restoreCount); 14391 canvas.setBitmap(null); 14392 14393 if (attachInfo != null) { 14394 // Restore the cached Canvas for our siblings 14395 attachInfo.mCanvas = canvas; 14396 } 14397 14398 return bitmap; 14399 } 14400 14401 /** 14402 * Indicates whether this View is currently in edit mode. A View is usually 14403 * in edit mode when displayed within a developer tool. For instance, if 14404 * this View is being drawn by a visual user interface builder, this method 14405 * should return true. 14406 * 14407 * Subclasses should check the return value of this method to provide 14408 * different behaviors if their normal behavior might interfere with the 14409 * host environment. For instance: the class spawns a thread in its 14410 * constructor, the drawing code relies on device-specific features, etc. 14411 * 14412 * This method is usually checked in the drawing code of custom widgets. 14413 * 14414 * @return True if this View is in edit mode, false otherwise. 14415 */ 14416 public boolean isInEditMode() { 14417 return false; 14418 } 14419 14420 /** 14421 * If the View draws content inside its padding and enables fading edges, 14422 * it needs to support padding offsets. Padding offsets are added to the 14423 * fading edges to extend the length of the fade so that it covers pixels 14424 * drawn inside the padding. 14425 * 14426 * Subclasses of this class should override this method if they need 14427 * to draw content inside the padding. 14428 * 14429 * @return True if padding offset must be applied, false otherwise. 14430 * 14431 * @see #getLeftPaddingOffset() 14432 * @see #getRightPaddingOffset() 14433 * @see #getTopPaddingOffset() 14434 * @see #getBottomPaddingOffset() 14435 * 14436 * @since CURRENT 14437 */ 14438 protected boolean isPaddingOffsetRequired() { 14439 return false; 14440 } 14441 14442 /** 14443 * Amount by which to extend the left fading region. Called only when 14444 * {@link #isPaddingOffsetRequired()} returns true. 14445 * 14446 * @return The left padding offset in pixels. 14447 * 14448 * @see #isPaddingOffsetRequired() 14449 * 14450 * @since CURRENT 14451 */ 14452 protected int getLeftPaddingOffset() { 14453 return 0; 14454 } 14455 14456 /** 14457 * Amount by which to extend the right fading region. Called only when 14458 * {@link #isPaddingOffsetRequired()} returns true. 14459 * 14460 * @return The right padding offset in pixels. 14461 * 14462 * @see #isPaddingOffsetRequired() 14463 * 14464 * @since CURRENT 14465 */ 14466 protected int getRightPaddingOffset() { 14467 return 0; 14468 } 14469 14470 /** 14471 * Amount by which to extend the top fading region. Called only when 14472 * {@link #isPaddingOffsetRequired()} returns true. 14473 * 14474 * @return The top padding offset in pixels. 14475 * 14476 * @see #isPaddingOffsetRequired() 14477 * 14478 * @since CURRENT 14479 */ 14480 protected int getTopPaddingOffset() { 14481 return 0; 14482 } 14483 14484 /** 14485 * Amount by which to extend the bottom fading region. Called only when 14486 * {@link #isPaddingOffsetRequired()} returns true. 14487 * 14488 * @return The bottom padding offset in pixels. 14489 * 14490 * @see #isPaddingOffsetRequired() 14491 * 14492 * @since CURRENT 14493 */ 14494 protected int getBottomPaddingOffset() { 14495 return 0; 14496 } 14497 14498 /** 14499 * @hide 14500 * @param offsetRequired 14501 */ 14502 protected int getFadeTop(boolean offsetRequired) { 14503 int top = mPaddingTop; 14504 if (offsetRequired) top += getTopPaddingOffset(); 14505 return top; 14506 } 14507 14508 /** 14509 * @hide 14510 * @param offsetRequired 14511 */ 14512 protected int getFadeHeight(boolean offsetRequired) { 14513 int padding = mPaddingTop; 14514 if (offsetRequired) padding += getTopPaddingOffset(); 14515 return mBottom - mTop - mPaddingBottom - padding; 14516 } 14517 14518 /** 14519 * <p>Indicates whether this view is attached to a hardware accelerated 14520 * window or not.</p> 14521 * 14522 * <p>Even if this method returns true, it does not mean that every call 14523 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 14524 * accelerated {@link android.graphics.Canvas}. For instance, if this view 14525 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 14526 * window is hardware accelerated, 14527 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 14528 * return false, and this method will return true.</p> 14529 * 14530 * @return True if the view is attached to a window and the window is 14531 * hardware accelerated; false in any other case. 14532 */ 14533 @ViewDebug.ExportedProperty(category = "drawing") 14534 public boolean isHardwareAccelerated() { 14535 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 14536 } 14537 14538 /** 14539 * Sets a rectangular area on this view to which the view will be clipped 14540 * when it is drawn. Setting the value to null will remove the clip bounds 14541 * and the view will draw normally, using its full bounds. 14542 * 14543 * @param clipBounds The rectangular area, in the local coordinates of 14544 * this view, to which future drawing operations will be clipped. 14545 */ 14546 public void setClipBounds(Rect clipBounds) { 14547 if (clipBounds != null) { 14548 if (clipBounds.equals(mClipBounds)) { 14549 return; 14550 } 14551 if (mClipBounds == null) { 14552 invalidate(); 14553 mClipBounds = new Rect(clipBounds); 14554 } else { 14555 invalidate(Math.min(mClipBounds.left, clipBounds.left), 14556 Math.min(mClipBounds.top, clipBounds.top), 14557 Math.max(mClipBounds.right, clipBounds.right), 14558 Math.max(mClipBounds.bottom, clipBounds.bottom)); 14559 mClipBounds.set(clipBounds); 14560 } 14561 } else { 14562 if (mClipBounds != null) { 14563 invalidate(); 14564 mClipBounds = null; 14565 } 14566 } 14567 mRenderNode.setClipBounds(mClipBounds); 14568 } 14569 14570 /** 14571 * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}. 14572 * 14573 * @return A copy of the current clip bounds if clip bounds are set, 14574 * otherwise null. 14575 */ 14576 public Rect getClipBounds() { 14577 return (mClipBounds != null) ? new Rect(mClipBounds) : null; 14578 } 14579 14580 /** 14581 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 14582 * case of an active Animation being run on the view. 14583 */ 14584 private boolean drawAnimation(ViewGroup parent, long drawingTime, 14585 Animation a, boolean scalingRequired) { 14586 Transformation invalidationTransform; 14587 final int flags = parent.mGroupFlags; 14588 final boolean initialized = a.isInitialized(); 14589 if (!initialized) { 14590 a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight()); 14591 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 14592 if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler); 14593 onAnimationStart(); 14594 } 14595 14596 final Transformation t = parent.getChildTransformation(); 14597 boolean more = a.getTransformation(drawingTime, t, 1f); 14598 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 14599 if (parent.mInvalidationTransformation == null) { 14600 parent.mInvalidationTransformation = new Transformation(); 14601 } 14602 invalidationTransform = parent.mInvalidationTransformation; 14603 a.getTransformation(drawingTime, invalidationTransform, 1f); 14604 } else { 14605 invalidationTransform = t; 14606 } 14607 14608 if (more) { 14609 if (!a.willChangeBounds()) { 14610 if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) == 14611 ViewGroup.FLAG_OPTIMIZE_INVALIDATE) { 14612 parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED; 14613 } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) { 14614 // The child need to draw an animation, potentially offscreen, so 14615 // make sure we do not cancel invalidate requests 14616 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 14617 parent.invalidate(mLeft, mTop, mRight, mBottom); 14618 } 14619 } else { 14620 if (parent.mInvalidateRegion == null) { 14621 parent.mInvalidateRegion = new RectF(); 14622 } 14623 final RectF region = parent.mInvalidateRegion; 14624 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 14625 invalidationTransform); 14626 14627 // The child need to draw an animation, potentially offscreen, so 14628 // make sure we do not cancel invalidate requests 14629 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 14630 14631 final int left = mLeft + (int) region.left; 14632 final int top = mTop + (int) region.top; 14633 parent.invalidate(left, top, left + (int) (region.width() + .5f), 14634 top + (int) (region.height() + .5f)); 14635 } 14636 } 14637 return more; 14638 } 14639 14640 /** 14641 * This method is called by getDisplayList() when a display list is recorded for a View. 14642 * It pushes any properties to the RenderNode that aren't managed by the RenderNode. 14643 */ 14644 void setDisplayListProperties(RenderNode renderNode) { 14645 if (renderNode != null) { 14646 renderNode.setHasOverlappingRendering(hasOverlappingRendering()); 14647 if (mParent instanceof ViewGroup) { 14648 renderNode.setClipToBounds( 14649 (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0); 14650 } 14651 float alpha = 1; 14652 if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags & 14653 ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 14654 ViewGroup parentVG = (ViewGroup) mParent; 14655 final Transformation t = parentVG.getChildTransformation(); 14656 if (parentVG.getChildStaticTransformation(this, t)) { 14657 final int transformType = t.getTransformationType(); 14658 if (transformType != Transformation.TYPE_IDENTITY) { 14659 if ((transformType & Transformation.TYPE_ALPHA) != 0) { 14660 alpha = t.getAlpha(); 14661 } 14662 if ((transformType & Transformation.TYPE_MATRIX) != 0) { 14663 renderNode.setStaticMatrix(t.getMatrix()); 14664 } 14665 } 14666 } 14667 } 14668 if (mTransformationInfo != null) { 14669 alpha *= getFinalAlpha(); 14670 if (alpha < 1) { 14671 final int multipliedAlpha = (int) (255 * alpha); 14672 if (onSetAlpha(multipliedAlpha)) { 14673 alpha = 1; 14674 } 14675 } 14676 renderNode.setAlpha(alpha); 14677 } else if (alpha < 1) { 14678 renderNode.setAlpha(alpha); 14679 } 14680 } 14681 } 14682 14683 /** 14684 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 14685 * This draw() method is an implementation detail and is not intended to be overridden or 14686 * to be called from anywhere else other than ViewGroup.drawChild(). 14687 */ 14688 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 14689 boolean usingRenderNodeProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 14690 boolean more = false; 14691 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 14692 final int flags = parent.mGroupFlags; 14693 14694 if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) { 14695 parent.getChildTransformation().clear(); 14696 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14697 } 14698 14699 Transformation transformToApply = null; 14700 boolean concatMatrix = false; 14701 14702 boolean scalingRequired = false; 14703 boolean caching; 14704 int layerType = getLayerType(); 14705 14706 final boolean hardwareAccelerated = canvas.isHardwareAccelerated(); 14707 if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 || 14708 (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) { 14709 caching = true; 14710 // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList 14711 if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired; 14712 } else { 14713 caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated; 14714 } 14715 14716 final Animation a = getAnimation(); 14717 if (a != null) { 14718 more = drawAnimation(parent, drawingTime, a, scalingRequired); 14719 concatMatrix = a.willChangeTransformationMatrix(); 14720 if (concatMatrix) { 14721 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 14722 } 14723 transformToApply = parent.getChildTransformation(); 14724 } else { 14725 if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) { 14726 // No longer animating: clear out old animation matrix 14727 mRenderNode.setAnimationMatrix(null); 14728 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 14729 } 14730 if (!usingRenderNodeProperties && 14731 (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 14732 final Transformation t = parent.getChildTransformation(); 14733 final boolean hasTransform = parent.getChildStaticTransformation(this, t); 14734 if (hasTransform) { 14735 final int transformType = t.getTransformationType(); 14736 transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null; 14737 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 14738 } 14739 } 14740 } 14741 14742 concatMatrix |= !childHasIdentityMatrix; 14743 14744 // Sets the flag as early as possible to allow draw() implementations 14745 // to call invalidate() successfully when doing animations 14746 mPrivateFlags |= PFLAG_DRAWN; 14747 14748 if (!concatMatrix && 14749 (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS | 14750 ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN && 14751 canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 14752 (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) { 14753 mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED; 14754 return more; 14755 } 14756 mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED; 14757 14758 if (hardwareAccelerated) { 14759 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 14760 // retain the flag's value temporarily in the mRecreateDisplayList flag 14761 mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED; 14762 mPrivateFlags &= ~PFLAG_INVALIDATED; 14763 } 14764 14765 RenderNode renderNode = null; 14766 Bitmap cache = null; 14767 boolean hasDisplayList = false; 14768 if (caching) { 14769 if (!hardwareAccelerated) { 14770 if (layerType != LAYER_TYPE_NONE) { 14771 layerType = LAYER_TYPE_SOFTWARE; 14772 buildDrawingCache(true); 14773 } 14774 cache = getDrawingCache(true); 14775 } else { 14776 switch (layerType) { 14777 case LAYER_TYPE_SOFTWARE: 14778 if (usingRenderNodeProperties) { 14779 hasDisplayList = canHaveDisplayList(); 14780 } else { 14781 buildDrawingCache(true); 14782 cache = getDrawingCache(true); 14783 } 14784 break; 14785 case LAYER_TYPE_HARDWARE: 14786 if (usingRenderNodeProperties) { 14787 hasDisplayList = canHaveDisplayList(); 14788 } 14789 break; 14790 case LAYER_TYPE_NONE: 14791 // Delay getting the display list until animation-driven alpha values are 14792 // set up and possibly passed on to the view 14793 hasDisplayList = canHaveDisplayList(); 14794 break; 14795 } 14796 } 14797 } 14798 usingRenderNodeProperties &= hasDisplayList; 14799 if (usingRenderNodeProperties) { 14800 renderNode = getDisplayList(); 14801 if (!renderNode.isValid()) { 14802 // Uncommon, but possible. If a view is removed from the hierarchy during the call 14803 // to getDisplayList(), the display list will be marked invalid and we should not 14804 // try to use it again. 14805 renderNode = null; 14806 hasDisplayList = false; 14807 usingRenderNodeProperties = false; 14808 } 14809 } 14810 14811 int sx = 0; 14812 int sy = 0; 14813 if (!hasDisplayList) { 14814 computeScroll(); 14815 sx = mScrollX; 14816 sy = mScrollY; 14817 } 14818 14819 final boolean hasNoCache = cache == null || hasDisplayList; 14820 final boolean offsetForScroll = cache == null && !hasDisplayList && 14821 layerType != LAYER_TYPE_HARDWARE; 14822 14823 int restoreTo = -1; 14824 if (!usingRenderNodeProperties || transformToApply != null) { 14825 restoreTo = canvas.save(); 14826 } 14827 if (offsetForScroll) { 14828 canvas.translate(mLeft - sx, mTop - sy); 14829 } else { 14830 if (!usingRenderNodeProperties) { 14831 canvas.translate(mLeft, mTop); 14832 } 14833 if (scalingRequired) { 14834 if (usingRenderNodeProperties) { 14835 // TODO: Might not need this if we put everything inside the DL 14836 restoreTo = canvas.save(); 14837 } 14838 // mAttachInfo cannot be null, otherwise scalingRequired == false 14839 final float scale = 1.0f / mAttachInfo.mApplicationScale; 14840 canvas.scale(scale, scale); 14841 } 14842 } 14843 14844 float alpha = usingRenderNodeProperties ? 1 : (getAlpha() * getTransitionAlpha()); 14845 if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() || 14846 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 14847 if (transformToApply != null || !childHasIdentityMatrix) { 14848 int transX = 0; 14849 int transY = 0; 14850 14851 if (offsetForScroll) { 14852 transX = -sx; 14853 transY = -sy; 14854 } 14855 14856 if (transformToApply != null) { 14857 if (concatMatrix) { 14858 if (usingRenderNodeProperties) { 14859 renderNode.setAnimationMatrix(transformToApply.getMatrix()); 14860 } else { 14861 // Undo the scroll translation, apply the transformation matrix, 14862 // then redo the scroll translate to get the correct result. 14863 canvas.translate(-transX, -transY); 14864 canvas.concat(transformToApply.getMatrix()); 14865 canvas.translate(transX, transY); 14866 } 14867 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14868 } 14869 14870 float transformAlpha = transformToApply.getAlpha(); 14871 if (transformAlpha < 1) { 14872 alpha *= transformAlpha; 14873 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14874 } 14875 } 14876 14877 if (!childHasIdentityMatrix && !usingRenderNodeProperties) { 14878 canvas.translate(-transX, -transY); 14879 canvas.concat(getMatrix()); 14880 canvas.translate(transX, transY); 14881 } 14882 } 14883 14884 // Deal with alpha if it is or used to be <1 14885 if (alpha < 1 || 14886 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 14887 if (alpha < 1) { 14888 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA; 14889 } else { 14890 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA; 14891 } 14892 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14893 if (hasNoCache) { 14894 final int multipliedAlpha = (int) (255 * alpha); 14895 if (!onSetAlpha(multipliedAlpha)) { 14896 int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 14897 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 || 14898 layerType != LAYER_TYPE_NONE) { 14899 layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG; 14900 } 14901 if (usingRenderNodeProperties) { 14902 renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha()); 14903 } else if (layerType == LAYER_TYPE_NONE) { 14904 final int scrollX = hasDisplayList ? 0 : sx; 14905 final int scrollY = hasDisplayList ? 0 : sy; 14906 canvas.saveLayerAlpha(scrollX, scrollY, 14907 scrollX + (mRight - mLeft), scrollY + (mBottom - mTop), 14908 multipliedAlpha, layerFlags); 14909 } 14910 } else { 14911 // Alpha is handled by the child directly, clobber the layer's alpha 14912 mPrivateFlags |= PFLAG_ALPHA_SET; 14913 } 14914 } 14915 } 14916 } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 14917 onSetAlpha(255); 14918 mPrivateFlags &= ~PFLAG_ALPHA_SET; 14919 } 14920 14921 if (!usingRenderNodeProperties) { 14922 // apply clips directly, since RenderNode won't do it for this draw 14923 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN 14924 && cache == null) { 14925 if (offsetForScroll) { 14926 canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop)); 14927 } else { 14928 if (!scalingRequired || cache == null) { 14929 canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop); 14930 } else { 14931 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 14932 } 14933 } 14934 } 14935 14936 if (mClipBounds != null) { 14937 // clip bounds ignore scroll 14938 canvas.clipRect(mClipBounds); 14939 } 14940 } 14941 14942 14943 14944 if (!usingRenderNodeProperties && hasDisplayList) { 14945 renderNode = getDisplayList(); 14946 if (!renderNode.isValid()) { 14947 // Uncommon, but possible. If a view is removed from the hierarchy during the call 14948 // to getDisplayList(), the display list will be marked invalid and we should not 14949 // try to use it again. 14950 renderNode = null; 14951 hasDisplayList = false; 14952 } 14953 } 14954 14955 if (hasNoCache) { 14956 boolean layerRendered = false; 14957 if (layerType == LAYER_TYPE_HARDWARE && !usingRenderNodeProperties) { 14958 final HardwareLayer layer = getHardwareLayer(); 14959 if (layer != null && layer.isValid()) { 14960 int restoreAlpha = mLayerPaint.getAlpha(); 14961 mLayerPaint.setAlpha((int) (alpha * 255)); 14962 ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint); 14963 mLayerPaint.setAlpha(restoreAlpha); 14964 layerRendered = true; 14965 } else { 14966 final int scrollX = hasDisplayList ? 0 : sx; 14967 final int scrollY = hasDisplayList ? 0 : sy; 14968 canvas.saveLayer(scrollX, scrollY, 14969 scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint, 14970 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG); 14971 } 14972 } 14973 14974 if (!layerRendered) { 14975 if (!hasDisplayList) { 14976 // Fast path for layouts with no backgrounds 14977 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14978 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14979 dispatchDraw(canvas); 14980 if (mOverlay != null && !mOverlay.isEmpty()) { 14981 mOverlay.getOverlayView().draw(canvas); 14982 } 14983 } else { 14984 draw(canvas); 14985 } 14986 drawAccessibilityFocus(canvas); 14987 } else { 14988 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14989 ((HardwareCanvas) canvas).drawRenderNode(renderNode, null, flags); 14990 } 14991 } 14992 } else if (cache != null) { 14993 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14994 Paint cachePaint; 14995 int restoreAlpha = 0; 14996 14997 if (layerType == LAYER_TYPE_NONE) { 14998 cachePaint = parent.mCachePaint; 14999 if (cachePaint == null) { 15000 cachePaint = new Paint(); 15001 cachePaint.setDither(false); 15002 parent.mCachePaint = cachePaint; 15003 } 15004 } else { 15005 cachePaint = mLayerPaint; 15006 restoreAlpha = mLayerPaint.getAlpha(); 15007 } 15008 cachePaint.setAlpha((int) (alpha * 255)); 15009 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 15010 cachePaint.setAlpha(restoreAlpha); 15011 } 15012 15013 if (restoreTo >= 0) { 15014 canvas.restoreToCount(restoreTo); 15015 } 15016 15017 if (a != null && !more) { 15018 if (!hardwareAccelerated && !a.getFillAfter()) { 15019 onSetAlpha(255); 15020 } 15021 parent.finishAnimatingView(this, a); 15022 } 15023 15024 if (more && hardwareAccelerated) { 15025 if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 15026 // alpha animations should cause the child to recreate its display list 15027 invalidate(true); 15028 } 15029 } 15030 15031 mRecreateDisplayList = false; 15032 15033 return more; 15034 } 15035 15036 /** 15037 * Manually render this view (and all of its children) to the given Canvas. 15038 * The view must have already done a full layout before this function is 15039 * called. When implementing a view, implement 15040 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 15041 * If you do need to override this method, call the superclass version. 15042 * 15043 * @param canvas The Canvas to which the View is rendered. 15044 */ 15045 public void draw(Canvas canvas) { 15046 final int privateFlags = mPrivateFlags; 15047 final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE && 15048 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 15049 mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN; 15050 15051 /* 15052 * Draw traversal performs several drawing steps which must be executed 15053 * in the appropriate order: 15054 * 15055 * 1. Draw the background 15056 * 2. If necessary, save the canvas' layers to prepare for fading 15057 * 3. Draw view's content 15058 * 4. Draw children 15059 * 5. If necessary, draw the fading edges and restore layers 15060 * 6. Draw decorations (scrollbars for instance) 15061 */ 15062 15063 // Step 1, draw the background, if needed 15064 int saveCount; 15065 15066 if (!dirtyOpaque) { 15067 drawBackground(canvas); 15068 } 15069 15070 // skip step 2 & 5 if possible (common case) 15071 final int viewFlags = mViewFlags; 15072 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 15073 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 15074 if (!verticalEdges && !horizontalEdges) { 15075 // Step 3, draw the content 15076 if (!dirtyOpaque) onDraw(canvas); 15077 15078 // Step 4, draw the children 15079 dispatchDraw(canvas); 15080 15081 // Step 6, draw decorations (scrollbars) 15082 onDrawScrollBars(canvas); 15083 15084 if (mOverlay != null && !mOverlay.isEmpty()) { 15085 mOverlay.getOverlayView().dispatchDraw(canvas); 15086 } 15087 15088 // we're done... 15089 return; 15090 } 15091 15092 /* 15093 * Here we do the full fledged routine... 15094 * (this is an uncommon case where speed matters less, 15095 * this is why we repeat some of the tests that have been 15096 * done above) 15097 */ 15098 15099 boolean drawTop = false; 15100 boolean drawBottom = false; 15101 boolean drawLeft = false; 15102 boolean drawRight = false; 15103 15104 float topFadeStrength = 0.0f; 15105 float bottomFadeStrength = 0.0f; 15106 float leftFadeStrength = 0.0f; 15107 float rightFadeStrength = 0.0f; 15108 15109 // Step 2, save the canvas' layers 15110 int paddingLeft = mPaddingLeft; 15111 15112 final boolean offsetRequired = isPaddingOffsetRequired(); 15113 if (offsetRequired) { 15114 paddingLeft += getLeftPaddingOffset(); 15115 } 15116 15117 int left = mScrollX + paddingLeft; 15118 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 15119 int top = mScrollY + getFadeTop(offsetRequired); 15120 int bottom = top + getFadeHeight(offsetRequired); 15121 15122 if (offsetRequired) { 15123 right += getRightPaddingOffset(); 15124 bottom += getBottomPaddingOffset(); 15125 } 15126 15127 final ScrollabilityCache scrollabilityCache = mScrollCache; 15128 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 15129 int length = (int) fadeHeight; 15130 15131 // clip the fade length if top and bottom fades overlap 15132 // overlapping fades produce odd-looking artifacts 15133 if (verticalEdges && (top + length > bottom - length)) { 15134 length = (bottom - top) / 2; 15135 } 15136 15137 // also clip horizontal fades if necessary 15138 if (horizontalEdges && (left + length > right - length)) { 15139 length = (right - left) / 2; 15140 } 15141 15142 if (verticalEdges) { 15143 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 15144 drawTop = topFadeStrength * fadeHeight > 1.0f; 15145 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 15146 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 15147 } 15148 15149 if (horizontalEdges) { 15150 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 15151 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 15152 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 15153 drawRight = rightFadeStrength * fadeHeight > 1.0f; 15154 } 15155 15156 saveCount = canvas.getSaveCount(); 15157 15158 int solidColor = getSolidColor(); 15159 if (solidColor == 0) { 15160 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 15161 15162 if (drawTop) { 15163 canvas.saveLayer(left, top, right, top + length, null, flags); 15164 } 15165 15166 if (drawBottom) { 15167 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 15168 } 15169 15170 if (drawLeft) { 15171 canvas.saveLayer(left, top, left + length, bottom, null, flags); 15172 } 15173 15174 if (drawRight) { 15175 canvas.saveLayer(right - length, top, right, bottom, null, flags); 15176 } 15177 } else { 15178 scrollabilityCache.setFadeColor(solidColor); 15179 } 15180 15181 // Step 3, draw the content 15182 if (!dirtyOpaque) onDraw(canvas); 15183 15184 // Step 4, draw the children 15185 dispatchDraw(canvas); 15186 15187 // Step 5, draw the fade effect and restore layers 15188 final Paint p = scrollabilityCache.paint; 15189 final Matrix matrix = scrollabilityCache.matrix; 15190 final Shader fade = scrollabilityCache.shader; 15191 15192 if (drawTop) { 15193 matrix.setScale(1, fadeHeight * topFadeStrength); 15194 matrix.postTranslate(left, top); 15195 fade.setLocalMatrix(matrix); 15196 p.setShader(fade); 15197 canvas.drawRect(left, top, right, top + length, p); 15198 } 15199 15200 if (drawBottom) { 15201 matrix.setScale(1, fadeHeight * bottomFadeStrength); 15202 matrix.postRotate(180); 15203 matrix.postTranslate(left, bottom); 15204 fade.setLocalMatrix(matrix); 15205 p.setShader(fade); 15206 canvas.drawRect(left, bottom - length, right, bottom, p); 15207 } 15208 15209 if (drawLeft) { 15210 matrix.setScale(1, fadeHeight * leftFadeStrength); 15211 matrix.postRotate(-90); 15212 matrix.postTranslate(left, top); 15213 fade.setLocalMatrix(matrix); 15214 p.setShader(fade); 15215 canvas.drawRect(left, top, left + length, bottom, p); 15216 } 15217 15218 if (drawRight) { 15219 matrix.setScale(1, fadeHeight * rightFadeStrength); 15220 matrix.postRotate(90); 15221 matrix.postTranslate(right, top); 15222 fade.setLocalMatrix(matrix); 15223 p.setShader(fade); 15224 canvas.drawRect(right - length, top, right, bottom, p); 15225 } 15226 15227 canvas.restoreToCount(saveCount); 15228 15229 // Step 6, draw decorations (scrollbars) 15230 onDrawScrollBars(canvas); 15231 15232 if (mOverlay != null && !mOverlay.isEmpty()) { 15233 mOverlay.getOverlayView().dispatchDraw(canvas); 15234 } 15235 } 15236 15237 /** 15238 * Draws the accessibility focus rect onto the specified canvas. 15239 * 15240 * @param canvas Canvas on which to draw the focus rect 15241 */ 15242 private void drawAccessibilityFocus(Canvas canvas) { 15243 if (mAttachInfo == null) { 15244 return; 15245 } 15246 15247 final Rect bounds = mAttachInfo.mTmpInvalRect; 15248 final ViewRootImpl viewRoot = getViewRootImpl(); 15249 if (viewRoot == null || viewRoot.getAccessibilityFocusedHost() != this) { 15250 return; 15251 } 15252 15253 final AccessibilityManager manager = AccessibilityManager.getInstance(mContext); 15254 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 15255 return; 15256 } 15257 15258 final Drawable drawable = viewRoot.getAccessibilityFocusedDrawable(); 15259 if (drawable == null) { 15260 return; 15261 } 15262 15263 final AccessibilityNodeInfo virtualView = viewRoot.getAccessibilityFocusedVirtualView(); 15264 if (virtualView != null) { 15265 virtualView.getBoundsInScreen(bounds); 15266 final int[] offset = mAttachInfo.mTmpLocation; 15267 getLocationOnScreen(offset); 15268 bounds.offset(-offset[0], -offset[1]); 15269 } else { 15270 bounds.set(0, 0, mRight - mLeft, mBottom - mTop); 15271 } 15272 15273 canvas.save(); 15274 canvas.translate(mScrollX, mScrollY); 15275 canvas.clipRect(bounds, Region.Op.REPLACE); 15276 drawable.setBounds(bounds); 15277 drawable.draw(canvas); 15278 canvas.restore(); 15279 } 15280 15281 /** 15282 * Draws the background onto the specified canvas. 15283 * 15284 * @param canvas Canvas on which to draw the background 15285 */ 15286 private void drawBackground(Canvas canvas) { 15287 final Drawable background = mBackground; 15288 if (background == null) { 15289 return; 15290 } 15291 15292 if (mBackgroundSizeChanged) { 15293 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 15294 mBackgroundSizeChanged = false; 15295 invalidateOutline(); 15296 } 15297 15298 // Attempt to use a display list if requested. 15299 if (canvas.isHardwareAccelerated() && mAttachInfo != null 15300 && mAttachInfo.mHardwareRenderer != null) { 15301 mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode); 15302 15303 final RenderNode displayList = mBackgroundRenderNode; 15304 if (displayList != null && displayList.isValid()) { 15305 setBackgroundDisplayListProperties(displayList); 15306 ((HardwareCanvas) canvas).drawRenderNode(displayList); 15307 return; 15308 } 15309 } 15310 15311 final int scrollX = mScrollX; 15312 final int scrollY = mScrollY; 15313 if ((scrollX | scrollY) == 0) { 15314 background.draw(canvas); 15315 } else { 15316 canvas.translate(scrollX, scrollY); 15317 background.draw(canvas); 15318 canvas.translate(-scrollX, -scrollY); 15319 } 15320 } 15321 15322 /** 15323 * Set up background drawable display list properties. 15324 * 15325 * @param displayList Valid display list for the background drawable 15326 */ 15327 private void setBackgroundDisplayListProperties(RenderNode displayList) { 15328 displayList.setTranslationX(mScrollX); 15329 displayList.setTranslationY(mScrollY); 15330 } 15331 15332 /** 15333 * Creates a new display list or updates the existing display list for the 15334 * specified Drawable. 15335 * 15336 * @param drawable Drawable for which to create a display list 15337 * @param renderNode Existing RenderNode, or {@code null} 15338 * @return A valid display list for the specified drawable 15339 */ 15340 private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) { 15341 if (renderNode == null) { 15342 renderNode = RenderNode.create(drawable.getClass().getName(), this); 15343 } 15344 15345 final Rect bounds = drawable.getBounds(); 15346 final int width = bounds.width(); 15347 final int height = bounds.height(); 15348 final HardwareCanvas canvas = renderNode.start(width, height); 15349 try { 15350 drawable.draw(canvas); 15351 } finally { 15352 renderNode.end(canvas); 15353 } 15354 15355 // Set up drawable properties that are view-independent. 15356 renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom); 15357 renderNode.setProjectBackwards(drawable.isProjected()); 15358 renderNode.setProjectionReceiver(true); 15359 renderNode.setClipToBounds(false); 15360 return renderNode; 15361 } 15362 15363 /** 15364 * Returns the overlay for this view, creating it if it does not yet exist. 15365 * Adding drawables to the overlay will cause them to be displayed whenever 15366 * the view itself is redrawn. Objects in the overlay should be actively 15367 * managed: remove them when they should not be displayed anymore. The 15368 * overlay will always have the same size as its host view. 15369 * 15370 * <p>Note: Overlays do not currently work correctly with {@link 15371 * SurfaceView} or {@link TextureView}; contents in overlays for these 15372 * types of views may not display correctly.</p> 15373 * 15374 * @return The ViewOverlay object for this view. 15375 * @see ViewOverlay 15376 */ 15377 public ViewOverlay getOverlay() { 15378 if (mOverlay == null) { 15379 mOverlay = new ViewOverlay(mContext, this); 15380 } 15381 return mOverlay; 15382 } 15383 15384 /** 15385 * Override this if your view is known to always be drawn on top of a solid color background, 15386 * and needs to draw fading edges. Returning a non-zero color enables the view system to 15387 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 15388 * should be set to 0xFF. 15389 * 15390 * @see #setVerticalFadingEdgeEnabled(boolean) 15391 * @see #setHorizontalFadingEdgeEnabled(boolean) 15392 * 15393 * @return The known solid color background for this view, or 0 if the color may vary 15394 */ 15395 @ViewDebug.ExportedProperty(category = "drawing") 15396 public int getSolidColor() { 15397 return 0; 15398 } 15399 15400 /** 15401 * Build a human readable string representation of the specified view flags. 15402 * 15403 * @param flags the view flags to convert to a string 15404 * @return a String representing the supplied flags 15405 */ 15406 private static String printFlags(int flags) { 15407 String output = ""; 15408 int numFlags = 0; 15409 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 15410 output += "TAKES_FOCUS"; 15411 numFlags++; 15412 } 15413 15414 switch (flags & VISIBILITY_MASK) { 15415 case INVISIBLE: 15416 if (numFlags > 0) { 15417 output += " "; 15418 } 15419 output += "INVISIBLE"; 15420 // USELESS HERE numFlags++; 15421 break; 15422 case GONE: 15423 if (numFlags > 0) { 15424 output += " "; 15425 } 15426 output += "GONE"; 15427 // USELESS HERE numFlags++; 15428 break; 15429 default: 15430 break; 15431 } 15432 return output; 15433 } 15434 15435 /** 15436 * Build a human readable string representation of the specified private 15437 * view flags. 15438 * 15439 * @param privateFlags the private view flags to convert to a string 15440 * @return a String representing the supplied flags 15441 */ 15442 private static String printPrivateFlags(int privateFlags) { 15443 String output = ""; 15444 int numFlags = 0; 15445 15446 if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) { 15447 output += "WANTS_FOCUS"; 15448 numFlags++; 15449 } 15450 15451 if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) { 15452 if (numFlags > 0) { 15453 output += " "; 15454 } 15455 output += "FOCUSED"; 15456 numFlags++; 15457 } 15458 15459 if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) { 15460 if (numFlags > 0) { 15461 output += " "; 15462 } 15463 output += "SELECTED"; 15464 numFlags++; 15465 } 15466 15467 if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) { 15468 if (numFlags > 0) { 15469 output += " "; 15470 } 15471 output += "IS_ROOT_NAMESPACE"; 15472 numFlags++; 15473 } 15474 15475 if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) { 15476 if (numFlags > 0) { 15477 output += " "; 15478 } 15479 output += "HAS_BOUNDS"; 15480 numFlags++; 15481 } 15482 15483 if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) { 15484 if (numFlags > 0) { 15485 output += " "; 15486 } 15487 output += "DRAWN"; 15488 // USELESS HERE numFlags++; 15489 } 15490 return output; 15491 } 15492 15493 /** 15494 * <p>Indicates whether or not this view's layout will be requested during 15495 * the next hierarchy layout pass.</p> 15496 * 15497 * @return true if the layout will be forced during next layout pass 15498 */ 15499 public boolean isLayoutRequested() { 15500 return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 15501 } 15502 15503 /** 15504 * Return true if o is a ViewGroup that is laying out using optical bounds. 15505 * @hide 15506 */ 15507 public static boolean isLayoutModeOptical(Object o) { 15508 return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical(); 15509 } 15510 15511 private boolean setOpticalFrame(int left, int top, int right, int bottom) { 15512 Insets parentInsets = mParent instanceof View ? 15513 ((View) mParent).getOpticalInsets() : Insets.NONE; 15514 Insets childInsets = getOpticalInsets(); 15515 return setFrame( 15516 left + parentInsets.left - childInsets.left, 15517 top + parentInsets.top - childInsets.top, 15518 right + parentInsets.left + childInsets.right, 15519 bottom + parentInsets.top + childInsets.bottom); 15520 } 15521 15522 /** 15523 * Assign a size and position to a view and all of its 15524 * descendants 15525 * 15526 * <p>This is the second phase of the layout mechanism. 15527 * (The first is measuring). In this phase, each parent calls 15528 * layout on all of its children to position them. 15529 * This is typically done using the child measurements 15530 * that were stored in the measure pass().</p> 15531 * 15532 * <p>Derived classes should not override this method. 15533 * Derived classes with children should override 15534 * onLayout. In that method, they should 15535 * call layout on each of their children.</p> 15536 * 15537 * @param l Left position, relative to parent 15538 * @param t Top position, relative to parent 15539 * @param r Right position, relative to parent 15540 * @param b Bottom position, relative to parent 15541 */ 15542 @SuppressWarnings({"unchecked"}) 15543 public void layout(int l, int t, int r, int b) { 15544 if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) { 15545 onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec); 15546 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 15547 } 15548 15549 int oldL = mLeft; 15550 int oldT = mTop; 15551 int oldB = mBottom; 15552 int oldR = mRight; 15553 15554 boolean changed = isLayoutModeOptical(mParent) ? 15555 setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b); 15556 15557 if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) { 15558 onLayout(changed, l, t, r, b); 15559 mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED; 15560 15561 ListenerInfo li = mListenerInfo; 15562 if (li != null && li.mOnLayoutChangeListeners != null) { 15563 ArrayList<OnLayoutChangeListener> listenersCopy = 15564 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 15565 int numListeners = listenersCopy.size(); 15566 for (int i = 0; i < numListeners; ++i) { 15567 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 15568 } 15569 } 15570 } 15571 15572 mPrivateFlags &= ~PFLAG_FORCE_LAYOUT; 15573 mPrivateFlags3 |= PFLAG3_IS_LAID_OUT; 15574 } 15575 15576 /** 15577 * Called from layout when this view should 15578 * assign a size and position to each of its children. 15579 * 15580 * Derived classes with children should override 15581 * this method and call layout on each of 15582 * their children. 15583 * @param changed This is a new size or position for this view 15584 * @param left Left position, relative to parent 15585 * @param top Top position, relative to parent 15586 * @param right Right position, relative to parent 15587 * @param bottom Bottom position, relative to parent 15588 */ 15589 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 15590 } 15591 15592 /** 15593 * Assign a size and position to this view. 15594 * 15595 * This is called from layout. 15596 * 15597 * @param left Left position, relative to parent 15598 * @param top Top position, relative to parent 15599 * @param right Right position, relative to parent 15600 * @param bottom Bottom position, relative to parent 15601 * @return true if the new size and position are different than the 15602 * previous ones 15603 * {@hide} 15604 */ 15605 protected boolean setFrame(int left, int top, int right, int bottom) { 15606 boolean changed = false; 15607 15608 if (DBG) { 15609 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 15610 + right + "," + bottom + ")"); 15611 } 15612 15613 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 15614 changed = true; 15615 15616 // Remember our drawn bit 15617 int drawn = mPrivateFlags & PFLAG_DRAWN; 15618 15619 int oldWidth = mRight - mLeft; 15620 int oldHeight = mBottom - mTop; 15621 int newWidth = right - left; 15622 int newHeight = bottom - top; 15623 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 15624 15625 // Invalidate our old position 15626 invalidate(sizeChanged); 15627 15628 mLeft = left; 15629 mTop = top; 15630 mRight = right; 15631 mBottom = bottom; 15632 mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 15633 15634 mPrivateFlags |= PFLAG_HAS_BOUNDS; 15635 15636 15637 if (sizeChanged) { 15638 sizeChange(newWidth, newHeight, oldWidth, oldHeight); 15639 } 15640 15641 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) { 15642 // If we are visible, force the DRAWN bit to on so that 15643 // this invalidate will go through (at least to our parent). 15644 // This is because someone may have invalidated this view 15645 // before this call to setFrame came in, thereby clearing 15646 // the DRAWN bit. 15647 mPrivateFlags |= PFLAG_DRAWN; 15648 invalidate(sizeChanged); 15649 // parent display list may need to be recreated based on a change in the bounds 15650 // of any child 15651 invalidateParentCaches(); 15652 } 15653 15654 // Reset drawn bit to original value (invalidate turns it off) 15655 mPrivateFlags |= drawn; 15656 15657 mBackgroundSizeChanged = true; 15658 15659 notifySubtreeAccessibilityStateChangedIfNeeded(); 15660 } 15661 return changed; 15662 } 15663 15664 private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) { 15665 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 15666 if (mOverlay != null) { 15667 mOverlay.getOverlayView().setRight(newWidth); 15668 mOverlay.getOverlayView().setBottom(newHeight); 15669 } 15670 invalidateOutline(); 15671 } 15672 15673 /** 15674 * Finalize inflating a view from XML. This is called as the last phase 15675 * of inflation, after all child views have been added. 15676 * 15677 * <p>Even if the subclass overrides onFinishInflate, they should always be 15678 * sure to call the super method, so that we get called. 15679 */ 15680 protected void onFinishInflate() { 15681 } 15682 15683 /** 15684 * Returns the resources associated with this view. 15685 * 15686 * @return Resources object. 15687 */ 15688 public Resources getResources() { 15689 return mResources; 15690 } 15691 15692 /** 15693 * Invalidates the specified Drawable. 15694 * 15695 * @param drawable the drawable to invalidate 15696 */ 15697 @Override 15698 public void invalidateDrawable(@NonNull Drawable drawable) { 15699 if (verifyDrawable(drawable)) { 15700 final Rect dirty = drawable.getDirtyBounds(); 15701 final int scrollX = mScrollX; 15702 final int scrollY = mScrollY; 15703 15704 invalidate(dirty.left + scrollX, dirty.top + scrollY, 15705 dirty.right + scrollX, dirty.bottom + scrollY); 15706 15707 invalidateOutline(); 15708 } 15709 } 15710 15711 /** 15712 * Schedules an action on a drawable to occur at a specified time. 15713 * 15714 * @param who the recipient of the action 15715 * @param what the action to run on the drawable 15716 * @param when the time at which the action must occur. Uses the 15717 * {@link SystemClock#uptimeMillis} timebase. 15718 */ 15719 @Override 15720 public void scheduleDrawable(Drawable who, Runnable what, long when) { 15721 if (verifyDrawable(who) && what != null) { 15722 final long delay = when - SystemClock.uptimeMillis(); 15723 if (mAttachInfo != null) { 15724 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 15725 Choreographer.CALLBACK_ANIMATION, what, who, 15726 Choreographer.subtractFrameDelay(delay)); 15727 } else { 15728 ViewRootImpl.getRunQueue().postDelayed(what, delay); 15729 } 15730 } 15731 } 15732 15733 /** 15734 * Cancels a scheduled action on a drawable. 15735 * 15736 * @param who the recipient of the action 15737 * @param what the action to cancel 15738 */ 15739 @Override 15740 public void unscheduleDrawable(Drawable who, Runnable what) { 15741 if (verifyDrawable(who) && what != null) { 15742 if (mAttachInfo != null) { 15743 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 15744 Choreographer.CALLBACK_ANIMATION, what, who); 15745 } 15746 ViewRootImpl.getRunQueue().removeCallbacks(what); 15747 } 15748 } 15749 15750 /** 15751 * Unschedule any events associated with the given Drawable. This can be 15752 * used when selecting a new Drawable into a view, so that the previous 15753 * one is completely unscheduled. 15754 * 15755 * @param who The Drawable to unschedule. 15756 * 15757 * @see #drawableStateChanged 15758 */ 15759 public void unscheduleDrawable(Drawable who) { 15760 if (mAttachInfo != null && who != null) { 15761 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 15762 Choreographer.CALLBACK_ANIMATION, null, who); 15763 } 15764 } 15765 15766 /** 15767 * Resolve the Drawables depending on the layout direction. This is implicitly supposing 15768 * that the View directionality can and will be resolved before its Drawables. 15769 * 15770 * Will call {@link View#onResolveDrawables} when resolution is done. 15771 * 15772 * @hide 15773 */ 15774 protected void resolveDrawables() { 15775 // Drawables resolution may need to happen before resolving the layout direction (which is 15776 // done only during the measure() call). 15777 // If the layout direction is not resolved yet, we cannot resolve the Drawables except in 15778 // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT. 15779 // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or 15780 // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout 15781 // direction to be resolved as its resolved value will be the same as its raw value. 15782 if (!isLayoutDirectionResolved() && 15783 getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) { 15784 return; 15785 } 15786 15787 final int layoutDirection = isLayoutDirectionResolved() ? 15788 getLayoutDirection() : getRawLayoutDirection(); 15789 15790 if (mBackground != null) { 15791 mBackground.setLayoutDirection(layoutDirection); 15792 } 15793 mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED; 15794 onResolveDrawables(layoutDirection); 15795 } 15796 15797 /** 15798 * Called when layout direction has been resolved. 15799 * 15800 * The default implementation does nothing. 15801 * 15802 * @param layoutDirection The resolved layout direction. 15803 * 15804 * @see #LAYOUT_DIRECTION_LTR 15805 * @see #LAYOUT_DIRECTION_RTL 15806 * 15807 * @hide 15808 */ 15809 public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) { 15810 } 15811 15812 /** 15813 * @hide 15814 */ 15815 protected void resetResolvedDrawables() { 15816 mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED; 15817 } 15818 15819 private boolean isDrawablesResolved() { 15820 return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED; 15821 } 15822 15823 /** 15824 * If your view subclass is displaying its own Drawable objects, it should 15825 * override this function and return true for any Drawable it is 15826 * displaying. This allows animations for those drawables to be 15827 * scheduled. 15828 * 15829 * <p>Be sure to call through to the super class when overriding this 15830 * function. 15831 * 15832 * @param who The Drawable to verify. Return true if it is one you are 15833 * displaying, else return the result of calling through to the 15834 * super class. 15835 * 15836 * @return boolean If true than the Drawable is being displayed in the 15837 * view; else false and it is not allowed to animate. 15838 * 15839 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 15840 * @see #drawableStateChanged() 15841 */ 15842 protected boolean verifyDrawable(Drawable who) { 15843 return who == mBackground; 15844 } 15845 15846 /** 15847 * This function is called whenever the state of the view changes in such 15848 * a way that it impacts the state of drawables being shown. 15849 * <p> 15850 * If the View has a StateListAnimator, it will also be called to run necessary state 15851 * change animations. 15852 * <p> 15853 * Be sure to call through to the superclass when overriding this function. 15854 * 15855 * @see Drawable#setState(int[]) 15856 */ 15857 protected void drawableStateChanged() { 15858 final Drawable d = mBackground; 15859 if (d != null && d.isStateful()) { 15860 d.setState(getDrawableState()); 15861 } 15862 15863 if (mStateListAnimator != null) { 15864 mStateListAnimator.setState(getDrawableState()); 15865 } 15866 } 15867 15868 /** 15869 * This function is called whenever the view hotspot changes and needs to 15870 * be propagated to drawables managed by the view. 15871 * <p> 15872 * Be sure to call through to the superclass when overriding this function. 15873 * 15874 * @param x hotspot x coordinate 15875 * @param y hotspot y coordinate 15876 */ 15877 public void drawableHotspotChanged(float x, float y) { 15878 if (mBackground != null) { 15879 mBackground.setHotspot(x, y); 15880 } 15881 } 15882 15883 /** 15884 * Call this to force a view to update its drawable state. This will cause 15885 * drawableStateChanged to be called on this view. Views that are interested 15886 * in the new state should call getDrawableState. 15887 * 15888 * @see #drawableStateChanged 15889 * @see #getDrawableState 15890 */ 15891 public void refreshDrawableState() { 15892 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 15893 drawableStateChanged(); 15894 15895 ViewParent parent = mParent; 15896 if (parent != null) { 15897 parent.childDrawableStateChanged(this); 15898 } 15899 } 15900 15901 /** 15902 * Return an array of resource IDs of the drawable states representing the 15903 * current state of the view. 15904 * 15905 * @return The current drawable state 15906 * 15907 * @see Drawable#setState(int[]) 15908 * @see #drawableStateChanged() 15909 * @see #onCreateDrawableState(int) 15910 */ 15911 public final int[] getDrawableState() { 15912 if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) { 15913 return mDrawableState; 15914 } else { 15915 mDrawableState = onCreateDrawableState(0); 15916 mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY; 15917 return mDrawableState; 15918 } 15919 } 15920 15921 /** 15922 * Generate the new {@link android.graphics.drawable.Drawable} state for 15923 * this view. This is called by the view 15924 * system when the cached Drawable state is determined to be invalid. To 15925 * retrieve the current state, you should use {@link #getDrawableState}. 15926 * 15927 * @param extraSpace if non-zero, this is the number of extra entries you 15928 * would like in the returned array in which you can place your own 15929 * states. 15930 * 15931 * @return Returns an array holding the current {@link Drawable} state of 15932 * the view. 15933 * 15934 * @see #mergeDrawableStates(int[], int[]) 15935 */ 15936 protected int[] onCreateDrawableState(int extraSpace) { 15937 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 15938 mParent instanceof View) { 15939 return ((View) mParent).onCreateDrawableState(extraSpace); 15940 } 15941 15942 int[] drawableState; 15943 15944 int privateFlags = mPrivateFlags; 15945 15946 int viewStateIndex = 0; 15947 if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED; 15948 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED; 15949 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED; 15950 if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED; 15951 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED; 15952 if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED; 15953 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 15954 HardwareRenderer.isAvailable()) { 15955 // This is set if HW acceleration is requested, even if the current 15956 // process doesn't allow it. This is just to allow app preview 15957 // windows to better match their app. 15958 viewStateIndex |= VIEW_STATE_ACCELERATED; 15959 } 15960 if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED; 15961 15962 final int privateFlags2 = mPrivateFlags2; 15963 if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT; 15964 if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED; 15965 15966 drawableState = VIEW_STATE_SETS[viewStateIndex]; 15967 15968 //noinspection ConstantIfStatement 15969 if (false) { 15970 Log.i("View", "drawableStateIndex=" + viewStateIndex); 15971 Log.i("View", toString() 15972 + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0) 15973 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 15974 + " fo=" + hasFocus() 15975 + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0) 15976 + " wf=" + hasWindowFocus() 15977 + ": " + Arrays.toString(drawableState)); 15978 } 15979 15980 if (extraSpace == 0) { 15981 return drawableState; 15982 } 15983 15984 final int[] fullState; 15985 if (drawableState != null) { 15986 fullState = new int[drawableState.length + extraSpace]; 15987 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 15988 } else { 15989 fullState = new int[extraSpace]; 15990 } 15991 15992 return fullState; 15993 } 15994 15995 /** 15996 * Merge your own state values in <var>additionalState</var> into the base 15997 * state values <var>baseState</var> that were returned by 15998 * {@link #onCreateDrawableState(int)}. 15999 * 16000 * @param baseState The base state values returned by 16001 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 16002 * own additional state values. 16003 * 16004 * @param additionalState The additional state values you would like 16005 * added to <var>baseState</var>; this array is not modified. 16006 * 16007 * @return As a convenience, the <var>baseState</var> array you originally 16008 * passed into the function is returned. 16009 * 16010 * @see #onCreateDrawableState(int) 16011 */ 16012 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 16013 final int N = baseState.length; 16014 int i = N - 1; 16015 while (i >= 0 && baseState[i] == 0) { 16016 i--; 16017 } 16018 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 16019 return baseState; 16020 } 16021 16022 /** 16023 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 16024 * on all Drawable objects associated with this view. 16025 * <p> 16026 * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator 16027 * attached to this view. 16028 */ 16029 public void jumpDrawablesToCurrentState() { 16030 if (mBackground != null) { 16031 mBackground.jumpToCurrentState(); 16032 } 16033 if (mStateListAnimator != null) { 16034 mStateListAnimator.jumpToCurrentState(); 16035 } 16036 } 16037 16038 /** 16039 * Sets the background color for this view. 16040 * @param color the color of the background 16041 */ 16042 @RemotableViewMethod 16043 public void setBackgroundColor(int color) { 16044 if (mBackground instanceof ColorDrawable) { 16045 ((ColorDrawable) mBackground.mutate()).setColor(color); 16046 computeOpaqueFlags(); 16047 mBackgroundResource = 0; 16048 } else { 16049 setBackground(new ColorDrawable(color)); 16050 } 16051 } 16052 16053 /** 16054 * Set the background to a given resource. The resource should refer to 16055 * a Drawable object or 0 to remove the background. 16056 * @param resid The identifier of the resource. 16057 * 16058 * @attr ref android.R.styleable#View_background 16059 */ 16060 @RemotableViewMethod 16061 public void setBackgroundResource(int resid) { 16062 if (resid != 0 && resid == mBackgroundResource) { 16063 return; 16064 } 16065 16066 Drawable d = null; 16067 if (resid != 0) { 16068 d = mContext.getDrawable(resid); 16069 } 16070 setBackground(d); 16071 16072 mBackgroundResource = resid; 16073 } 16074 16075 /** 16076 * Set the background to a given Drawable, or remove the background. If the 16077 * background has padding, this View's padding is set to the background's 16078 * padding. However, when a background is removed, this View's padding isn't 16079 * touched. If setting the padding is desired, please use 16080 * {@link #setPadding(int, int, int, int)}. 16081 * 16082 * @param background The Drawable to use as the background, or null to remove the 16083 * background 16084 */ 16085 public void setBackground(Drawable background) { 16086 //noinspection deprecation 16087 setBackgroundDrawable(background); 16088 } 16089 16090 /** 16091 * @deprecated use {@link #setBackground(Drawable)} instead 16092 */ 16093 @Deprecated 16094 public void setBackgroundDrawable(Drawable background) { 16095 computeOpaqueFlags(); 16096 16097 if (background == mBackground) { 16098 return; 16099 } 16100 16101 boolean requestLayout = false; 16102 16103 mBackgroundResource = 0; 16104 16105 /* 16106 * Regardless of whether we're setting a new background or not, we want 16107 * to clear the previous drawable. 16108 */ 16109 if (mBackground != null) { 16110 mBackground.setCallback(null); 16111 unscheduleDrawable(mBackground); 16112 } 16113 16114 if (background != null) { 16115 Rect padding = sThreadLocal.get(); 16116 if (padding == null) { 16117 padding = new Rect(); 16118 sThreadLocal.set(padding); 16119 } 16120 resetResolvedDrawables(); 16121 background.setLayoutDirection(getLayoutDirection()); 16122 if (background.getPadding(padding)) { 16123 resetResolvedPadding(); 16124 switch (background.getLayoutDirection()) { 16125 case LAYOUT_DIRECTION_RTL: 16126 mUserPaddingLeftInitial = padding.right; 16127 mUserPaddingRightInitial = padding.left; 16128 internalSetPadding(padding.right, padding.top, padding.left, padding.bottom); 16129 break; 16130 case LAYOUT_DIRECTION_LTR: 16131 default: 16132 mUserPaddingLeftInitial = padding.left; 16133 mUserPaddingRightInitial = padding.right; 16134 internalSetPadding(padding.left, padding.top, padding.right, padding.bottom); 16135 } 16136 mLeftPaddingDefined = false; 16137 mRightPaddingDefined = false; 16138 } 16139 16140 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 16141 // if it has a different minimum size, we should layout again 16142 if (mBackground == null 16143 || mBackground.getMinimumHeight() != background.getMinimumHeight() 16144 || mBackground.getMinimumWidth() != background.getMinimumWidth()) { 16145 requestLayout = true; 16146 } 16147 16148 background.setCallback(this); 16149 if (background.isStateful()) { 16150 background.setState(getDrawableState()); 16151 } 16152 background.setVisible(getVisibility() == VISIBLE, false); 16153 mBackground = background; 16154 16155 applyBackgroundTint(); 16156 16157 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 16158 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 16159 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 16160 requestLayout = true; 16161 } 16162 } else { 16163 /* Remove the background */ 16164 mBackground = null; 16165 16166 if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) { 16167 /* 16168 * This view ONLY drew the background before and we're removing 16169 * the background, so now it won't draw anything 16170 * (hence we SKIP_DRAW) 16171 */ 16172 mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND; 16173 mPrivateFlags |= PFLAG_SKIP_DRAW; 16174 } 16175 16176 /* 16177 * When the background is set, we try to apply its padding to this 16178 * View. When the background is removed, we don't touch this View's 16179 * padding. This is noted in the Javadocs. Hence, we don't need to 16180 * requestLayout(), the invalidate() below is sufficient. 16181 */ 16182 16183 // The old background's minimum size could have affected this 16184 // View's layout, so let's requestLayout 16185 requestLayout = true; 16186 } 16187 16188 computeOpaqueFlags(); 16189 16190 if (requestLayout) { 16191 requestLayout(); 16192 } 16193 16194 mBackgroundSizeChanged = true; 16195 invalidate(true); 16196 } 16197 16198 /** 16199 * Gets the background drawable 16200 * 16201 * @return The drawable used as the background for this view, if any. 16202 * 16203 * @see #setBackground(Drawable) 16204 * 16205 * @attr ref android.R.styleable#View_background 16206 */ 16207 public Drawable getBackground() { 16208 return mBackground; 16209 } 16210 16211 /** 16212 * Applies a tint to the background drawable. Does not modify the current tint 16213 * mode, which is {@link PorterDuff.Mode#SRC_ATOP} by default. 16214 * <p> 16215 * Subsequent calls to {@link #setBackground(Drawable)} will automatically 16216 * mutate the drawable and apply the specified tint and tint mode using 16217 * {@link Drawable#setTintList(ColorStateList)}. 16218 * 16219 * @param tint the tint to apply, may be {@code null} to clear tint 16220 * 16221 * @attr ref android.R.styleable#View_backgroundTint 16222 * @see #getBackgroundTintList() 16223 * @see Drawable#setTintList(ColorStateList) 16224 */ 16225 public void setBackgroundTintList(@Nullable ColorStateList tint) { 16226 mBackgroundTintList = tint; 16227 mHasBackgroundTint = true; 16228 16229 applyBackgroundTint(); 16230 } 16231 16232 /** 16233 * @return the tint applied to the background drawable 16234 * @attr ref android.R.styleable#View_backgroundTint 16235 * @see #setBackgroundTintList(ColorStateList) 16236 */ 16237 @Nullable 16238 public ColorStateList getBackgroundTintList() { 16239 return mBackgroundTintList; 16240 } 16241 16242 /** 16243 * Specifies the blending mode used to apply the tint specified by 16244 * {@link #setBackgroundTintList(ColorStateList)}} to the background drawable. 16245 * The default mode is {@link PorterDuff.Mode#SRC_ATOP}. 16246 * 16247 * @param tintMode the blending mode used to apply the tint, may be 16248 * {@code null} to clear tint 16249 * @attr ref android.R.styleable#View_backgroundTintMode 16250 * @see #getBackgroundTintMode() 16251 * @see Drawable#setTintMode(PorterDuff.Mode) 16252 */ 16253 public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) { 16254 mBackgroundTintMode = tintMode; 16255 16256 applyBackgroundTint(); 16257 } 16258 16259 /** 16260 * @return the blending mode used to apply the tint to the background drawable 16261 * @attr ref android.R.styleable#View_backgroundTintMode 16262 * @see #setBackgroundTintMode(PorterDuff.Mode) 16263 */ 16264 @Nullable 16265 public PorterDuff.Mode getBackgroundTintMode() { 16266 return mBackgroundTintMode; 16267 } 16268 16269 private void applyBackgroundTint() { 16270 if (mBackground != null && mHasBackgroundTint) { 16271 mBackground = mBackground.mutate(); 16272 mBackground.setTintList(mBackgroundTintList); 16273 mBackground.setTintMode(mBackgroundTintMode); 16274 } 16275 } 16276 16277 /** 16278 * Sets the padding. The view may add on the space required to display 16279 * the scrollbars, depending on the style and visibility of the scrollbars. 16280 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 16281 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 16282 * from the values set in this call. 16283 * 16284 * @attr ref android.R.styleable#View_padding 16285 * @attr ref android.R.styleable#View_paddingBottom 16286 * @attr ref android.R.styleable#View_paddingLeft 16287 * @attr ref android.R.styleable#View_paddingRight 16288 * @attr ref android.R.styleable#View_paddingTop 16289 * @param left the left padding in pixels 16290 * @param top the top padding in pixels 16291 * @param right the right padding in pixels 16292 * @param bottom the bottom padding in pixels 16293 */ 16294 public void setPadding(int left, int top, int right, int bottom) { 16295 resetResolvedPadding(); 16296 16297 mUserPaddingStart = UNDEFINED_PADDING; 16298 mUserPaddingEnd = UNDEFINED_PADDING; 16299 16300 mUserPaddingLeftInitial = left; 16301 mUserPaddingRightInitial = right; 16302 16303 mLeftPaddingDefined = true; 16304 mRightPaddingDefined = true; 16305 16306 internalSetPadding(left, top, right, bottom); 16307 } 16308 16309 /** 16310 * @hide 16311 */ 16312 protected void internalSetPadding(int left, int top, int right, int bottom) { 16313 mUserPaddingLeft = left; 16314 mUserPaddingRight = right; 16315 mUserPaddingBottom = bottom; 16316 16317 final int viewFlags = mViewFlags; 16318 boolean changed = false; 16319 16320 // Common case is there are no scroll bars. 16321 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 16322 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 16323 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 16324 ? 0 : getVerticalScrollbarWidth(); 16325 switch (mVerticalScrollbarPosition) { 16326 case SCROLLBAR_POSITION_DEFAULT: 16327 if (isLayoutRtl()) { 16328 left += offset; 16329 } else { 16330 right += offset; 16331 } 16332 break; 16333 case SCROLLBAR_POSITION_RIGHT: 16334 right += offset; 16335 break; 16336 case SCROLLBAR_POSITION_LEFT: 16337 left += offset; 16338 break; 16339 } 16340 } 16341 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 16342 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 16343 ? 0 : getHorizontalScrollbarHeight(); 16344 } 16345 } 16346 16347 if (mPaddingLeft != left) { 16348 changed = true; 16349 mPaddingLeft = left; 16350 } 16351 if (mPaddingTop != top) { 16352 changed = true; 16353 mPaddingTop = top; 16354 } 16355 if (mPaddingRight != right) { 16356 changed = true; 16357 mPaddingRight = right; 16358 } 16359 if (mPaddingBottom != bottom) { 16360 changed = true; 16361 mPaddingBottom = bottom; 16362 } 16363 16364 if (changed) { 16365 requestLayout(); 16366 } 16367 } 16368 16369 /** 16370 * Sets the relative padding. The view may add on the space required to display 16371 * the scrollbars, depending on the style and visibility of the scrollbars. 16372 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 16373 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 16374 * from the values set in this call. 16375 * 16376 * @attr ref android.R.styleable#View_padding 16377 * @attr ref android.R.styleable#View_paddingBottom 16378 * @attr ref android.R.styleable#View_paddingStart 16379 * @attr ref android.R.styleable#View_paddingEnd 16380 * @attr ref android.R.styleable#View_paddingTop 16381 * @param start the start padding in pixels 16382 * @param top the top padding in pixels 16383 * @param end the end padding in pixels 16384 * @param bottom the bottom padding in pixels 16385 */ 16386 public void setPaddingRelative(int start, int top, int end, int bottom) { 16387 resetResolvedPadding(); 16388 16389 mUserPaddingStart = start; 16390 mUserPaddingEnd = end; 16391 mLeftPaddingDefined = true; 16392 mRightPaddingDefined = true; 16393 16394 switch(getLayoutDirection()) { 16395 case LAYOUT_DIRECTION_RTL: 16396 mUserPaddingLeftInitial = end; 16397 mUserPaddingRightInitial = start; 16398 internalSetPadding(end, top, start, bottom); 16399 break; 16400 case LAYOUT_DIRECTION_LTR: 16401 default: 16402 mUserPaddingLeftInitial = start; 16403 mUserPaddingRightInitial = end; 16404 internalSetPadding(start, top, end, bottom); 16405 } 16406 } 16407 16408 /** 16409 * Returns the top padding of this view. 16410 * 16411 * @return the top padding in pixels 16412 */ 16413 public int getPaddingTop() { 16414 return mPaddingTop; 16415 } 16416 16417 /** 16418 * Returns the bottom padding of this view. If there are inset and enabled 16419 * scrollbars, this value may include the space required to display the 16420 * scrollbars as well. 16421 * 16422 * @return the bottom padding in pixels 16423 */ 16424 public int getPaddingBottom() { 16425 return mPaddingBottom; 16426 } 16427 16428 /** 16429 * Returns the left padding of this view. If there are inset and enabled 16430 * scrollbars, this value may include the space required to display the 16431 * scrollbars as well. 16432 * 16433 * @return the left padding in pixels 16434 */ 16435 public int getPaddingLeft() { 16436 if (!isPaddingResolved()) { 16437 resolvePadding(); 16438 } 16439 return mPaddingLeft; 16440 } 16441 16442 /** 16443 * Returns the start padding of this view depending on its resolved layout direction. 16444 * If there are inset and enabled scrollbars, this value may include the space 16445 * required to display the scrollbars as well. 16446 * 16447 * @return the start padding in pixels 16448 */ 16449 public int getPaddingStart() { 16450 if (!isPaddingResolved()) { 16451 resolvePadding(); 16452 } 16453 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 16454 mPaddingRight : mPaddingLeft; 16455 } 16456 16457 /** 16458 * Returns the right padding of this view. If there are inset and enabled 16459 * scrollbars, this value may include the space required to display the 16460 * scrollbars as well. 16461 * 16462 * @return the right padding in pixels 16463 */ 16464 public int getPaddingRight() { 16465 if (!isPaddingResolved()) { 16466 resolvePadding(); 16467 } 16468 return mPaddingRight; 16469 } 16470 16471 /** 16472 * Returns the end padding of this view depending on its resolved layout direction. 16473 * If there are inset and enabled scrollbars, this value may include the space 16474 * required to display the scrollbars as well. 16475 * 16476 * @return the end padding in pixels 16477 */ 16478 public int getPaddingEnd() { 16479 if (!isPaddingResolved()) { 16480 resolvePadding(); 16481 } 16482 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 16483 mPaddingLeft : mPaddingRight; 16484 } 16485 16486 /** 16487 * Return if the padding as been set thru relative values 16488 * {@link #setPaddingRelative(int, int, int, int)} or thru 16489 * @attr ref android.R.styleable#View_paddingStart or 16490 * @attr ref android.R.styleable#View_paddingEnd 16491 * 16492 * @return true if the padding is relative or false if it is not. 16493 */ 16494 public boolean isPaddingRelative() { 16495 return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING); 16496 } 16497 16498 Insets computeOpticalInsets() { 16499 return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets(); 16500 } 16501 16502 /** 16503 * @hide 16504 */ 16505 public void resetPaddingToInitialValues() { 16506 if (isRtlCompatibilityMode()) { 16507 mPaddingLeft = mUserPaddingLeftInitial; 16508 mPaddingRight = mUserPaddingRightInitial; 16509 return; 16510 } 16511 if (isLayoutRtl()) { 16512 mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial; 16513 mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial; 16514 } else { 16515 mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial; 16516 mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial; 16517 } 16518 } 16519 16520 /** 16521 * @hide 16522 */ 16523 public Insets getOpticalInsets() { 16524 if (mLayoutInsets == null) { 16525 mLayoutInsets = computeOpticalInsets(); 16526 } 16527 return mLayoutInsets; 16528 } 16529 16530 /** 16531 * Set this view's optical insets. 16532 * 16533 * <p>This method should be treated similarly to setMeasuredDimension and not as a general 16534 * property. Views that compute their own optical insets should call it as part of measurement. 16535 * This method does not request layout. If you are setting optical insets outside of 16536 * measure/layout itself you will want to call requestLayout() yourself. 16537 * </p> 16538 * @hide 16539 */ 16540 public void setOpticalInsets(Insets insets) { 16541 mLayoutInsets = insets; 16542 } 16543 16544 /** 16545 * Changes the selection state of this view. A view can be selected or not. 16546 * Note that selection is not the same as focus. Views are typically 16547 * selected in the context of an AdapterView like ListView or GridView; 16548 * the selected view is the view that is highlighted. 16549 * 16550 * @param selected true if the view must be selected, false otherwise 16551 */ 16552 public void setSelected(boolean selected) { 16553 //noinspection DoubleNegation 16554 if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) { 16555 mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0); 16556 if (!selected) resetPressedState(); 16557 invalidate(true); 16558 refreshDrawableState(); 16559 dispatchSetSelected(selected); 16560 notifyViewAccessibilityStateChangedIfNeeded( 16561 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 16562 } 16563 } 16564 16565 /** 16566 * Dispatch setSelected to all of this View's children. 16567 * 16568 * @see #setSelected(boolean) 16569 * 16570 * @param selected The new selected state 16571 */ 16572 protected void dispatchSetSelected(boolean selected) { 16573 } 16574 16575 /** 16576 * Indicates the selection state of this view. 16577 * 16578 * @return true if the view is selected, false otherwise 16579 */ 16580 @ViewDebug.ExportedProperty 16581 public boolean isSelected() { 16582 return (mPrivateFlags & PFLAG_SELECTED) != 0; 16583 } 16584 16585 /** 16586 * Changes the activated state of this view. A view can be activated or not. 16587 * Note that activation is not the same as selection. Selection is 16588 * a transient property, representing the view (hierarchy) the user is 16589 * currently interacting with. Activation is a longer-term state that the 16590 * user can move views in and out of. For example, in a list view with 16591 * single or multiple selection enabled, the views in the current selection 16592 * set are activated. (Um, yeah, we are deeply sorry about the terminology 16593 * here.) The activated state is propagated down to children of the view it 16594 * is set on. 16595 * 16596 * @param activated true if the view must be activated, false otherwise 16597 */ 16598 public void setActivated(boolean activated) { 16599 //noinspection DoubleNegation 16600 if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) { 16601 mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0); 16602 invalidate(true); 16603 refreshDrawableState(); 16604 dispatchSetActivated(activated); 16605 } 16606 } 16607 16608 /** 16609 * Dispatch setActivated to all of this View's children. 16610 * 16611 * @see #setActivated(boolean) 16612 * 16613 * @param activated The new activated state 16614 */ 16615 protected void dispatchSetActivated(boolean activated) { 16616 } 16617 16618 /** 16619 * Indicates the activation state of this view. 16620 * 16621 * @return true if the view is activated, false otherwise 16622 */ 16623 @ViewDebug.ExportedProperty 16624 public boolean isActivated() { 16625 return (mPrivateFlags & PFLAG_ACTIVATED) != 0; 16626 } 16627 16628 /** 16629 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 16630 * observer can be used to get notifications when global events, like 16631 * layout, happen. 16632 * 16633 * The returned ViewTreeObserver observer is not guaranteed to remain 16634 * valid for the lifetime of this View. If the caller of this method keeps 16635 * a long-lived reference to ViewTreeObserver, it should always check for 16636 * the return value of {@link ViewTreeObserver#isAlive()}. 16637 * 16638 * @return The ViewTreeObserver for this view's hierarchy. 16639 */ 16640 public ViewTreeObserver getViewTreeObserver() { 16641 if (mAttachInfo != null) { 16642 return mAttachInfo.mTreeObserver; 16643 } 16644 if (mFloatingTreeObserver == null) { 16645 mFloatingTreeObserver = new ViewTreeObserver(); 16646 } 16647 return mFloatingTreeObserver; 16648 } 16649 16650 /** 16651 * <p>Finds the topmost view in the current view hierarchy.</p> 16652 * 16653 * @return the topmost view containing this view 16654 */ 16655 public View getRootView() { 16656 if (mAttachInfo != null) { 16657 final View v = mAttachInfo.mRootView; 16658 if (v != null) { 16659 return v; 16660 } 16661 } 16662 16663 View parent = this; 16664 16665 while (parent.mParent != null && parent.mParent instanceof View) { 16666 parent = (View) parent.mParent; 16667 } 16668 16669 return parent; 16670 } 16671 16672 /** 16673 * Transforms a motion event from view-local coordinates to on-screen 16674 * coordinates. 16675 * 16676 * @param ev the view-local motion event 16677 * @return false if the transformation could not be applied 16678 * @hide 16679 */ 16680 public boolean toGlobalMotionEvent(MotionEvent ev) { 16681 final AttachInfo info = mAttachInfo; 16682 if (info == null) { 16683 return false; 16684 } 16685 16686 final Matrix m = info.mTmpMatrix; 16687 m.set(Matrix.IDENTITY_MATRIX); 16688 transformMatrixToGlobal(m); 16689 ev.transform(m); 16690 return true; 16691 } 16692 16693 /** 16694 * Transforms a motion event from on-screen coordinates to view-local 16695 * coordinates. 16696 * 16697 * @param ev the on-screen motion event 16698 * @return false if the transformation could not be applied 16699 * @hide 16700 */ 16701 public boolean toLocalMotionEvent(MotionEvent ev) { 16702 final AttachInfo info = mAttachInfo; 16703 if (info == null) { 16704 return false; 16705 } 16706 16707 final Matrix m = info.mTmpMatrix; 16708 m.set(Matrix.IDENTITY_MATRIX); 16709 transformMatrixToLocal(m); 16710 ev.transform(m); 16711 return true; 16712 } 16713 16714 /** 16715 * Modifies the input matrix such that it maps view-local coordinates to 16716 * on-screen coordinates. 16717 * 16718 * @param m input matrix to modify 16719 * @hide 16720 */ 16721 public void transformMatrixToGlobal(Matrix m) { 16722 final ViewParent parent = mParent; 16723 if (parent instanceof View) { 16724 final View vp = (View) parent; 16725 vp.transformMatrixToGlobal(m); 16726 m.preTranslate(-vp.mScrollX, -vp.mScrollY); 16727 } else if (parent instanceof ViewRootImpl) { 16728 final ViewRootImpl vr = (ViewRootImpl) parent; 16729 vr.transformMatrixToGlobal(m); 16730 m.preTranslate(0, -vr.mCurScrollY); 16731 } 16732 16733 m.preTranslate(mLeft, mTop); 16734 16735 if (!hasIdentityMatrix()) { 16736 m.preConcat(getMatrix()); 16737 } 16738 } 16739 16740 /** 16741 * Modifies the input matrix such that it maps on-screen coordinates to 16742 * view-local coordinates. 16743 * 16744 * @param m input matrix to modify 16745 * @hide 16746 */ 16747 public void transformMatrixToLocal(Matrix m) { 16748 final ViewParent parent = mParent; 16749 if (parent instanceof View) { 16750 final View vp = (View) parent; 16751 vp.transformMatrixToLocal(m); 16752 m.postTranslate(vp.mScrollX, vp.mScrollY); 16753 } else if (parent instanceof ViewRootImpl) { 16754 final ViewRootImpl vr = (ViewRootImpl) parent; 16755 vr.transformMatrixToLocal(m); 16756 m.postTranslate(0, vr.mCurScrollY); 16757 } 16758 16759 m.postTranslate(-mLeft, -mTop); 16760 16761 if (!hasIdentityMatrix()) { 16762 m.postConcat(getInverseMatrix()); 16763 } 16764 } 16765 16766 /** 16767 * @hide 16768 */ 16769 @ViewDebug.ExportedProperty(category = "layout", indexMapping = { 16770 @ViewDebug.IntToString(from = 0, to = "x"), 16771 @ViewDebug.IntToString(from = 1, to = "y") 16772 }) 16773 public int[] getLocationOnScreen() { 16774 int[] location = new int[2]; 16775 getLocationOnScreen(location); 16776 return location; 16777 } 16778 16779 /** 16780 * <p>Computes the coordinates of this view on the screen. The argument 16781 * must be an array of two integers. After the method returns, the array 16782 * contains the x and y location in that order.</p> 16783 * 16784 * @param location an array of two integers in which to hold the coordinates 16785 */ 16786 public void getLocationOnScreen(int[] location) { 16787 getLocationInWindow(location); 16788 16789 final AttachInfo info = mAttachInfo; 16790 if (info != null) { 16791 location[0] += info.mWindowLeft; 16792 location[1] += info.mWindowTop; 16793 } 16794 } 16795 16796 /** 16797 * <p>Computes the coordinates of this view in its window. The argument 16798 * must be an array of two integers. After the method returns, the array 16799 * contains the x and y location in that order.</p> 16800 * 16801 * @param location an array of two integers in which to hold the coordinates 16802 */ 16803 public void getLocationInWindow(int[] location) { 16804 if (location == null || location.length < 2) { 16805 throw new IllegalArgumentException("location must be an array of two integers"); 16806 } 16807 16808 if (mAttachInfo == null) { 16809 // When the view is not attached to a window, this method does not make sense 16810 location[0] = location[1] = 0; 16811 return; 16812 } 16813 16814 float[] position = mAttachInfo.mTmpTransformLocation; 16815 position[0] = position[1] = 0.0f; 16816 16817 if (!hasIdentityMatrix()) { 16818 getMatrix().mapPoints(position); 16819 } 16820 16821 position[0] += mLeft; 16822 position[1] += mTop; 16823 16824 ViewParent viewParent = mParent; 16825 while (viewParent instanceof View) { 16826 final View view = (View) viewParent; 16827 16828 position[0] -= view.mScrollX; 16829 position[1] -= view.mScrollY; 16830 16831 if (!view.hasIdentityMatrix()) { 16832 view.getMatrix().mapPoints(position); 16833 } 16834 16835 position[0] += view.mLeft; 16836 position[1] += view.mTop; 16837 16838 viewParent = view.mParent; 16839 } 16840 16841 if (viewParent instanceof ViewRootImpl) { 16842 // *cough* 16843 final ViewRootImpl vr = (ViewRootImpl) viewParent; 16844 position[1] -= vr.mCurScrollY; 16845 } 16846 16847 location[0] = (int) (position[0] + 0.5f); 16848 location[1] = (int) (position[1] + 0.5f); 16849 } 16850 16851 /** 16852 * {@hide} 16853 * @param id the id of the view to be found 16854 * @return the view of the specified id, null if cannot be found 16855 */ 16856 protected View findViewTraversal(int id) { 16857 if (id == mID) { 16858 return this; 16859 } 16860 return null; 16861 } 16862 16863 /** 16864 * {@hide} 16865 * @param tag the tag of the view to be found 16866 * @return the view of specified tag, null if cannot be found 16867 */ 16868 protected View findViewWithTagTraversal(Object tag) { 16869 if (tag != null && tag.equals(mTag)) { 16870 return this; 16871 } 16872 return null; 16873 } 16874 16875 /** 16876 * {@hide} 16877 * @param predicate The predicate to evaluate. 16878 * @param childToSkip If not null, ignores this child during the recursive traversal. 16879 * @return The first view that matches the predicate or null. 16880 */ 16881 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 16882 if (predicate.apply(this)) { 16883 return this; 16884 } 16885 return null; 16886 } 16887 16888 /** 16889 * Look for a child view with the given id. If this view has the given 16890 * id, return this view. 16891 * 16892 * @param id The id to search for. 16893 * @return The view that has the given id in the hierarchy or null 16894 */ 16895 public final View findViewById(int id) { 16896 if (id < 0) { 16897 return null; 16898 } 16899 return findViewTraversal(id); 16900 } 16901 16902 /** 16903 * Finds a view by its unuque and stable accessibility id. 16904 * 16905 * @param accessibilityId The searched accessibility id. 16906 * @return The found view. 16907 */ 16908 final View findViewByAccessibilityId(int accessibilityId) { 16909 if (accessibilityId < 0) { 16910 return null; 16911 } 16912 return findViewByAccessibilityIdTraversal(accessibilityId); 16913 } 16914 16915 /** 16916 * Performs the traversal to find a view by its unuque and stable accessibility id. 16917 * 16918 * <strong>Note:</strong>This method does not stop at the root namespace 16919 * boundary since the user can touch the screen at an arbitrary location 16920 * potentially crossing the root namespace bounday which will send an 16921 * accessibility event to accessibility services and they should be able 16922 * to obtain the event source. Also accessibility ids are guaranteed to be 16923 * unique in the window. 16924 * 16925 * @param accessibilityId The accessibility id. 16926 * @return The found view. 16927 * 16928 * @hide 16929 */ 16930 public View findViewByAccessibilityIdTraversal(int accessibilityId) { 16931 if (getAccessibilityViewId() == accessibilityId) { 16932 return this; 16933 } 16934 return null; 16935 } 16936 16937 /** 16938 * Look for a child view with the given tag. If this view has the given 16939 * tag, return this view. 16940 * 16941 * @param tag The tag to search for, using "tag.equals(getTag())". 16942 * @return The View that has the given tag in the hierarchy or null 16943 */ 16944 public final View findViewWithTag(Object tag) { 16945 if (tag == null) { 16946 return null; 16947 } 16948 return findViewWithTagTraversal(tag); 16949 } 16950 16951 /** 16952 * {@hide} 16953 * Look for a child view that matches the specified predicate. 16954 * If this view matches the predicate, return this view. 16955 * 16956 * @param predicate The predicate to evaluate. 16957 * @return The first view that matches the predicate or null. 16958 */ 16959 public final View findViewByPredicate(Predicate<View> predicate) { 16960 return findViewByPredicateTraversal(predicate, null); 16961 } 16962 16963 /** 16964 * {@hide} 16965 * Look for a child view that matches the specified predicate, 16966 * starting with the specified view and its descendents and then 16967 * recusively searching the ancestors and siblings of that view 16968 * until this view is reached. 16969 * 16970 * This method is useful in cases where the predicate does not match 16971 * a single unique view (perhaps multiple views use the same id) 16972 * and we are trying to find the view that is "closest" in scope to the 16973 * starting view. 16974 * 16975 * @param start The view to start from. 16976 * @param predicate The predicate to evaluate. 16977 * @return The first view that matches the predicate or null. 16978 */ 16979 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 16980 View childToSkip = null; 16981 for (;;) { 16982 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 16983 if (view != null || start == this) { 16984 return view; 16985 } 16986 16987 ViewParent parent = start.getParent(); 16988 if (parent == null || !(parent instanceof View)) { 16989 return null; 16990 } 16991 16992 childToSkip = start; 16993 start = (View) parent; 16994 } 16995 } 16996 16997 /** 16998 * Sets the identifier for this view. The identifier does not have to be 16999 * unique in this view's hierarchy. The identifier should be a positive 17000 * number. 17001 * 17002 * @see #NO_ID 17003 * @see #getId() 17004 * @see #findViewById(int) 17005 * 17006 * @param id a number used to identify the view 17007 * 17008 * @attr ref android.R.styleable#View_id 17009 */ 17010 public void setId(int id) { 17011 mID = id; 17012 if (mID == View.NO_ID && mLabelForId != View.NO_ID) { 17013 mID = generateViewId(); 17014 } 17015 } 17016 17017 /** 17018 * {@hide} 17019 * 17020 * @param isRoot true if the view belongs to the root namespace, false 17021 * otherwise 17022 */ 17023 public void setIsRootNamespace(boolean isRoot) { 17024 if (isRoot) { 17025 mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE; 17026 } else { 17027 mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE; 17028 } 17029 } 17030 17031 /** 17032 * {@hide} 17033 * 17034 * @return true if the view belongs to the root namespace, false otherwise 17035 */ 17036 public boolean isRootNamespace() { 17037 return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0; 17038 } 17039 17040 /** 17041 * Returns this view's identifier. 17042 * 17043 * @return a positive integer used to identify the view or {@link #NO_ID} 17044 * if the view has no ID 17045 * 17046 * @see #setId(int) 17047 * @see #findViewById(int) 17048 * @attr ref android.R.styleable#View_id 17049 */ 17050 @ViewDebug.CapturedViewProperty 17051 public int getId() { 17052 return mID; 17053 } 17054 17055 /** 17056 * Returns this view's tag. 17057 * 17058 * @return the Object stored in this view as a tag, or {@code null} if not 17059 * set 17060 * 17061 * @see #setTag(Object) 17062 * @see #getTag(int) 17063 */ 17064 @ViewDebug.ExportedProperty 17065 public Object getTag() { 17066 return mTag; 17067 } 17068 17069 /** 17070 * Sets the tag associated with this view. A tag can be used to mark 17071 * a view in its hierarchy and does not have to be unique within the 17072 * hierarchy. Tags can also be used to store data within a view without 17073 * resorting to another data structure. 17074 * 17075 * @param tag an Object to tag the view with 17076 * 17077 * @see #getTag() 17078 * @see #setTag(int, Object) 17079 */ 17080 public void setTag(final Object tag) { 17081 mTag = tag; 17082 } 17083 17084 /** 17085 * Returns the tag associated with this view and the specified key. 17086 * 17087 * @param key The key identifying the tag 17088 * 17089 * @return the Object stored in this view as a tag, or {@code null} if not 17090 * set 17091 * 17092 * @see #setTag(int, Object) 17093 * @see #getTag() 17094 */ 17095 public Object getTag(int key) { 17096 if (mKeyedTags != null) return mKeyedTags.get(key); 17097 return null; 17098 } 17099 17100 /** 17101 * Sets a tag associated with this view and a key. A tag can be used 17102 * to mark a view in its hierarchy and does not have to be unique within 17103 * the hierarchy. Tags can also be used to store data within a view 17104 * without resorting to another data structure. 17105 * 17106 * The specified key should be an id declared in the resources of the 17107 * application to ensure it is unique (see the <a 17108 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 17109 * Keys identified as belonging to 17110 * the Android framework or not associated with any package will cause 17111 * an {@link IllegalArgumentException} to be thrown. 17112 * 17113 * @param key The key identifying the tag 17114 * @param tag An Object to tag the view with 17115 * 17116 * @throws IllegalArgumentException If they specified key is not valid 17117 * 17118 * @see #setTag(Object) 17119 * @see #getTag(int) 17120 */ 17121 public void setTag(int key, final Object tag) { 17122 // If the package id is 0x00 or 0x01, it's either an undefined package 17123 // or a framework id 17124 if ((key >>> 24) < 2) { 17125 throw new IllegalArgumentException("The key must be an application-specific " 17126 + "resource id."); 17127 } 17128 17129 setKeyedTag(key, tag); 17130 } 17131 17132 /** 17133 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 17134 * framework id. 17135 * 17136 * @hide 17137 */ 17138 public void setTagInternal(int key, Object tag) { 17139 if ((key >>> 24) != 0x1) { 17140 throw new IllegalArgumentException("The key must be a framework-specific " 17141 + "resource id."); 17142 } 17143 17144 setKeyedTag(key, tag); 17145 } 17146 17147 private void setKeyedTag(int key, Object tag) { 17148 if (mKeyedTags == null) { 17149 mKeyedTags = new SparseArray<Object>(2); 17150 } 17151 17152 mKeyedTags.put(key, tag); 17153 } 17154 17155 /** 17156 * Prints information about this view in the log output, with the tag 17157 * {@link #VIEW_LOG_TAG}. 17158 * 17159 * @hide 17160 */ 17161 public void debug() { 17162 debug(0); 17163 } 17164 17165 /** 17166 * Prints information about this view in the log output, with the tag 17167 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 17168 * indentation defined by the <code>depth</code>. 17169 * 17170 * @param depth the indentation level 17171 * 17172 * @hide 17173 */ 17174 protected void debug(int depth) { 17175 String output = debugIndent(depth - 1); 17176 17177 output += "+ " + this; 17178 int id = getId(); 17179 if (id != -1) { 17180 output += " (id=" + id + ")"; 17181 } 17182 Object tag = getTag(); 17183 if (tag != null) { 17184 output += " (tag=" + tag + ")"; 17185 } 17186 Log.d(VIEW_LOG_TAG, output); 17187 17188 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 17189 output = debugIndent(depth) + " FOCUSED"; 17190 Log.d(VIEW_LOG_TAG, output); 17191 } 17192 17193 output = debugIndent(depth); 17194 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 17195 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 17196 + "} "; 17197 Log.d(VIEW_LOG_TAG, output); 17198 17199 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 17200 || mPaddingBottom != 0) { 17201 output = debugIndent(depth); 17202 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 17203 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 17204 Log.d(VIEW_LOG_TAG, output); 17205 } 17206 17207 output = debugIndent(depth); 17208 output += "mMeasureWidth=" + mMeasuredWidth + 17209 " mMeasureHeight=" + mMeasuredHeight; 17210 Log.d(VIEW_LOG_TAG, output); 17211 17212 output = debugIndent(depth); 17213 if (mLayoutParams == null) { 17214 output += "BAD! no layout params"; 17215 } else { 17216 output = mLayoutParams.debug(output); 17217 } 17218 Log.d(VIEW_LOG_TAG, output); 17219 17220 output = debugIndent(depth); 17221 output += "flags={"; 17222 output += View.printFlags(mViewFlags); 17223 output += "}"; 17224 Log.d(VIEW_LOG_TAG, output); 17225 17226 output = debugIndent(depth); 17227 output += "privateFlags={"; 17228 output += View.printPrivateFlags(mPrivateFlags); 17229 output += "}"; 17230 Log.d(VIEW_LOG_TAG, output); 17231 } 17232 17233 /** 17234 * Creates a string of whitespaces used for indentation. 17235 * 17236 * @param depth the indentation level 17237 * @return a String containing (depth * 2 + 3) * 2 white spaces 17238 * 17239 * @hide 17240 */ 17241 protected static String debugIndent(int depth) { 17242 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 17243 for (int i = 0; i < (depth * 2) + 3; i++) { 17244 spaces.append(' ').append(' '); 17245 } 17246 return spaces.toString(); 17247 } 17248 17249 /** 17250 * <p>Return the offset of the widget's text baseline from the widget's top 17251 * boundary. If this widget does not support baseline alignment, this 17252 * method returns -1. </p> 17253 * 17254 * @return the offset of the baseline within the widget's bounds or -1 17255 * if baseline alignment is not supported 17256 */ 17257 @ViewDebug.ExportedProperty(category = "layout") 17258 public int getBaseline() { 17259 return -1; 17260 } 17261 17262 /** 17263 * Returns whether the view hierarchy is currently undergoing a layout pass. This 17264 * information is useful to avoid situations such as calling {@link #requestLayout()} during 17265 * a layout pass. 17266 * 17267 * @return whether the view hierarchy is currently undergoing a layout pass 17268 */ 17269 public boolean isInLayout() { 17270 ViewRootImpl viewRoot = getViewRootImpl(); 17271 return (viewRoot != null && viewRoot.isInLayout()); 17272 } 17273 17274 /** 17275 * Call this when something has changed which has invalidated the 17276 * layout of this view. This will schedule a layout pass of the view 17277 * tree. This should not be called while the view hierarchy is currently in a layout 17278 * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the 17279 * end of the current layout pass (and then layout will run again) or after the current 17280 * frame is drawn and the next layout occurs. 17281 * 17282 * <p>Subclasses which override this method should call the superclass method to 17283 * handle possible request-during-layout errors correctly.</p> 17284 */ 17285 public void requestLayout() { 17286 if (mMeasureCache != null) mMeasureCache.clear(); 17287 17288 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) { 17289 // Only trigger request-during-layout logic if this is the view requesting it, 17290 // not the views in its parent hierarchy 17291 ViewRootImpl viewRoot = getViewRootImpl(); 17292 if (viewRoot != null && viewRoot.isInLayout()) { 17293 if (!viewRoot.requestLayoutDuringLayout(this)) { 17294 return; 17295 } 17296 } 17297 mAttachInfo.mViewRequestingLayout = this; 17298 } 17299 17300 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 17301 mPrivateFlags |= PFLAG_INVALIDATED; 17302 17303 if (mParent != null && !mParent.isLayoutRequested()) { 17304 mParent.requestLayout(); 17305 } 17306 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) { 17307 mAttachInfo.mViewRequestingLayout = null; 17308 } 17309 } 17310 17311 /** 17312 * Forces this view to be laid out during the next layout pass. 17313 * This method does not call requestLayout() or forceLayout() 17314 * on the parent. 17315 */ 17316 public void forceLayout() { 17317 if (mMeasureCache != null) mMeasureCache.clear(); 17318 17319 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 17320 mPrivateFlags |= PFLAG_INVALIDATED; 17321 } 17322 17323 /** 17324 * <p> 17325 * This is called to find out how big a view should be. The parent 17326 * supplies constraint information in the width and height parameters. 17327 * </p> 17328 * 17329 * <p> 17330 * The actual measurement work of a view is performed in 17331 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 17332 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 17333 * </p> 17334 * 17335 * 17336 * @param widthMeasureSpec Horizontal space requirements as imposed by the 17337 * parent 17338 * @param heightMeasureSpec Vertical space requirements as imposed by the 17339 * parent 17340 * 17341 * @see #onMeasure(int, int) 17342 */ 17343 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 17344 boolean optical = isLayoutModeOptical(this); 17345 if (optical != isLayoutModeOptical(mParent)) { 17346 Insets insets = getOpticalInsets(); 17347 int oWidth = insets.left + insets.right; 17348 int oHeight = insets.top + insets.bottom; 17349 widthMeasureSpec = MeasureSpec.adjust(widthMeasureSpec, optical ? -oWidth : oWidth); 17350 heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight); 17351 } 17352 17353 // Suppress sign extension for the low bytes 17354 long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL; 17355 if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2); 17356 17357 if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT || 17358 widthMeasureSpec != mOldWidthMeasureSpec || 17359 heightMeasureSpec != mOldHeightMeasureSpec) { 17360 17361 // first clears the measured dimension flag 17362 mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET; 17363 17364 resolveRtlPropertiesIfNeeded(); 17365 17366 int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 : 17367 mMeasureCache.indexOfKey(key); 17368 if (cacheIndex < 0 || sIgnoreMeasureCache) { 17369 // measure ourselves, this should set the measured dimension flag back 17370 onMeasure(widthMeasureSpec, heightMeasureSpec); 17371 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 17372 } else { 17373 long value = mMeasureCache.valueAt(cacheIndex); 17374 // Casting a long to int drops the high 32 bits, no mask needed 17375 setMeasuredDimensionRaw((int) (value >> 32), (int) value); 17376 mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 17377 } 17378 17379 // flag not set, setMeasuredDimension() was not invoked, we raise 17380 // an exception to warn the developer 17381 if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) { 17382 throw new IllegalStateException("onMeasure() did not set the" 17383 + " measured dimension by calling" 17384 + " setMeasuredDimension()"); 17385 } 17386 17387 mPrivateFlags |= PFLAG_LAYOUT_REQUIRED; 17388 } 17389 17390 mOldWidthMeasureSpec = widthMeasureSpec; 17391 mOldHeightMeasureSpec = heightMeasureSpec; 17392 17393 mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 | 17394 (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension 17395 } 17396 17397 /** 17398 * <p> 17399 * Measure the view and its content to determine the measured width and the 17400 * measured height. This method is invoked by {@link #measure(int, int)} and 17401 * should be overriden by subclasses to provide accurate and efficient 17402 * measurement of their contents. 17403 * </p> 17404 * 17405 * <p> 17406 * <strong>CONTRACT:</strong> When overriding this method, you 17407 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 17408 * measured width and height of this view. Failure to do so will trigger an 17409 * <code>IllegalStateException</code>, thrown by 17410 * {@link #measure(int, int)}. Calling the superclass' 17411 * {@link #onMeasure(int, int)} is a valid use. 17412 * </p> 17413 * 17414 * <p> 17415 * The base class implementation of measure defaults to the background size, 17416 * unless a larger size is allowed by the MeasureSpec. Subclasses should 17417 * override {@link #onMeasure(int, int)} to provide better measurements of 17418 * their content. 17419 * </p> 17420 * 17421 * <p> 17422 * If this method is overridden, it is the subclass's responsibility to make 17423 * sure the measured height and width are at least the view's minimum height 17424 * and width ({@link #getSuggestedMinimumHeight()} and 17425 * {@link #getSuggestedMinimumWidth()}). 17426 * </p> 17427 * 17428 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 17429 * The requirements are encoded with 17430 * {@link android.view.View.MeasureSpec}. 17431 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 17432 * The requirements are encoded with 17433 * {@link android.view.View.MeasureSpec}. 17434 * 17435 * @see #getMeasuredWidth() 17436 * @see #getMeasuredHeight() 17437 * @see #setMeasuredDimension(int, int) 17438 * @see #getSuggestedMinimumHeight() 17439 * @see #getSuggestedMinimumWidth() 17440 * @see android.view.View.MeasureSpec#getMode(int) 17441 * @see android.view.View.MeasureSpec#getSize(int) 17442 */ 17443 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 17444 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 17445 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 17446 } 17447 17448 /** 17449 * <p>This method must be called by {@link #onMeasure(int, int)} to store the 17450 * measured width and measured height. Failing to do so will trigger an 17451 * exception at measurement time.</p> 17452 * 17453 * @param measuredWidth The measured width of this view. May be a complex 17454 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17455 * {@link #MEASURED_STATE_TOO_SMALL}. 17456 * @param measuredHeight The measured height of this view. May be a complex 17457 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17458 * {@link #MEASURED_STATE_TOO_SMALL}. 17459 */ 17460 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 17461 boolean optical = isLayoutModeOptical(this); 17462 if (optical != isLayoutModeOptical(mParent)) { 17463 Insets insets = getOpticalInsets(); 17464 int opticalWidth = insets.left + insets.right; 17465 int opticalHeight = insets.top + insets.bottom; 17466 17467 measuredWidth += optical ? opticalWidth : -opticalWidth; 17468 measuredHeight += optical ? opticalHeight : -opticalHeight; 17469 } 17470 setMeasuredDimensionRaw(measuredWidth, measuredHeight); 17471 } 17472 17473 /** 17474 * Sets the measured dimension without extra processing for things like optical bounds. 17475 * Useful for reapplying consistent values that have already been cooked with adjustments 17476 * for optical bounds, etc. such as those from the measurement cache. 17477 * 17478 * @param measuredWidth The measured width of this view. May be a complex 17479 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17480 * {@link #MEASURED_STATE_TOO_SMALL}. 17481 * @param measuredHeight The measured height of this view. May be a complex 17482 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17483 * {@link #MEASURED_STATE_TOO_SMALL}. 17484 */ 17485 private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) { 17486 mMeasuredWidth = measuredWidth; 17487 mMeasuredHeight = measuredHeight; 17488 17489 mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET; 17490 } 17491 17492 /** 17493 * Merge two states as returned by {@link #getMeasuredState()}. 17494 * @param curState The current state as returned from a view or the result 17495 * of combining multiple views. 17496 * @param newState The new view state to combine. 17497 * @return Returns a new integer reflecting the combination of the two 17498 * states. 17499 */ 17500 public static int combineMeasuredStates(int curState, int newState) { 17501 return curState | newState; 17502 } 17503 17504 /** 17505 * Version of {@link #resolveSizeAndState(int, int, int)} 17506 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 17507 */ 17508 public static int resolveSize(int size, int measureSpec) { 17509 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 17510 } 17511 17512 /** 17513 * Utility to reconcile a desired size and state, with constraints imposed 17514 * by a MeasureSpec. Will take the desired size, unless a different size 17515 * is imposed by the constraints. The returned value is a compound integer, 17516 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 17517 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting 17518 * size is smaller than the size the view wants to be. 17519 * 17520 * @param size How big the view wants to be 17521 * @param measureSpec Constraints imposed by the parent 17522 * @return Size information bit mask as defined by 17523 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 17524 */ 17525 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 17526 int result = size; 17527 int specMode = MeasureSpec.getMode(measureSpec); 17528 int specSize = MeasureSpec.getSize(measureSpec); 17529 switch (specMode) { 17530 case MeasureSpec.UNSPECIFIED: 17531 result = size; 17532 break; 17533 case MeasureSpec.AT_MOST: 17534 if (specSize < size) { 17535 result = specSize | MEASURED_STATE_TOO_SMALL; 17536 } else { 17537 result = size; 17538 } 17539 break; 17540 case MeasureSpec.EXACTLY: 17541 result = specSize; 17542 break; 17543 } 17544 return result | (childMeasuredState&MEASURED_STATE_MASK); 17545 } 17546 17547 /** 17548 * Utility to return a default size. Uses the supplied size if the 17549 * MeasureSpec imposed no constraints. Will get larger if allowed 17550 * by the MeasureSpec. 17551 * 17552 * @param size Default size for this view 17553 * @param measureSpec Constraints imposed by the parent 17554 * @return The size this view should be. 17555 */ 17556 public static int getDefaultSize(int size, int measureSpec) { 17557 int result = size; 17558 int specMode = MeasureSpec.getMode(measureSpec); 17559 int specSize = MeasureSpec.getSize(measureSpec); 17560 17561 switch (specMode) { 17562 case MeasureSpec.UNSPECIFIED: 17563 result = size; 17564 break; 17565 case MeasureSpec.AT_MOST: 17566 case MeasureSpec.EXACTLY: 17567 result = specSize; 17568 break; 17569 } 17570 return result; 17571 } 17572 17573 /** 17574 * Returns the suggested minimum height that the view should use. This 17575 * returns the maximum of the view's minimum height 17576 * and the background's minimum height 17577 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 17578 * <p> 17579 * When being used in {@link #onMeasure(int, int)}, the caller should still 17580 * ensure the returned height is within the requirements of the parent. 17581 * 17582 * @return The suggested minimum height of the view. 17583 */ 17584 protected int getSuggestedMinimumHeight() { 17585 return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight()); 17586 17587 } 17588 17589 /** 17590 * Returns the suggested minimum width that the view should use. This 17591 * returns the maximum of the view's minimum width) 17592 * and the background's minimum width 17593 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 17594 * <p> 17595 * When being used in {@link #onMeasure(int, int)}, the caller should still 17596 * ensure the returned width is within the requirements of the parent. 17597 * 17598 * @return The suggested minimum width of the view. 17599 */ 17600 protected int getSuggestedMinimumWidth() { 17601 return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); 17602 } 17603 17604 /** 17605 * Returns the minimum height of the view. 17606 * 17607 * @return the minimum height the view will try to be. 17608 * 17609 * @see #setMinimumHeight(int) 17610 * 17611 * @attr ref android.R.styleable#View_minHeight 17612 */ 17613 public int getMinimumHeight() { 17614 return mMinHeight; 17615 } 17616 17617 /** 17618 * Sets the minimum height of the view. It is not guaranteed the view will 17619 * be able to achieve this minimum height (for example, if its parent layout 17620 * constrains it with less available height). 17621 * 17622 * @param minHeight The minimum height the view will try to be. 17623 * 17624 * @see #getMinimumHeight() 17625 * 17626 * @attr ref android.R.styleable#View_minHeight 17627 */ 17628 public void setMinimumHeight(int minHeight) { 17629 mMinHeight = minHeight; 17630 requestLayout(); 17631 } 17632 17633 /** 17634 * Returns the minimum width of the view. 17635 * 17636 * @return the minimum width the view will try to be. 17637 * 17638 * @see #setMinimumWidth(int) 17639 * 17640 * @attr ref android.R.styleable#View_minWidth 17641 */ 17642 public int getMinimumWidth() { 17643 return mMinWidth; 17644 } 17645 17646 /** 17647 * Sets the minimum width of the view. It is not guaranteed the view will 17648 * be able to achieve this minimum width (for example, if its parent layout 17649 * constrains it with less available width). 17650 * 17651 * @param minWidth The minimum width the view will try to be. 17652 * 17653 * @see #getMinimumWidth() 17654 * 17655 * @attr ref android.R.styleable#View_minWidth 17656 */ 17657 public void setMinimumWidth(int minWidth) { 17658 mMinWidth = minWidth; 17659 requestLayout(); 17660 17661 } 17662 17663 /** 17664 * Get the animation currently associated with this view. 17665 * 17666 * @return The animation that is currently playing or 17667 * scheduled to play for this view. 17668 */ 17669 public Animation getAnimation() { 17670 return mCurrentAnimation; 17671 } 17672 17673 /** 17674 * Start the specified animation now. 17675 * 17676 * @param animation the animation to start now 17677 */ 17678 public void startAnimation(Animation animation) { 17679 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 17680 setAnimation(animation); 17681 invalidateParentCaches(); 17682 invalidate(true); 17683 } 17684 17685 /** 17686 * Cancels any animations for this view. 17687 */ 17688 public void clearAnimation() { 17689 if (mCurrentAnimation != null) { 17690 mCurrentAnimation.detach(); 17691 } 17692 mCurrentAnimation = null; 17693 invalidateParentIfNeeded(); 17694 } 17695 17696 /** 17697 * Sets the next animation to play for this view. 17698 * If you want the animation to play immediately, use 17699 * {@link #startAnimation(android.view.animation.Animation)} instead. 17700 * This method provides allows fine-grained 17701 * control over the start time and invalidation, but you 17702 * must make sure that 1) the animation has a start time set, and 17703 * 2) the view's parent (which controls animations on its children) 17704 * will be invalidated when the animation is supposed to 17705 * start. 17706 * 17707 * @param animation The next animation, or null. 17708 */ 17709 public void setAnimation(Animation animation) { 17710 mCurrentAnimation = animation; 17711 17712 if (animation != null) { 17713 // If the screen is off assume the animation start time is now instead of 17714 // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time 17715 // would cause the animation to start when the screen turns back on 17716 if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF 17717 && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) { 17718 animation.setStartTime(AnimationUtils.currentAnimationTimeMillis()); 17719 } 17720 animation.reset(); 17721 } 17722 } 17723 17724 /** 17725 * Invoked by a parent ViewGroup to notify the start of the animation 17726 * currently associated with this view. If you override this method, 17727 * always call super.onAnimationStart(); 17728 * 17729 * @see #setAnimation(android.view.animation.Animation) 17730 * @see #getAnimation() 17731 */ 17732 protected void onAnimationStart() { 17733 mPrivateFlags |= PFLAG_ANIMATION_STARTED; 17734 } 17735 17736 /** 17737 * Invoked by a parent ViewGroup to notify the end of the animation 17738 * currently associated with this view. If you override this method, 17739 * always call super.onAnimationEnd(); 17740 * 17741 * @see #setAnimation(android.view.animation.Animation) 17742 * @see #getAnimation() 17743 */ 17744 protected void onAnimationEnd() { 17745 mPrivateFlags &= ~PFLAG_ANIMATION_STARTED; 17746 } 17747 17748 /** 17749 * Invoked if there is a Transform that involves alpha. Subclass that can 17750 * draw themselves with the specified alpha should return true, and then 17751 * respect that alpha when their onDraw() is called. If this returns false 17752 * then the view may be redirected to draw into an offscreen buffer to 17753 * fulfill the request, which will look fine, but may be slower than if the 17754 * subclass handles it internally. The default implementation returns false. 17755 * 17756 * @param alpha The alpha (0..255) to apply to the view's drawing 17757 * @return true if the view can draw with the specified alpha. 17758 */ 17759 protected boolean onSetAlpha(int alpha) { 17760 return false; 17761 } 17762 17763 /** 17764 * This is used by the RootView to perform an optimization when 17765 * the view hierarchy contains one or several SurfaceView. 17766 * SurfaceView is always considered transparent, but its children are not, 17767 * therefore all View objects remove themselves from the global transparent 17768 * region (passed as a parameter to this function). 17769 * 17770 * @param region The transparent region for this ViewAncestor (window). 17771 * 17772 * @return Returns true if the effective visibility of the view at this 17773 * point is opaque, regardless of the transparent region; returns false 17774 * if it is possible for underlying windows to be seen behind the view. 17775 * 17776 * {@hide} 17777 */ 17778 public boolean gatherTransparentRegion(Region region) { 17779 final AttachInfo attachInfo = mAttachInfo; 17780 if (region != null && attachInfo != null) { 17781 final int pflags = mPrivateFlags; 17782 if ((pflags & PFLAG_SKIP_DRAW) == 0) { 17783 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 17784 // remove it from the transparent region. 17785 final int[] location = attachInfo.mTransparentLocation; 17786 getLocationInWindow(location); 17787 region.op(location[0], location[1], location[0] + mRight - mLeft, 17788 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 17789 } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null && 17790 mBackground.getOpacity() != PixelFormat.TRANSPARENT) { 17791 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 17792 // exists, so we remove the background drawable's non-transparent 17793 // parts from this transparent region. 17794 applyDrawableToTransparentRegion(mBackground, region); 17795 } 17796 } 17797 return true; 17798 } 17799 17800 /** 17801 * Play a sound effect for this view. 17802 * 17803 * <p>The framework will play sound effects for some built in actions, such as 17804 * clicking, but you may wish to play these effects in your widget, 17805 * for instance, for internal navigation. 17806 * 17807 * <p>The sound effect will only be played if sound effects are enabled by the user, and 17808 * {@link #isSoundEffectsEnabled()} is true. 17809 * 17810 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 17811 */ 17812 public void playSoundEffect(int soundConstant) { 17813 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 17814 return; 17815 } 17816 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 17817 } 17818 17819 /** 17820 * BZZZTT!!1! 17821 * 17822 * <p>Provide haptic feedback to the user for this view. 17823 * 17824 * <p>The framework will provide haptic feedback for some built in actions, 17825 * such as long presses, but you may wish to provide feedback for your 17826 * own widget. 17827 * 17828 * <p>The feedback will only be performed if 17829 * {@link #isHapticFeedbackEnabled()} is true. 17830 * 17831 * @param feedbackConstant One of the constants defined in 17832 * {@link HapticFeedbackConstants} 17833 */ 17834 public boolean performHapticFeedback(int feedbackConstant) { 17835 return performHapticFeedback(feedbackConstant, 0); 17836 } 17837 17838 /** 17839 * BZZZTT!!1! 17840 * 17841 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 17842 * 17843 * @param feedbackConstant One of the constants defined in 17844 * {@link HapticFeedbackConstants} 17845 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 17846 */ 17847 public boolean performHapticFeedback(int feedbackConstant, int flags) { 17848 if (mAttachInfo == null) { 17849 return false; 17850 } 17851 //noinspection SimplifiableIfStatement 17852 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 17853 && !isHapticFeedbackEnabled()) { 17854 return false; 17855 } 17856 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 17857 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 17858 } 17859 17860 /** 17861 * Request that the visibility of the status bar or other screen/window 17862 * decorations be changed. 17863 * 17864 * <p>This method is used to put the over device UI into temporary modes 17865 * where the user's attention is focused more on the application content, 17866 * by dimming or hiding surrounding system affordances. This is typically 17867 * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY 17868 * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content 17869 * to be placed behind the action bar (and with these flags other system 17870 * affordances) so that smooth transitions between hiding and showing them 17871 * can be done. 17872 * 17873 * <p>Two representative examples of the use of system UI visibility is 17874 * implementing a content browsing application (like a magazine reader) 17875 * and a video playing application. 17876 * 17877 * <p>The first code shows a typical implementation of a View in a content 17878 * browsing application. In this implementation, the application goes 17879 * into a content-oriented mode by hiding the status bar and action bar, 17880 * and putting the navigation elements into lights out mode. The user can 17881 * then interact with content while in this mode. Such an application should 17882 * provide an easy way for the user to toggle out of the mode (such as to 17883 * check information in the status bar or access notifications). In the 17884 * implementation here, this is done simply by tapping on the content. 17885 * 17886 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java 17887 * content} 17888 * 17889 * <p>This second code sample shows a typical implementation of a View 17890 * in a video playing application. In this situation, while the video is 17891 * playing the application would like to go into a complete full-screen mode, 17892 * to use as much of the display as possible for the video. When in this state 17893 * the user can not interact with the application; the system intercepts 17894 * touching on the screen to pop the UI out of full screen mode. See 17895 * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code. 17896 * 17897 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java 17898 * content} 17899 * 17900 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 17901 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 17902 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 17903 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 17904 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 17905 */ 17906 public void setSystemUiVisibility(int visibility) { 17907 if (visibility != mSystemUiVisibility) { 17908 mSystemUiVisibility = visibility; 17909 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 17910 mParent.recomputeViewAttributes(this); 17911 } 17912 } 17913 } 17914 17915 /** 17916 * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested. 17917 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 17918 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 17919 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 17920 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 17921 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 17922 */ 17923 public int getSystemUiVisibility() { 17924 return mSystemUiVisibility; 17925 } 17926 17927 /** 17928 * Returns the current system UI visibility that is currently set for 17929 * the entire window. This is the combination of the 17930 * {@link #setSystemUiVisibility(int)} values supplied by all of the 17931 * views in the window. 17932 */ 17933 public int getWindowSystemUiVisibility() { 17934 return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0; 17935 } 17936 17937 /** 17938 * Override to find out when the window's requested system UI visibility 17939 * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}. 17940 * This is different from the callbacks received through 17941 * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)} 17942 * in that this is only telling you about the local request of the window, 17943 * not the actual values applied by the system. 17944 */ 17945 public void onWindowSystemUiVisibilityChanged(int visible) { 17946 } 17947 17948 /** 17949 * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down 17950 * the view hierarchy. 17951 */ 17952 public void dispatchWindowSystemUiVisiblityChanged(int visible) { 17953 onWindowSystemUiVisibilityChanged(visible); 17954 } 17955 17956 /** 17957 * Set a listener to receive callbacks when the visibility of the system bar changes. 17958 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 17959 */ 17960 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 17961 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 17962 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 17963 mParent.recomputeViewAttributes(this); 17964 } 17965 } 17966 17967 /** 17968 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 17969 * the view hierarchy. 17970 */ 17971 public void dispatchSystemUiVisibilityChanged(int visibility) { 17972 ListenerInfo li = mListenerInfo; 17973 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 17974 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 17975 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 17976 } 17977 } 17978 17979 boolean updateLocalSystemUiVisibility(int localValue, int localChanges) { 17980 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 17981 if (val != mSystemUiVisibility) { 17982 setSystemUiVisibility(val); 17983 return true; 17984 } 17985 return false; 17986 } 17987 17988 /** @hide */ 17989 public void setDisabledSystemUiVisibility(int flags) { 17990 if (mAttachInfo != null) { 17991 if (mAttachInfo.mDisabledSystemUiVisibility != flags) { 17992 mAttachInfo.mDisabledSystemUiVisibility = flags; 17993 if (mParent != null) { 17994 mParent.recomputeViewAttributes(this); 17995 } 17996 } 17997 } 17998 } 17999 18000 /** 18001 * Creates an image that the system displays during the drag and drop 18002 * operation. This is called a "drag shadow". The default implementation 18003 * for a DragShadowBuilder based on a View returns an image that has exactly the same 18004 * appearance as the given View. The default also positions the center of the drag shadow 18005 * directly under the touch point. If no View is provided (the constructor with no parameters 18006 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 18007 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the 18008 * default is an invisible drag shadow. 18009 * <p> 18010 * You are not required to use the View you provide to the constructor as the basis of the 18011 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 18012 * anything you want as the drag shadow. 18013 * </p> 18014 * <p> 18015 * You pass a DragShadowBuilder object to the system when you start the drag. The system 18016 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 18017 * size and position of the drag shadow. It uses this data to construct a 18018 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 18019 * so that your application can draw the shadow image in the Canvas. 18020 * </p> 18021 * 18022 * <div class="special reference"> 18023 * <h3>Developer Guides</h3> 18024 * <p>For a guide to implementing drag and drop features, read the 18025 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 18026 * </div> 18027 */ 18028 public static class DragShadowBuilder { 18029 private final WeakReference<View> mView; 18030 18031 /** 18032 * Constructs a shadow image builder based on a View. By default, the resulting drag 18033 * shadow will have the same appearance and dimensions as the View, with the touch point 18034 * over the center of the View. 18035 * @param view A View. Any View in scope can be used. 18036 */ 18037 public DragShadowBuilder(View view) { 18038 mView = new WeakReference<View>(view); 18039 } 18040 18041 /** 18042 * Construct a shadow builder object with no associated View. This 18043 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 18044 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 18045 * to supply the drag shadow's dimensions and appearance without 18046 * reference to any View object. If they are not overridden, then the result is an 18047 * invisible drag shadow. 18048 */ 18049 public DragShadowBuilder() { 18050 mView = new WeakReference<View>(null); 18051 } 18052 18053 /** 18054 * Returns the View object that had been passed to the 18055 * {@link #View.DragShadowBuilder(View)} 18056 * constructor. If that View parameter was {@code null} or if the 18057 * {@link #View.DragShadowBuilder()} 18058 * constructor was used to instantiate the builder object, this method will return 18059 * null. 18060 * 18061 * @return The View object associate with this builder object. 18062 */ 18063 @SuppressWarnings({"JavadocReference"}) 18064 final public View getView() { 18065 return mView.get(); 18066 } 18067 18068 /** 18069 * Provides the metrics for the shadow image. These include the dimensions of 18070 * the shadow image, and the point within that shadow that should 18071 * be centered under the touch location while dragging. 18072 * <p> 18073 * The default implementation sets the dimensions of the shadow to be the 18074 * same as the dimensions of the View itself and centers the shadow under 18075 * the touch point. 18076 * </p> 18077 * 18078 * @param shadowSize A {@link android.graphics.Point} containing the width and height 18079 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 18080 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 18081 * image. 18082 * 18083 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 18084 * shadow image that should be underneath the touch point during the drag and drop 18085 * operation. Your application must set {@link android.graphics.Point#x} to the 18086 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 18087 */ 18088 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 18089 final View view = mView.get(); 18090 if (view != null) { 18091 shadowSize.set(view.getWidth(), view.getHeight()); 18092 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 18093 } else { 18094 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 18095 } 18096 } 18097 18098 /** 18099 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 18100 * based on the dimensions it received from the 18101 * {@link #onProvideShadowMetrics(Point, Point)} callback. 18102 * 18103 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 18104 */ 18105 public void onDrawShadow(Canvas canvas) { 18106 final View view = mView.get(); 18107 if (view != null) { 18108 view.draw(canvas); 18109 } else { 18110 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 18111 } 18112 } 18113 } 18114 18115 /** 18116 * Starts a drag and drop operation. When your application calls this method, it passes a 18117 * {@link android.view.View.DragShadowBuilder} object to the system. The 18118 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 18119 * to get metrics for the drag shadow, and then calls the object's 18120 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 18121 * <p> 18122 * Once the system has the drag shadow, it begins the drag and drop operation by sending 18123 * drag events to all the View objects in your application that are currently visible. It does 18124 * this either by calling the View object's drag listener (an implementation of 18125 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 18126 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 18127 * Both are passed a {@link android.view.DragEvent} object that has a 18128 * {@link android.view.DragEvent#getAction()} value of 18129 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 18130 * </p> 18131 * <p> 18132 * Your application can invoke startDrag() on any attached View object. The View object does not 18133 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to 18134 * be related to the View the user selected for dragging. 18135 * </p> 18136 * @param data A {@link android.content.ClipData} object pointing to the data to be 18137 * transferred by the drag and drop operation. 18138 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 18139 * drag shadow. 18140 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 18141 * drop operation. This Object is put into every DragEvent object sent by the system during the 18142 * current drag. 18143 * <p> 18144 * myLocalState is a lightweight mechanism for the sending information from the dragged View 18145 * to the target Views. For example, it can contain flags that differentiate between a 18146 * a copy operation and a move operation. 18147 * </p> 18148 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 18149 * so the parameter should be set to 0. 18150 * @return {@code true} if the method completes successfully, or 18151 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 18152 * do a drag, and so no drag operation is in progress. 18153 */ 18154 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 18155 Object myLocalState, int flags) { 18156 if (ViewDebug.DEBUG_DRAG) { 18157 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 18158 } 18159 boolean okay = false; 18160 18161 Point shadowSize = new Point(); 18162 Point shadowTouchPoint = new Point(); 18163 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 18164 18165 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 18166 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 18167 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 18168 } 18169 18170 if (ViewDebug.DEBUG_DRAG) { 18171 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 18172 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 18173 } 18174 Surface surface = new Surface(); 18175 try { 18176 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 18177 flags, shadowSize.x, shadowSize.y, surface); 18178 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 18179 + " surface=" + surface); 18180 if (token != null) { 18181 Canvas canvas = surface.lockCanvas(null); 18182 try { 18183 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 18184 shadowBuilder.onDrawShadow(canvas); 18185 } finally { 18186 surface.unlockCanvasAndPost(canvas); 18187 } 18188 18189 final ViewRootImpl root = getViewRootImpl(); 18190 18191 // Cache the local state object for delivery with DragEvents 18192 root.setLocalDragState(myLocalState); 18193 18194 // repurpose 'shadowSize' for the last touch point 18195 root.getLastTouchPoint(shadowSize); 18196 18197 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 18198 shadowSize.x, shadowSize.y, 18199 shadowTouchPoint.x, shadowTouchPoint.y, data); 18200 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 18201 18202 // Off and running! Release our local surface instance; the drag 18203 // shadow surface is now managed by the system process. 18204 surface.release(); 18205 } 18206 } catch (Exception e) { 18207 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 18208 surface.destroy(); 18209 } 18210 18211 return okay; 18212 } 18213 18214 /** 18215 * Handles drag events sent by the system following a call to 18216 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}. 18217 *<p> 18218 * When the system calls this method, it passes a 18219 * {@link android.view.DragEvent} object. A call to 18220 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 18221 * in DragEvent. The method uses these to determine what is happening in the drag and drop 18222 * operation. 18223 * @param event The {@link android.view.DragEvent} sent by the system. 18224 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 18225 * in DragEvent, indicating the type of drag event represented by this object. 18226 * @return {@code true} if the method was successful, otherwise {@code false}. 18227 * <p> 18228 * The method should return {@code true} in response to an action type of 18229 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 18230 * operation. 18231 * </p> 18232 * <p> 18233 * The method should also return {@code true} in response to an action type of 18234 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 18235 * {@code false} if it didn't. 18236 * </p> 18237 */ 18238 public boolean onDragEvent(DragEvent event) { 18239 return false; 18240 } 18241 18242 /** 18243 * Detects if this View is enabled and has a drag event listener. 18244 * If both are true, then it calls the drag event listener with the 18245 * {@link android.view.DragEvent} it received. If the drag event listener returns 18246 * {@code true}, then dispatchDragEvent() returns {@code true}. 18247 * <p> 18248 * For all other cases, the method calls the 18249 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 18250 * method and returns its result. 18251 * </p> 18252 * <p> 18253 * This ensures that a drag event is always consumed, even if the View does not have a drag 18254 * event listener. However, if the View has a listener and the listener returns true, then 18255 * onDragEvent() is not called. 18256 * </p> 18257 */ 18258 public boolean dispatchDragEvent(DragEvent event) { 18259 ListenerInfo li = mListenerInfo; 18260 //noinspection SimplifiableIfStatement 18261 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 18262 && li.mOnDragListener.onDrag(this, event)) { 18263 return true; 18264 } 18265 return onDragEvent(event); 18266 } 18267 18268 boolean canAcceptDrag() { 18269 return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0; 18270 } 18271 18272 /** 18273 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 18274 * it is ever exposed at all. 18275 * @hide 18276 */ 18277 public void onCloseSystemDialogs(String reason) { 18278 } 18279 18280 /** 18281 * Given a Drawable whose bounds have been set to draw into this view, 18282 * update a Region being computed for 18283 * {@link #gatherTransparentRegion(android.graphics.Region)} so 18284 * that any non-transparent parts of the Drawable are removed from the 18285 * given transparent region. 18286 * 18287 * @param dr The Drawable whose transparency is to be applied to the region. 18288 * @param region A Region holding the current transparency information, 18289 * where any parts of the region that are set are considered to be 18290 * transparent. On return, this region will be modified to have the 18291 * transparency information reduced by the corresponding parts of the 18292 * Drawable that are not transparent. 18293 * {@hide} 18294 */ 18295 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 18296 if (DBG) { 18297 Log.i("View", "Getting transparent region for: " + this); 18298 } 18299 final Region r = dr.getTransparentRegion(); 18300 final Rect db = dr.getBounds(); 18301 final AttachInfo attachInfo = mAttachInfo; 18302 if (r != null && attachInfo != null) { 18303 final int w = getRight()-getLeft(); 18304 final int h = getBottom()-getTop(); 18305 if (db.left > 0) { 18306 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 18307 r.op(0, 0, db.left, h, Region.Op.UNION); 18308 } 18309 if (db.right < w) { 18310 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 18311 r.op(db.right, 0, w, h, Region.Op.UNION); 18312 } 18313 if (db.top > 0) { 18314 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 18315 r.op(0, 0, w, db.top, Region.Op.UNION); 18316 } 18317 if (db.bottom < h) { 18318 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 18319 r.op(0, db.bottom, w, h, Region.Op.UNION); 18320 } 18321 final int[] location = attachInfo.mTransparentLocation; 18322 getLocationInWindow(location); 18323 r.translate(location[0], location[1]); 18324 region.op(r, Region.Op.INTERSECT); 18325 } else { 18326 region.op(db, Region.Op.DIFFERENCE); 18327 } 18328 } 18329 18330 private void checkForLongClick(int delayOffset) { 18331 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 18332 mHasPerformedLongPress = false; 18333 18334 if (mPendingCheckForLongPress == null) { 18335 mPendingCheckForLongPress = new CheckForLongPress(); 18336 } 18337 mPendingCheckForLongPress.rememberWindowAttachCount(); 18338 postDelayed(mPendingCheckForLongPress, 18339 ViewConfiguration.getLongPressTimeout() - delayOffset); 18340 } 18341 } 18342 18343 /** 18344 * Inflate a view from an XML resource. This convenience method wraps the {@link 18345 * LayoutInflater} class, which provides a full range of options for view inflation. 18346 * 18347 * @param context The Context object for your activity or application. 18348 * @param resource The resource ID to inflate 18349 * @param root A view group that will be the parent. Used to properly inflate the 18350 * layout_* parameters. 18351 * @see LayoutInflater 18352 */ 18353 public static View inflate(Context context, int resource, ViewGroup root) { 18354 LayoutInflater factory = LayoutInflater.from(context); 18355 return factory.inflate(resource, root); 18356 } 18357 18358 /** 18359 * Scroll the view with standard behavior for scrolling beyond the normal 18360 * content boundaries. Views that call this method should override 18361 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 18362 * results of an over-scroll operation. 18363 * 18364 * Views can use this method to handle any touch or fling-based scrolling. 18365 * 18366 * @param deltaX Change in X in pixels 18367 * @param deltaY Change in Y in pixels 18368 * @param scrollX Current X scroll value in pixels before applying deltaX 18369 * @param scrollY Current Y scroll value in pixels before applying deltaY 18370 * @param scrollRangeX Maximum content scroll range along the X axis 18371 * @param scrollRangeY Maximum content scroll range along the Y axis 18372 * @param maxOverScrollX Number of pixels to overscroll by in either direction 18373 * along the X axis. 18374 * @param maxOverScrollY Number of pixels to overscroll by in either direction 18375 * along the Y axis. 18376 * @param isTouchEvent true if this scroll operation is the result of a touch event. 18377 * @return true if scrolling was clamped to an over-scroll boundary along either 18378 * axis, false otherwise. 18379 */ 18380 @SuppressWarnings({"UnusedParameters"}) 18381 protected boolean overScrollBy(int deltaX, int deltaY, 18382 int scrollX, int scrollY, 18383 int scrollRangeX, int scrollRangeY, 18384 int maxOverScrollX, int maxOverScrollY, 18385 boolean isTouchEvent) { 18386 final int overScrollMode = mOverScrollMode; 18387 final boolean canScrollHorizontal = 18388 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 18389 final boolean canScrollVertical = 18390 computeVerticalScrollRange() > computeVerticalScrollExtent(); 18391 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 18392 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 18393 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 18394 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 18395 18396 int newScrollX = scrollX + deltaX; 18397 if (!overScrollHorizontal) { 18398 maxOverScrollX = 0; 18399 } 18400 18401 int newScrollY = scrollY + deltaY; 18402 if (!overScrollVertical) { 18403 maxOverScrollY = 0; 18404 } 18405 18406 // Clamp values if at the limits and record 18407 final int left = -maxOverScrollX; 18408 final int right = maxOverScrollX + scrollRangeX; 18409 final int top = -maxOverScrollY; 18410 final int bottom = maxOverScrollY + scrollRangeY; 18411 18412 boolean clampedX = false; 18413 if (newScrollX > right) { 18414 newScrollX = right; 18415 clampedX = true; 18416 } else if (newScrollX < left) { 18417 newScrollX = left; 18418 clampedX = true; 18419 } 18420 18421 boolean clampedY = false; 18422 if (newScrollY > bottom) { 18423 newScrollY = bottom; 18424 clampedY = true; 18425 } else if (newScrollY < top) { 18426 newScrollY = top; 18427 clampedY = true; 18428 } 18429 18430 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 18431 18432 return clampedX || clampedY; 18433 } 18434 18435 /** 18436 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 18437 * respond to the results of an over-scroll operation. 18438 * 18439 * @param scrollX New X scroll value in pixels 18440 * @param scrollY New Y scroll value in pixels 18441 * @param clampedX True if scrollX was clamped to an over-scroll boundary 18442 * @param clampedY True if scrollY was clamped to an over-scroll boundary 18443 */ 18444 protected void onOverScrolled(int scrollX, int scrollY, 18445 boolean clampedX, boolean clampedY) { 18446 // Intentionally empty. 18447 } 18448 18449 /** 18450 * Returns the over-scroll mode for this view. The result will be 18451 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 18452 * (allow over-scrolling only if the view content is larger than the container), 18453 * or {@link #OVER_SCROLL_NEVER}. 18454 * 18455 * @return This view's over-scroll mode. 18456 */ 18457 public int getOverScrollMode() { 18458 return mOverScrollMode; 18459 } 18460 18461 /** 18462 * Set the over-scroll mode for this view. Valid over-scroll modes are 18463 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 18464 * (allow over-scrolling only if the view content is larger than the container), 18465 * or {@link #OVER_SCROLL_NEVER}. 18466 * 18467 * Setting the over-scroll mode of a view will have an effect only if the 18468 * view is capable of scrolling. 18469 * 18470 * @param overScrollMode The new over-scroll mode for this view. 18471 */ 18472 public void setOverScrollMode(int overScrollMode) { 18473 if (overScrollMode != OVER_SCROLL_ALWAYS && 18474 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 18475 overScrollMode != OVER_SCROLL_NEVER) { 18476 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 18477 } 18478 mOverScrollMode = overScrollMode; 18479 } 18480 18481 /** 18482 * Enable or disable nested scrolling for this view. 18483 * 18484 * <p>If this property is set to true the view will be permitted to initiate nested 18485 * scrolling operations with a compatible parent view in the current hierarchy. If this 18486 * view does not implement nested scrolling this will have no effect. Disabling nested scrolling 18487 * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping} 18488 * the nested scroll.</p> 18489 * 18490 * @param enabled true to enable nested scrolling, false to disable 18491 * 18492 * @see #isNestedScrollingEnabled() 18493 */ 18494 public void setNestedScrollingEnabled(boolean enabled) { 18495 if (enabled) { 18496 mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED; 18497 } else { 18498 stopNestedScroll(); 18499 mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED; 18500 } 18501 } 18502 18503 /** 18504 * Returns true if nested scrolling is enabled for this view. 18505 * 18506 * <p>If nested scrolling is enabled and this View class implementation supports it, 18507 * this view will act as a nested scrolling child view when applicable, forwarding data 18508 * about the scroll operation in progress to a compatible and cooperating nested scrolling 18509 * parent.</p> 18510 * 18511 * @return true if nested scrolling is enabled 18512 * 18513 * @see #setNestedScrollingEnabled(boolean) 18514 */ 18515 public boolean isNestedScrollingEnabled() { 18516 return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) == 18517 PFLAG3_NESTED_SCROLLING_ENABLED; 18518 } 18519 18520 /** 18521 * Begin a nestable scroll operation along the given axes. 18522 * 18523 * <p>A view starting a nested scroll promises to abide by the following contract:</p> 18524 * 18525 * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case 18526 * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}. 18527 * In the case of touch scrolling the nested scroll will be terminated automatically in 18528 * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}. 18529 * In the event of programmatic scrolling the caller must explicitly call 18530 * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p> 18531 * 18532 * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found. 18533 * If it returns false the caller may ignore the rest of this contract until the next scroll. 18534 * Calling startNestedScroll while a nested scroll is already in progress will return true.</p> 18535 * 18536 * <p>At each incremental step of the scroll the caller should invoke 18537 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} 18538 * once it has calculated the requested scrolling delta. If it returns true the nested scrolling 18539 * parent at least partially consumed the scroll and the caller should adjust the amount it 18540 * scrolls by.</p> 18541 * 18542 * <p>After applying the remainder of the scroll delta the caller should invoke 18543 * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing 18544 * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat 18545 * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}. 18546 * </p> 18547 * 18548 * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or 18549 * {@link #SCROLL_AXIS_VERTICAL}. 18550 * @return true if a cooperative parent was found and nested scrolling has been enabled for 18551 * the current gesture. 18552 * 18553 * @see #stopNestedScroll() 18554 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 18555 * @see #dispatchNestedScroll(int, int, int, int, int[]) 18556 */ 18557 public boolean startNestedScroll(int axes) { 18558 if (hasNestedScrollingParent()) { 18559 // Already in progress 18560 return true; 18561 } 18562 if (isNestedScrollingEnabled()) { 18563 ViewParent p = getParent(); 18564 View child = this; 18565 while (p != null) { 18566 try { 18567 if (p.onStartNestedScroll(child, this, axes)) { 18568 mNestedScrollingParent = p; 18569 p.onNestedScrollAccepted(child, this, axes); 18570 return true; 18571 } 18572 } catch (AbstractMethodError e) { 18573 Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " + 18574 "method onStartNestedScroll", e); 18575 // Allow the search upward to continue 18576 } 18577 if (p instanceof View) { 18578 child = (View) p; 18579 } 18580 p = p.getParent(); 18581 } 18582 } 18583 return false; 18584 } 18585 18586 /** 18587 * Stop a nested scroll in progress. 18588 * 18589 * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p> 18590 * 18591 * @see #startNestedScroll(int) 18592 */ 18593 public void stopNestedScroll() { 18594 if (mNestedScrollingParent != null) { 18595 mNestedScrollingParent.onStopNestedScroll(this); 18596 mNestedScrollingParent = null; 18597 } 18598 } 18599 18600 /** 18601 * Returns true if this view has a nested scrolling parent. 18602 * 18603 * <p>The presence of a nested scrolling parent indicates that this view has initiated 18604 * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p> 18605 * 18606 * @return whether this view has a nested scrolling parent 18607 */ 18608 public boolean hasNestedScrollingParent() { 18609 return mNestedScrollingParent != null; 18610 } 18611 18612 /** 18613 * Dispatch one step of a nested scroll in progress. 18614 * 18615 * <p>Implementations of views that support nested scrolling should call this to report 18616 * info about a scroll in progress to the current nested scrolling parent. If a nested scroll 18617 * is not currently in progress or nested scrolling is not 18618 * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p> 18619 * 18620 * <p>Compatible View implementations should also call 18621 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before 18622 * consuming a component of the scroll event themselves.</p> 18623 * 18624 * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step 18625 * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step 18626 * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view 18627 * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view 18628 * @param offsetInWindow Optional. If not null, on return this will contain the offset 18629 * in local view coordinates of this view from before this operation 18630 * to after it completes. View implementations may use this to adjust 18631 * expected input coordinate tracking. 18632 * @return true if the event was dispatched, false if it could not be dispatched. 18633 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 18634 */ 18635 public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, 18636 int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow) { 18637 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18638 if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) { 18639 int startX = 0; 18640 int startY = 0; 18641 if (offsetInWindow != null) { 18642 getLocationInWindow(offsetInWindow); 18643 startX = offsetInWindow[0]; 18644 startY = offsetInWindow[1]; 18645 } 18646 18647 mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed, 18648 dxUnconsumed, dyUnconsumed); 18649 18650 if (offsetInWindow != null) { 18651 getLocationInWindow(offsetInWindow); 18652 offsetInWindow[0] -= startX; 18653 offsetInWindow[1] -= startY; 18654 } 18655 return true; 18656 } else if (offsetInWindow != null) { 18657 // No motion, no dispatch. Keep offsetInWindow up to date. 18658 offsetInWindow[0] = 0; 18659 offsetInWindow[1] = 0; 18660 } 18661 } 18662 return false; 18663 } 18664 18665 /** 18666 * Dispatch one step of a nested scroll in progress before this view consumes any portion of it. 18667 * 18668 * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch. 18669 * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested 18670 * scrolling operation to consume some or all of the scroll operation before the child view 18671 * consumes it.</p> 18672 * 18673 * @param dx Horizontal scroll distance in pixels 18674 * @param dy Vertical scroll distance in pixels 18675 * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx 18676 * and consumed[1] the consumed dy. 18677 * @param offsetInWindow Optional. If not null, on return this will contain the offset 18678 * in local view coordinates of this view from before this operation 18679 * to after it completes. View implementations may use this to adjust 18680 * expected input coordinate tracking. 18681 * @return true if the parent consumed some or all of the scroll delta 18682 * @see #dispatchNestedScroll(int, int, int, int, int[]) 18683 */ 18684 public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) { 18685 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18686 if (dx != 0 || dy != 0) { 18687 int startX = 0; 18688 int startY = 0; 18689 if (offsetInWindow != null) { 18690 getLocationInWindow(offsetInWindow); 18691 startX = offsetInWindow[0]; 18692 startY = offsetInWindow[1]; 18693 } 18694 18695 if (consumed == null) { 18696 if (mTempNestedScrollConsumed == null) { 18697 mTempNestedScrollConsumed = new int[2]; 18698 } 18699 consumed = mTempNestedScrollConsumed; 18700 } 18701 consumed[0] = 0; 18702 consumed[1] = 0; 18703 mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed); 18704 18705 if (offsetInWindow != null) { 18706 getLocationInWindow(offsetInWindow); 18707 offsetInWindow[0] -= startX; 18708 offsetInWindow[1] -= startY; 18709 } 18710 return consumed[0] != 0 || consumed[1] != 0; 18711 } else if (offsetInWindow != null) { 18712 offsetInWindow[0] = 0; 18713 offsetInWindow[1] = 0; 18714 } 18715 } 18716 return false; 18717 } 18718 18719 /** 18720 * Dispatch a fling to a nested scrolling parent. 18721 * 18722 * <p>This method should be used to indicate that a nested scrolling child has detected 18723 * suitable conditions for a fling. Generally this means that a touch scroll has ended with a 18724 * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds 18725 * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity} 18726 * along a scrollable axis.</p> 18727 * 18728 * <p>If a nested scrolling child view would normally fling but it is at the edge of 18729 * its own content, it can use this method to delegate the fling to its nested scrolling 18730 * parent instead. The parent may optionally consume the fling or observe a child fling.</p> 18731 * 18732 * @param velocityX Horizontal fling velocity in pixels per second 18733 * @param velocityY Vertical fling velocity in pixels per second 18734 * @param consumed true if the child consumed the fling, false otherwise 18735 * @return true if the nested scrolling parent consumed or otherwise reacted to the fling 18736 */ 18737 public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) { 18738 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18739 return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed); 18740 } 18741 return false; 18742 } 18743 18744 /** 18745 * Dispatch a fling to a nested scrolling parent before it is processed by this view. 18746 * 18747 * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch 18748 * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code> 18749 * offsets an opportunity for the parent view in a nested fling to fully consume the fling 18750 * before the child view consumes it. If this method returns <code>true</code>, a nested 18751 * parent view consumed the fling and this view should not scroll as a result.</p> 18752 * 18753 * <p>For a better user experience, only one view in a nested scrolling chain should consume 18754 * the fling at a time. If a parent view consumed the fling this method will return false. 18755 * Custom view implementations should account for this in two ways:</p> 18756 * 18757 * <ul> 18758 * <li>If a custom view is paged and needs to settle to a fixed page-point, do not 18759 * call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid 18760 * position regardless.</li> 18761 * <li>If a nested parent does consume the fling, this view should not scroll at all, 18762 * even to settle back to a valid idle position.</li> 18763 * </ul> 18764 * 18765 * <p>Views should also not offer fling velocities to nested parent views along an axis 18766 * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView} 18767 * should not offer a horizontal fling velocity to its parents since scrolling along that 18768 * axis is not permitted and carrying velocity along that motion does not make sense.</p> 18769 * 18770 * @param velocityX Horizontal fling velocity in pixels per second 18771 * @param velocityY Vertical fling velocity in pixels per second 18772 * @return true if a nested scrolling parent consumed the fling 18773 */ 18774 public boolean dispatchNestedPreFling(float velocityX, float velocityY) { 18775 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18776 return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY); 18777 } 18778 return false; 18779 } 18780 18781 /** 18782 * Gets a scale factor that determines the distance the view should scroll 18783 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 18784 * @return The vertical scroll scale factor. 18785 * @hide 18786 */ 18787 protected float getVerticalScrollFactor() { 18788 if (mVerticalScrollFactor == 0) { 18789 TypedValue outValue = new TypedValue(); 18790 if (!mContext.getTheme().resolveAttribute( 18791 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 18792 throw new IllegalStateException( 18793 "Expected theme to define listPreferredItemHeight."); 18794 } 18795 mVerticalScrollFactor = outValue.getDimension( 18796 mContext.getResources().getDisplayMetrics()); 18797 } 18798 return mVerticalScrollFactor; 18799 } 18800 18801 /** 18802 * Gets a scale factor that determines the distance the view should scroll 18803 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 18804 * @return The horizontal scroll scale factor. 18805 * @hide 18806 */ 18807 protected float getHorizontalScrollFactor() { 18808 // TODO: Should use something else. 18809 return getVerticalScrollFactor(); 18810 } 18811 18812 /** 18813 * Return the value specifying the text direction or policy that was set with 18814 * {@link #setTextDirection(int)}. 18815 * 18816 * @return the defined text direction. It can be one of: 18817 * 18818 * {@link #TEXT_DIRECTION_INHERIT}, 18819 * {@link #TEXT_DIRECTION_FIRST_STRONG} 18820 * {@link #TEXT_DIRECTION_ANY_RTL}, 18821 * {@link #TEXT_DIRECTION_LTR}, 18822 * {@link #TEXT_DIRECTION_RTL}, 18823 * {@link #TEXT_DIRECTION_LOCALE} 18824 * 18825 * @attr ref android.R.styleable#View_textDirection 18826 * 18827 * @hide 18828 */ 18829 @ViewDebug.ExportedProperty(category = "text", mapping = { 18830 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 18831 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 18832 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 18833 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 18834 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 18835 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 18836 }) 18837 public int getRawTextDirection() { 18838 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 18839 } 18840 18841 /** 18842 * Set the text direction. 18843 * 18844 * @param textDirection the direction to set. Should be one of: 18845 * 18846 * {@link #TEXT_DIRECTION_INHERIT}, 18847 * {@link #TEXT_DIRECTION_FIRST_STRONG} 18848 * {@link #TEXT_DIRECTION_ANY_RTL}, 18849 * {@link #TEXT_DIRECTION_LTR}, 18850 * {@link #TEXT_DIRECTION_RTL}, 18851 * {@link #TEXT_DIRECTION_LOCALE} 18852 * 18853 * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution 18854 * proceeds up the parent chain of the view to get the value. If there is no parent, then it will 18855 * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}. 18856 * 18857 * @attr ref android.R.styleable#View_textDirection 18858 */ 18859 public void setTextDirection(int textDirection) { 18860 if (getRawTextDirection() != textDirection) { 18861 // Reset the current text direction and the resolved one 18862 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 18863 resetResolvedTextDirection(); 18864 // Set the new text direction 18865 mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK); 18866 // Do resolution 18867 resolveTextDirection(); 18868 // Notify change 18869 onRtlPropertiesChanged(getLayoutDirection()); 18870 // Refresh 18871 requestLayout(); 18872 invalidate(true); 18873 } 18874 } 18875 18876 /** 18877 * Return the resolved text direction. 18878 * 18879 * @return the resolved text direction. Returns one of: 18880 * 18881 * {@link #TEXT_DIRECTION_FIRST_STRONG} 18882 * {@link #TEXT_DIRECTION_ANY_RTL}, 18883 * {@link #TEXT_DIRECTION_LTR}, 18884 * {@link #TEXT_DIRECTION_RTL}, 18885 * {@link #TEXT_DIRECTION_LOCALE} 18886 * 18887 * @attr ref android.R.styleable#View_textDirection 18888 */ 18889 @ViewDebug.ExportedProperty(category = "text", mapping = { 18890 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 18891 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 18892 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 18893 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 18894 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 18895 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 18896 }) 18897 public int getTextDirection() { 18898 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 18899 } 18900 18901 /** 18902 * Resolve the text direction. 18903 * 18904 * @return true if resolution has been done, false otherwise. 18905 * 18906 * @hide 18907 */ 18908 public boolean resolveTextDirection() { 18909 // Reset any previous text direction resolution 18910 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 18911 18912 if (hasRtlSupport()) { 18913 // Set resolved text direction flag depending on text direction flag 18914 final int textDirection = getRawTextDirection(); 18915 switch(textDirection) { 18916 case TEXT_DIRECTION_INHERIT: 18917 if (!canResolveTextDirection()) { 18918 // We cannot do the resolution if there is no parent, so use the default one 18919 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18920 // Resolution will need to happen again later 18921 return false; 18922 } 18923 18924 // Parent has not yet resolved, so we still return the default 18925 try { 18926 if (!mParent.isTextDirectionResolved()) { 18927 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18928 // Resolution will need to happen again later 18929 return false; 18930 } 18931 } catch (AbstractMethodError e) { 18932 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18933 " does not fully implement ViewParent", e); 18934 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED | 18935 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18936 return true; 18937 } 18938 18939 // Set current resolved direction to the same value as the parent's one 18940 int parentResolvedDirection; 18941 try { 18942 parentResolvedDirection = mParent.getTextDirection(); 18943 } catch (AbstractMethodError e) { 18944 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18945 " does not fully implement ViewParent", e); 18946 parentResolvedDirection = TEXT_DIRECTION_LTR; 18947 } 18948 switch (parentResolvedDirection) { 18949 case TEXT_DIRECTION_FIRST_STRONG: 18950 case TEXT_DIRECTION_ANY_RTL: 18951 case TEXT_DIRECTION_LTR: 18952 case TEXT_DIRECTION_RTL: 18953 case TEXT_DIRECTION_LOCALE: 18954 mPrivateFlags2 |= 18955 (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 18956 break; 18957 default: 18958 // Default resolved direction is "first strong" heuristic 18959 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18960 } 18961 break; 18962 case TEXT_DIRECTION_FIRST_STRONG: 18963 case TEXT_DIRECTION_ANY_RTL: 18964 case TEXT_DIRECTION_LTR: 18965 case TEXT_DIRECTION_RTL: 18966 case TEXT_DIRECTION_LOCALE: 18967 // Resolved direction is the same as text direction 18968 mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 18969 break; 18970 default: 18971 // Default resolved direction is "first strong" heuristic 18972 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18973 } 18974 } else { 18975 // Default resolved direction is "first strong" heuristic 18976 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18977 } 18978 18979 // Set to resolved 18980 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED; 18981 return true; 18982 } 18983 18984 /** 18985 * Check if text direction resolution can be done. 18986 * 18987 * @return true if text direction resolution can be done otherwise return false. 18988 */ 18989 public boolean canResolveTextDirection() { 18990 switch (getRawTextDirection()) { 18991 case TEXT_DIRECTION_INHERIT: 18992 if (mParent != null) { 18993 try { 18994 return mParent.canResolveTextDirection(); 18995 } catch (AbstractMethodError e) { 18996 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18997 " does not fully implement ViewParent", e); 18998 } 18999 } 19000 return false; 19001 19002 default: 19003 return true; 19004 } 19005 } 19006 19007 /** 19008 * Reset resolved text direction. Text direction will be resolved during a call to 19009 * {@link #onMeasure(int, int)}. 19010 * 19011 * @hide 19012 */ 19013 public void resetResolvedTextDirection() { 19014 // Reset any previous text direction resolution 19015 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 19016 // Set to default value 19017 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 19018 } 19019 19020 /** 19021 * @return true if text direction is inherited. 19022 * 19023 * @hide 19024 */ 19025 public boolean isTextDirectionInherited() { 19026 return (getRawTextDirection() == TEXT_DIRECTION_INHERIT); 19027 } 19028 19029 /** 19030 * @return true if text direction is resolved. 19031 */ 19032 public boolean isTextDirectionResolved() { 19033 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED; 19034 } 19035 19036 /** 19037 * Return the value specifying the text alignment or policy that was set with 19038 * {@link #setTextAlignment(int)}. 19039 * 19040 * @return the defined text alignment. It can be one of: 19041 * 19042 * {@link #TEXT_ALIGNMENT_INHERIT}, 19043 * {@link #TEXT_ALIGNMENT_GRAVITY}, 19044 * {@link #TEXT_ALIGNMENT_CENTER}, 19045 * {@link #TEXT_ALIGNMENT_TEXT_START}, 19046 * {@link #TEXT_ALIGNMENT_TEXT_END}, 19047 * {@link #TEXT_ALIGNMENT_VIEW_START}, 19048 * {@link #TEXT_ALIGNMENT_VIEW_END} 19049 * 19050 * @attr ref android.R.styleable#View_textAlignment 19051 * 19052 * @hide 19053 */ 19054 @ViewDebug.ExportedProperty(category = "text", mapping = { 19055 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 19056 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 19057 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 19058 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 19059 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 19060 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 19061 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 19062 }) 19063 @TextAlignment 19064 public int getRawTextAlignment() { 19065 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 19066 } 19067 19068 /** 19069 * Set the text alignment. 19070 * 19071 * @param textAlignment The text alignment to set. Should be one of 19072 * 19073 * {@link #TEXT_ALIGNMENT_INHERIT}, 19074 * {@link #TEXT_ALIGNMENT_GRAVITY}, 19075 * {@link #TEXT_ALIGNMENT_CENTER}, 19076 * {@link #TEXT_ALIGNMENT_TEXT_START}, 19077 * {@link #TEXT_ALIGNMENT_TEXT_END}, 19078 * {@link #TEXT_ALIGNMENT_VIEW_START}, 19079 * {@link #TEXT_ALIGNMENT_VIEW_END} 19080 * 19081 * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution 19082 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 19083 * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}. 19084 * 19085 * @attr ref android.R.styleable#View_textAlignment 19086 */ 19087 public void setTextAlignment(@TextAlignment int textAlignment) { 19088 if (textAlignment != getRawTextAlignment()) { 19089 // Reset the current and resolved text alignment 19090 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 19091 resetResolvedTextAlignment(); 19092 // Set the new text alignment 19093 mPrivateFlags2 |= 19094 ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK); 19095 // Do resolution 19096 resolveTextAlignment(); 19097 // Notify change 19098 onRtlPropertiesChanged(getLayoutDirection()); 19099 // Refresh 19100 requestLayout(); 19101 invalidate(true); 19102 } 19103 } 19104 19105 /** 19106 * Return the resolved text alignment. 19107 * 19108 * @return the resolved text alignment. Returns one of: 19109 * 19110 * {@link #TEXT_ALIGNMENT_GRAVITY}, 19111 * {@link #TEXT_ALIGNMENT_CENTER}, 19112 * {@link #TEXT_ALIGNMENT_TEXT_START}, 19113 * {@link #TEXT_ALIGNMENT_TEXT_END}, 19114 * {@link #TEXT_ALIGNMENT_VIEW_START}, 19115 * {@link #TEXT_ALIGNMENT_VIEW_END} 19116 * 19117 * @attr ref android.R.styleable#View_textAlignment 19118 */ 19119 @ViewDebug.ExportedProperty(category = "text", mapping = { 19120 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 19121 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 19122 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 19123 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 19124 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 19125 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 19126 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 19127 }) 19128 @TextAlignment 19129 public int getTextAlignment() { 19130 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >> 19131 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 19132 } 19133 19134 /** 19135 * Resolve the text alignment. 19136 * 19137 * @return true if resolution has been done, false otherwise. 19138 * 19139 * @hide 19140 */ 19141 public boolean resolveTextAlignment() { 19142 // Reset any previous text alignment resolution 19143 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 19144 19145 if (hasRtlSupport()) { 19146 // Set resolved text alignment flag depending on text alignment flag 19147 final int textAlignment = getRawTextAlignment(); 19148 switch (textAlignment) { 19149 case TEXT_ALIGNMENT_INHERIT: 19150 // Check if we can resolve the text alignment 19151 if (!canResolveTextAlignment()) { 19152 // We cannot do the resolution if there is no parent so use the default 19153 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 19154 // Resolution will need to happen again later 19155 return false; 19156 } 19157 19158 // Parent has not yet resolved, so we still return the default 19159 try { 19160 if (!mParent.isTextAlignmentResolved()) { 19161 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 19162 // Resolution will need to happen again later 19163 return false; 19164 } 19165 } catch (AbstractMethodError e) { 19166 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 19167 " does not fully implement ViewParent", e); 19168 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED | 19169 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 19170 return true; 19171 } 19172 19173 int parentResolvedTextAlignment; 19174 try { 19175 parentResolvedTextAlignment = mParent.getTextAlignment(); 19176 } catch (AbstractMethodError e) { 19177 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 19178 " does not fully implement ViewParent", e); 19179 parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY; 19180 } 19181 switch (parentResolvedTextAlignment) { 19182 case TEXT_ALIGNMENT_GRAVITY: 19183 case TEXT_ALIGNMENT_TEXT_START: 19184 case TEXT_ALIGNMENT_TEXT_END: 19185 case TEXT_ALIGNMENT_CENTER: 19186 case TEXT_ALIGNMENT_VIEW_START: 19187 case TEXT_ALIGNMENT_VIEW_END: 19188 // Resolved text alignment is the same as the parent resolved 19189 // text alignment 19190 mPrivateFlags2 |= 19191 (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 19192 break; 19193 default: 19194 // Use default resolved text alignment 19195 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 19196 } 19197 break; 19198 case TEXT_ALIGNMENT_GRAVITY: 19199 case TEXT_ALIGNMENT_TEXT_START: 19200 case TEXT_ALIGNMENT_TEXT_END: 19201 case TEXT_ALIGNMENT_CENTER: 19202 case TEXT_ALIGNMENT_VIEW_START: 19203 case TEXT_ALIGNMENT_VIEW_END: 19204 // Resolved text alignment is the same as text alignment 19205 mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 19206 break; 19207 default: 19208 // Use default resolved text alignment 19209 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 19210 } 19211 } else { 19212 // Use default resolved text alignment 19213 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 19214 } 19215 19216 // Set the resolved 19217 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED; 19218 return true; 19219 } 19220 19221 /** 19222 * Check if text alignment resolution can be done. 19223 * 19224 * @return true if text alignment resolution can be done otherwise return false. 19225 */ 19226 public boolean canResolveTextAlignment() { 19227 switch (getRawTextAlignment()) { 19228 case TEXT_DIRECTION_INHERIT: 19229 if (mParent != null) { 19230 try { 19231 return mParent.canResolveTextAlignment(); 19232 } catch (AbstractMethodError e) { 19233 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 19234 " does not fully implement ViewParent", e); 19235 } 19236 } 19237 return false; 19238 19239 default: 19240 return true; 19241 } 19242 } 19243 19244 /** 19245 * Reset resolved text alignment. Text alignment will be resolved during a call to 19246 * {@link #onMeasure(int, int)}. 19247 * 19248 * @hide 19249 */ 19250 public void resetResolvedTextAlignment() { 19251 // Reset any previous text alignment resolution 19252 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 19253 // Set to default 19254 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 19255 } 19256 19257 /** 19258 * @return true if text alignment is inherited. 19259 * 19260 * @hide 19261 */ 19262 public boolean isTextAlignmentInherited() { 19263 return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT); 19264 } 19265 19266 /** 19267 * @return true if text alignment is resolved. 19268 */ 19269 public boolean isTextAlignmentResolved() { 19270 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED; 19271 } 19272 19273 /** 19274 * Generate a value suitable for use in {@link #setId(int)}. 19275 * This value will not collide with ID values generated at build time by aapt for R.id. 19276 * 19277 * @return a generated ID value 19278 */ 19279 public static int generateViewId() { 19280 for (;;) { 19281 final int result = sNextGeneratedId.get(); 19282 // aapt-generated IDs have the high byte nonzero; clamp to the range under that. 19283 int newValue = result + 1; 19284 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. 19285 if (sNextGeneratedId.compareAndSet(result, newValue)) { 19286 return result; 19287 } 19288 } 19289 } 19290 19291 /** 19292 * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions. 19293 * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and 19294 * a normal View or a ViewGroup with 19295 * {@link android.view.ViewGroup#isTransitionGroup()} true. 19296 * @hide 19297 */ 19298 public void captureTransitioningViews(List<View> transitioningViews) { 19299 if (getVisibility() == View.VISIBLE) { 19300 transitioningViews.add(this); 19301 } 19302 } 19303 19304 /** 19305 * Adds all Views that have {@link #getTransitionName()} non-null to namedElements. 19306 * @param namedElements Will contain all Views in the hierarchy having a transitionName. 19307 * @hide 19308 */ 19309 public void findNamedViews(Map<String, View> namedElements) { 19310 if (getVisibility() == VISIBLE || mGhostView != null) { 19311 String transitionName = getTransitionName(); 19312 if (transitionName != null) { 19313 namedElements.put(transitionName, this); 19314 } 19315 } 19316 } 19317 19318 // 19319 // Properties 19320 // 19321 /** 19322 * A Property wrapper around the <code>alpha</code> functionality handled by the 19323 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 19324 */ 19325 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 19326 @Override 19327 public void setValue(View object, float value) { 19328 object.setAlpha(value); 19329 } 19330 19331 @Override 19332 public Float get(View object) { 19333 return object.getAlpha(); 19334 } 19335 }; 19336 19337 /** 19338 * A Property wrapper around the <code>translationX</code> functionality handled by the 19339 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 19340 */ 19341 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 19342 @Override 19343 public void setValue(View object, float value) { 19344 object.setTranslationX(value); 19345 } 19346 19347 @Override 19348 public Float get(View object) { 19349 return object.getTranslationX(); 19350 } 19351 }; 19352 19353 /** 19354 * A Property wrapper around the <code>translationY</code> functionality handled by the 19355 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 19356 */ 19357 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 19358 @Override 19359 public void setValue(View object, float value) { 19360 object.setTranslationY(value); 19361 } 19362 19363 @Override 19364 public Float get(View object) { 19365 return object.getTranslationY(); 19366 } 19367 }; 19368 19369 /** 19370 * A Property wrapper around the <code>translationZ</code> functionality handled by the 19371 * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods. 19372 */ 19373 public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") { 19374 @Override 19375 public void setValue(View object, float value) { 19376 object.setTranslationZ(value); 19377 } 19378 19379 @Override 19380 public Float get(View object) { 19381 return object.getTranslationZ(); 19382 } 19383 }; 19384 19385 /** 19386 * A Property wrapper around the <code>x</code> functionality handled by the 19387 * {@link View#setX(float)} and {@link View#getX()} methods. 19388 */ 19389 public static final Property<View, Float> X = new FloatProperty<View>("x") { 19390 @Override 19391 public void setValue(View object, float value) { 19392 object.setX(value); 19393 } 19394 19395 @Override 19396 public Float get(View object) { 19397 return object.getX(); 19398 } 19399 }; 19400 19401 /** 19402 * A Property wrapper around the <code>y</code> functionality handled by the 19403 * {@link View#setY(float)} and {@link View#getY()} methods. 19404 */ 19405 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 19406 @Override 19407 public void setValue(View object, float value) { 19408 object.setY(value); 19409 } 19410 19411 @Override 19412 public Float get(View object) { 19413 return object.getY(); 19414 } 19415 }; 19416 19417 /** 19418 * A Property wrapper around the <code>z</code> functionality handled by the 19419 * {@link View#setZ(float)} and {@link View#getZ()} methods. 19420 */ 19421 public static final Property<View, Float> Z = new FloatProperty<View>("z") { 19422 @Override 19423 public void setValue(View object, float value) { 19424 object.setZ(value); 19425 } 19426 19427 @Override 19428 public Float get(View object) { 19429 return object.getZ(); 19430 } 19431 }; 19432 19433 /** 19434 * A Property wrapper around the <code>rotation</code> functionality handled by the 19435 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 19436 */ 19437 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 19438 @Override 19439 public void setValue(View object, float value) { 19440 object.setRotation(value); 19441 } 19442 19443 @Override 19444 public Float get(View object) { 19445 return object.getRotation(); 19446 } 19447 }; 19448 19449 /** 19450 * A Property wrapper around the <code>rotationX</code> functionality handled by the 19451 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 19452 */ 19453 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 19454 @Override 19455 public void setValue(View object, float value) { 19456 object.setRotationX(value); 19457 } 19458 19459 @Override 19460 public Float get(View object) { 19461 return object.getRotationX(); 19462 } 19463 }; 19464 19465 /** 19466 * A Property wrapper around the <code>rotationY</code> functionality handled by the 19467 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 19468 */ 19469 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 19470 @Override 19471 public void setValue(View object, float value) { 19472 object.setRotationY(value); 19473 } 19474 19475 @Override 19476 public Float get(View object) { 19477 return object.getRotationY(); 19478 } 19479 }; 19480 19481 /** 19482 * A Property wrapper around the <code>scaleX</code> functionality handled by the 19483 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 19484 */ 19485 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 19486 @Override 19487 public void setValue(View object, float value) { 19488 object.setScaleX(value); 19489 } 19490 19491 @Override 19492 public Float get(View object) { 19493 return object.getScaleX(); 19494 } 19495 }; 19496 19497 /** 19498 * A Property wrapper around the <code>scaleY</code> functionality handled by the 19499 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 19500 */ 19501 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 19502 @Override 19503 public void setValue(View object, float value) { 19504 object.setScaleY(value); 19505 } 19506 19507 @Override 19508 public Float get(View object) { 19509 return object.getScaleY(); 19510 } 19511 }; 19512 19513 /** 19514 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 19515 * Each MeasureSpec represents a requirement for either the width or the height. 19516 * A MeasureSpec is comprised of a size and a mode. There are three possible 19517 * modes: 19518 * <dl> 19519 * <dt>UNSPECIFIED</dt> 19520 * <dd> 19521 * The parent has not imposed any constraint on the child. It can be whatever size 19522 * it wants. 19523 * </dd> 19524 * 19525 * <dt>EXACTLY</dt> 19526 * <dd> 19527 * The parent has determined an exact size for the child. The child is going to be 19528 * given those bounds regardless of how big it wants to be. 19529 * </dd> 19530 * 19531 * <dt>AT_MOST</dt> 19532 * <dd> 19533 * The child can be as large as it wants up to the specified size. 19534 * </dd> 19535 * </dl> 19536 * 19537 * MeasureSpecs are implemented as ints to reduce object allocation. This class 19538 * is provided to pack and unpack the <size, mode> tuple into the int. 19539 */ 19540 public static class MeasureSpec { 19541 private static final int MODE_SHIFT = 30; 19542 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 19543 19544 /** 19545 * Measure specification mode: The parent has not imposed any constraint 19546 * on the child. It can be whatever size it wants. 19547 */ 19548 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 19549 19550 /** 19551 * Measure specification mode: The parent has determined an exact size 19552 * for the child. The child is going to be given those bounds regardless 19553 * of how big it wants to be. 19554 */ 19555 public static final int EXACTLY = 1 << MODE_SHIFT; 19556 19557 /** 19558 * Measure specification mode: The child can be as large as it wants up 19559 * to the specified size. 19560 */ 19561 public static final int AT_MOST = 2 << MODE_SHIFT; 19562 19563 /** 19564 * Creates a measure specification based on the supplied size and mode. 19565 * 19566 * The mode must always be one of the following: 19567 * <ul> 19568 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 19569 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 19570 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 19571 * </ul> 19572 * 19573 * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's 19574 * implementation was such that the order of arguments did not matter 19575 * and overflow in either value could impact the resulting MeasureSpec. 19576 * {@link android.widget.RelativeLayout} was affected by this bug. 19577 * Apps targeting API levels greater than 17 will get the fixed, more strict 19578 * behavior.</p> 19579 * 19580 * @param size the size of the measure specification 19581 * @param mode the mode of the measure specification 19582 * @return the measure specification based on size and mode 19583 */ 19584 public static int makeMeasureSpec(int size, int mode) { 19585 if (sUseBrokenMakeMeasureSpec) { 19586 return size + mode; 19587 } else { 19588 return (size & ~MODE_MASK) | (mode & MODE_MASK); 19589 } 19590 } 19591 19592 /** 19593 * Extracts the mode from the supplied measure specification. 19594 * 19595 * @param measureSpec the measure specification to extract the mode from 19596 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 19597 * {@link android.view.View.MeasureSpec#AT_MOST} or 19598 * {@link android.view.View.MeasureSpec#EXACTLY} 19599 */ 19600 public static int getMode(int measureSpec) { 19601 return (measureSpec & MODE_MASK); 19602 } 19603 19604 /** 19605 * Extracts the size from the supplied measure specification. 19606 * 19607 * @param measureSpec the measure specification to extract the size from 19608 * @return the size in pixels defined in the supplied measure specification 19609 */ 19610 public static int getSize(int measureSpec) { 19611 return (measureSpec & ~MODE_MASK); 19612 } 19613 19614 static int adjust(int measureSpec, int delta) { 19615 final int mode = getMode(measureSpec); 19616 if (mode == UNSPECIFIED) { 19617 // No need to adjust size for UNSPECIFIED mode. 19618 return makeMeasureSpec(0, UNSPECIFIED); 19619 } 19620 int size = getSize(measureSpec) + delta; 19621 if (size < 0) { 19622 Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size + 19623 ") spec: " + toString(measureSpec) + " delta: " + delta); 19624 size = 0; 19625 } 19626 return makeMeasureSpec(size, mode); 19627 } 19628 19629 /** 19630 * Returns a String representation of the specified measure 19631 * specification. 19632 * 19633 * @param measureSpec the measure specification to convert to a String 19634 * @return a String with the following format: "MeasureSpec: MODE SIZE" 19635 */ 19636 public static String toString(int measureSpec) { 19637 int mode = getMode(measureSpec); 19638 int size = getSize(measureSpec); 19639 19640 StringBuilder sb = new StringBuilder("MeasureSpec: "); 19641 19642 if (mode == UNSPECIFIED) 19643 sb.append("UNSPECIFIED "); 19644 else if (mode == EXACTLY) 19645 sb.append("EXACTLY "); 19646 else if (mode == AT_MOST) 19647 sb.append("AT_MOST "); 19648 else 19649 sb.append(mode).append(" "); 19650 19651 sb.append(size); 19652 return sb.toString(); 19653 } 19654 } 19655 19656 private final class CheckForLongPress implements Runnable { 19657 private int mOriginalWindowAttachCount; 19658 19659 @Override 19660 public void run() { 19661 if (isPressed() && (mParent != null) 19662 && mOriginalWindowAttachCount == mWindowAttachCount) { 19663 if (performLongClick()) { 19664 mHasPerformedLongPress = true; 19665 } 19666 } 19667 } 19668 19669 public void rememberWindowAttachCount() { 19670 mOriginalWindowAttachCount = mWindowAttachCount; 19671 } 19672 } 19673 19674 private final class CheckForTap implements Runnable { 19675 public float x; 19676 public float y; 19677 19678 @Override 19679 public void run() { 19680 mPrivateFlags &= ~PFLAG_PREPRESSED; 19681 setPressed(true, x, y); 19682 checkForLongClick(ViewConfiguration.getTapTimeout()); 19683 } 19684 } 19685 19686 private final class PerformClick implements Runnable { 19687 @Override 19688 public void run() { 19689 performClick(); 19690 } 19691 } 19692 19693 /** @hide */ 19694 public void hackTurnOffWindowResizeAnim(boolean off) { 19695 mAttachInfo.mTurnOffWindowResizeAnim = off; 19696 } 19697 19698 /** 19699 * This method returns a ViewPropertyAnimator object, which can be used to animate 19700 * specific properties on this View. 19701 * 19702 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 19703 */ 19704 public ViewPropertyAnimator animate() { 19705 if (mAnimator == null) { 19706 mAnimator = new ViewPropertyAnimator(this); 19707 } 19708 return mAnimator; 19709 } 19710 19711 /** 19712 * Sets the name of the View to be used to identify Views in Transitions. 19713 * Names should be unique in the View hierarchy. 19714 * 19715 * @param transitionName The name of the View to uniquely identify it for Transitions. 19716 */ 19717 public final void setTransitionName(String transitionName) { 19718 mTransitionName = transitionName; 19719 } 19720 19721 /** 19722 * Returns the name of the View to be used to identify Views in Transitions. 19723 * Names should be unique in the View hierarchy. 19724 * 19725 * <p>This returns null if the View has not been given a name.</p> 19726 * 19727 * @return The name used of the View to be used to identify Views in Transitions or null 19728 * if no name has been given. 19729 */ 19730 @ViewDebug.ExportedProperty 19731 public String getTransitionName() { 19732 return mTransitionName; 19733 } 19734 19735 /** 19736 * Interface definition for a callback to be invoked when a hardware key event is 19737 * dispatched to this view. The callback will be invoked before the key event is 19738 * given to the view. This is only useful for hardware keyboards; a software input 19739 * method has no obligation to trigger this listener. 19740 */ 19741 public interface OnKeyListener { 19742 /** 19743 * Called when a hardware key is dispatched to a view. This allows listeners to 19744 * get a chance to respond before the target view. 19745 * <p>Key presses in software keyboards will generally NOT trigger this method, 19746 * although some may elect to do so in some situations. Do not assume a 19747 * software input method has to be key-based; even if it is, it may use key presses 19748 * in a different way than you expect, so there is no way to reliably catch soft 19749 * input key presses. 19750 * 19751 * @param v The view the key has been dispatched to. 19752 * @param keyCode The code for the physical key that was pressed 19753 * @param event The KeyEvent object containing full information about 19754 * the event. 19755 * @return True if the listener has consumed the event, false otherwise. 19756 */ 19757 boolean onKey(View v, int keyCode, KeyEvent event); 19758 } 19759 19760 /** 19761 * Interface definition for a callback to be invoked when a touch event is 19762 * dispatched to this view. The callback will be invoked before the touch 19763 * event is given to the view. 19764 */ 19765 public interface OnTouchListener { 19766 /** 19767 * Called when a touch event is dispatched to a view. This allows listeners to 19768 * get a chance to respond before the target view. 19769 * 19770 * @param v The view the touch event has been dispatched to. 19771 * @param event The MotionEvent object containing full information about 19772 * the event. 19773 * @return True if the listener has consumed the event, false otherwise. 19774 */ 19775 boolean onTouch(View v, MotionEvent event); 19776 } 19777 19778 /** 19779 * Interface definition for a callback to be invoked when a hover event is 19780 * dispatched to this view. The callback will be invoked before the hover 19781 * event is given to the view. 19782 */ 19783 public interface OnHoverListener { 19784 /** 19785 * Called when a hover event is dispatched to a view. This allows listeners to 19786 * get a chance to respond before the target view. 19787 * 19788 * @param v The view the hover event has been dispatched to. 19789 * @param event The MotionEvent object containing full information about 19790 * the event. 19791 * @return True if the listener has consumed the event, false otherwise. 19792 */ 19793 boolean onHover(View v, MotionEvent event); 19794 } 19795 19796 /** 19797 * Interface definition for a callback to be invoked when a generic motion event is 19798 * dispatched to this view. The callback will be invoked before the generic motion 19799 * event is given to the view. 19800 */ 19801 public interface OnGenericMotionListener { 19802 /** 19803 * Called when a generic motion event is dispatched to a view. This allows listeners to 19804 * get a chance to respond before the target view. 19805 * 19806 * @param v The view the generic motion event has been dispatched to. 19807 * @param event The MotionEvent object containing full information about 19808 * the event. 19809 * @return True if the listener has consumed the event, false otherwise. 19810 */ 19811 boolean onGenericMotion(View v, MotionEvent event); 19812 } 19813 19814 /** 19815 * Interface definition for a callback to be invoked when a view has been clicked and held. 19816 */ 19817 public interface OnLongClickListener { 19818 /** 19819 * Called when a view has been clicked and held. 19820 * 19821 * @param v The view that was clicked and held. 19822 * 19823 * @return true if the callback consumed the long click, false otherwise. 19824 */ 19825 boolean onLongClick(View v); 19826 } 19827 19828 /** 19829 * Interface definition for a callback to be invoked when a drag is being dispatched 19830 * to this view. The callback will be invoked before the hosting view's own 19831 * onDrag(event) method. If the listener wants to fall back to the hosting view's 19832 * onDrag(event) behavior, it should return 'false' from this callback. 19833 * 19834 * <div class="special reference"> 19835 * <h3>Developer Guides</h3> 19836 * <p>For a guide to implementing drag and drop features, read the 19837 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 19838 * </div> 19839 */ 19840 public interface OnDragListener { 19841 /** 19842 * Called when a drag event is dispatched to a view. This allows listeners 19843 * to get a chance to override base View behavior. 19844 * 19845 * @param v The View that received the drag event. 19846 * @param event The {@link android.view.DragEvent} object for the drag event. 19847 * @return {@code true} if the drag event was handled successfully, or {@code false} 19848 * if the drag event was not handled. Note that {@code false} will trigger the View 19849 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 19850 */ 19851 boolean onDrag(View v, DragEvent event); 19852 } 19853 19854 /** 19855 * Interface definition for a callback to be invoked when the focus state of 19856 * a view changed. 19857 */ 19858 public interface OnFocusChangeListener { 19859 /** 19860 * Called when the focus state of a view has changed. 19861 * 19862 * @param v The view whose state has changed. 19863 * @param hasFocus The new focus state of v. 19864 */ 19865 void onFocusChange(View v, boolean hasFocus); 19866 } 19867 19868 /** 19869 * Interface definition for a callback to be invoked when a view is clicked. 19870 */ 19871 public interface OnClickListener { 19872 /** 19873 * Called when a view has been clicked. 19874 * 19875 * @param v The view that was clicked. 19876 */ 19877 void onClick(View v); 19878 } 19879 19880 /** 19881 * Interface definition for a callback to be invoked when the context menu 19882 * for this view is being built. 19883 */ 19884 public interface OnCreateContextMenuListener { 19885 /** 19886 * Called when the context menu for this view is being built. It is not 19887 * safe to hold onto the menu after this method returns. 19888 * 19889 * @param menu The context menu that is being built 19890 * @param v The view for which the context menu is being built 19891 * @param menuInfo Extra information about the item for which the 19892 * context menu should be shown. This information will vary 19893 * depending on the class of v. 19894 */ 19895 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 19896 } 19897 19898 /** 19899 * Interface definition for a callback to be invoked when the status bar changes 19900 * visibility. This reports <strong>global</strong> changes to the system UI 19901 * state, not what the application is requesting. 19902 * 19903 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 19904 */ 19905 public interface OnSystemUiVisibilityChangeListener { 19906 /** 19907 * Called when the status bar changes visibility because of a call to 19908 * {@link View#setSystemUiVisibility(int)}. 19909 * 19910 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 19911 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}. 19912 * This tells you the <strong>global</strong> state of these UI visibility 19913 * flags, not what your app is currently applying. 19914 */ 19915 public void onSystemUiVisibilityChange(int visibility); 19916 } 19917 19918 /** 19919 * Interface definition for a callback to be invoked when this view is attached 19920 * or detached from its window. 19921 */ 19922 public interface OnAttachStateChangeListener { 19923 /** 19924 * Called when the view is attached to a window. 19925 * @param v The view that was attached 19926 */ 19927 public void onViewAttachedToWindow(View v); 19928 /** 19929 * Called when the view is detached from a window. 19930 * @param v The view that was detached 19931 */ 19932 public void onViewDetachedFromWindow(View v); 19933 } 19934 19935 /** 19936 * Listener for applying window insets on a view in a custom way. 19937 * 19938 * <p>Apps may choose to implement this interface if they want to apply custom policy 19939 * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener 19940 * is set, its 19941 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 19942 * method will be called instead of the View's own 19943 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener 19944 * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply 19945 * the View's normal behavior as part of its own.</p> 19946 */ 19947 public interface OnApplyWindowInsetsListener { 19948 /** 19949 * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set} 19950 * on a View, this listener method will be called instead of the view's own 19951 * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 19952 * 19953 * @param v The view applying window insets 19954 * @param insets The insets to apply 19955 * @return The insets supplied, minus any insets that were consumed 19956 */ 19957 public WindowInsets onApplyWindowInsets(View v, WindowInsets insets); 19958 } 19959 19960 private final class UnsetPressedState implements Runnable { 19961 @Override 19962 public void run() { 19963 setPressed(false); 19964 } 19965 } 19966 19967 /** 19968 * Base class for derived classes that want to save and restore their own 19969 * state in {@link android.view.View#onSaveInstanceState()}. 19970 */ 19971 public static class BaseSavedState extends AbsSavedState { 19972 /** 19973 * Constructor used when reading from a parcel. Reads the state of the superclass. 19974 * 19975 * @param source 19976 */ 19977 public BaseSavedState(Parcel source) { 19978 super(source); 19979 } 19980 19981 /** 19982 * Constructor called by derived classes when creating their SavedState objects 19983 * 19984 * @param superState The state of the superclass of this view 19985 */ 19986 public BaseSavedState(Parcelable superState) { 19987 super(superState); 19988 } 19989 19990 public static final Parcelable.Creator<BaseSavedState> CREATOR = 19991 new Parcelable.Creator<BaseSavedState>() { 19992 public BaseSavedState createFromParcel(Parcel in) { 19993 return new BaseSavedState(in); 19994 } 19995 19996 public BaseSavedState[] newArray(int size) { 19997 return new BaseSavedState[size]; 19998 } 19999 }; 20000 } 20001 20002 /** 20003 * A set of information given to a view when it is attached to its parent 20004 * window. 20005 */ 20006 final static class AttachInfo { 20007 interface Callbacks { 20008 void playSoundEffect(int effectId); 20009 boolean performHapticFeedback(int effectId, boolean always); 20010 } 20011 20012 /** 20013 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 20014 * to a Handler. This class contains the target (View) to invalidate and 20015 * the coordinates of the dirty rectangle. 20016 * 20017 * For performance purposes, this class also implements a pool of up to 20018 * POOL_LIMIT objects that get reused. This reduces memory allocations 20019 * whenever possible. 20020 */ 20021 static class InvalidateInfo { 20022 private static final int POOL_LIMIT = 10; 20023 20024 private static final SynchronizedPool<InvalidateInfo> sPool = 20025 new SynchronizedPool<InvalidateInfo>(POOL_LIMIT); 20026 20027 View target; 20028 20029 int left; 20030 int top; 20031 int right; 20032 int bottom; 20033 20034 public static InvalidateInfo obtain() { 20035 InvalidateInfo instance = sPool.acquire(); 20036 return (instance != null) ? instance : new InvalidateInfo(); 20037 } 20038 20039 public void recycle() { 20040 target = null; 20041 sPool.release(this); 20042 } 20043 } 20044 20045 final IWindowSession mSession; 20046 20047 final IWindow mWindow; 20048 20049 final IBinder mWindowToken; 20050 20051 final Display mDisplay; 20052 20053 final Callbacks mRootCallbacks; 20054 20055 IWindowId mIWindowId; 20056 WindowId mWindowId; 20057 20058 /** 20059 * The top view of the hierarchy. 20060 */ 20061 View mRootView; 20062 20063 IBinder mPanelParentWindowToken; 20064 20065 boolean mHardwareAccelerated; 20066 boolean mHardwareAccelerationRequested; 20067 HardwareRenderer mHardwareRenderer; 20068 List<RenderNode> mPendingAnimatingRenderNodes; 20069 20070 /** 20071 * The state of the display to which the window is attached, as reported 20072 * by {@link Display#getState()}. Note that the display state constants 20073 * declared by {@link Display} do not exactly line up with the screen state 20074 * constants declared by {@link View} (there are more display states than 20075 * screen states). 20076 */ 20077 int mDisplayState = Display.STATE_UNKNOWN; 20078 20079 /** 20080 * Scale factor used by the compatibility mode 20081 */ 20082 float mApplicationScale; 20083 20084 /** 20085 * Indicates whether the application is in compatibility mode 20086 */ 20087 boolean mScalingRequired; 20088 20089 /** 20090 * If set, ViewRootImpl doesn't use its lame animation for when the window resizes. 20091 */ 20092 boolean mTurnOffWindowResizeAnim; 20093 20094 /** 20095 * Left position of this view's window 20096 */ 20097 int mWindowLeft; 20098 20099 /** 20100 * Top position of this view's window 20101 */ 20102 int mWindowTop; 20103 20104 /** 20105 * Indicates whether views need to use 32-bit drawing caches 20106 */ 20107 boolean mUse32BitDrawingCache; 20108 20109 /** 20110 * For windows that are full-screen but using insets to layout inside 20111 * of the screen areas, these are the current insets to appear inside 20112 * the overscan area of the display. 20113 */ 20114 final Rect mOverscanInsets = new Rect(); 20115 20116 /** 20117 * For windows that are full-screen but using insets to layout inside 20118 * of the screen decorations, these are the current insets for the 20119 * content of the window. 20120 */ 20121 final Rect mContentInsets = new Rect(); 20122 20123 /** 20124 * For windows that are full-screen but using insets to layout inside 20125 * of the screen decorations, these are the current insets for the 20126 * actual visible parts of the window. 20127 */ 20128 final Rect mVisibleInsets = new Rect(); 20129 20130 /** 20131 * For windows that are full-screen but using insets to layout inside 20132 * of the screen decorations, these are the current insets for the 20133 * stable system windows. 20134 */ 20135 final Rect mStableInsets = new Rect(); 20136 20137 /** 20138 * The internal insets given by this window. This value is 20139 * supplied by the client (through 20140 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 20141 * be given to the window manager when changed to be used in laying 20142 * out windows behind it. 20143 */ 20144 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 20145 = new ViewTreeObserver.InternalInsetsInfo(); 20146 20147 /** 20148 * Set to true when mGivenInternalInsets is non-empty. 20149 */ 20150 boolean mHasNonEmptyGivenInternalInsets; 20151 20152 /** 20153 * All views in the window's hierarchy that serve as scroll containers, 20154 * used to determine if the window can be resized or must be panned 20155 * to adjust for a soft input area. 20156 */ 20157 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 20158 20159 final KeyEvent.DispatcherState mKeyDispatchState 20160 = new KeyEvent.DispatcherState(); 20161 20162 /** 20163 * Indicates whether the view's window currently has the focus. 20164 */ 20165 boolean mHasWindowFocus; 20166 20167 /** 20168 * The current visibility of the window. 20169 */ 20170 int mWindowVisibility; 20171 20172 /** 20173 * Indicates the time at which drawing started to occur. 20174 */ 20175 long mDrawingTime; 20176 20177 /** 20178 * Indicates whether or not ignoring the DIRTY_MASK flags. 20179 */ 20180 boolean mIgnoreDirtyState; 20181 20182 /** 20183 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 20184 * to avoid clearing that flag prematurely. 20185 */ 20186 boolean mSetIgnoreDirtyState = false; 20187 20188 /** 20189 * Indicates whether the view's window is currently in touch mode. 20190 */ 20191 boolean mInTouchMode; 20192 20193 /** 20194 * Indicates whether the view has requested unbuffered input dispatching for the current 20195 * event stream. 20196 */ 20197 boolean mUnbufferedDispatchRequested; 20198 20199 /** 20200 * Indicates that ViewAncestor should trigger a global layout change 20201 * the next time it performs a traversal 20202 */ 20203 boolean mRecomputeGlobalAttributes; 20204 20205 /** 20206 * Always report new attributes at next traversal. 20207 */ 20208 boolean mForceReportNewAttributes; 20209 20210 /** 20211 * Set during a traveral if any views want to keep the screen on. 20212 */ 20213 boolean mKeepScreenOn; 20214 20215 /** 20216 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 20217 */ 20218 int mSystemUiVisibility; 20219 20220 /** 20221 * Hack to force certain system UI visibility flags to be cleared. 20222 */ 20223 int mDisabledSystemUiVisibility; 20224 20225 /** 20226 * Last global system UI visibility reported by the window manager. 20227 */ 20228 int mGlobalSystemUiVisibility; 20229 20230 /** 20231 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 20232 * attached. 20233 */ 20234 boolean mHasSystemUiListeners; 20235 20236 /** 20237 * Set if the window has requested to extend into the overscan region 20238 * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN. 20239 */ 20240 boolean mOverscanRequested; 20241 20242 /** 20243 * Set if the visibility of any views has changed. 20244 */ 20245 boolean mViewVisibilityChanged; 20246 20247 /** 20248 * Set to true if a view has been scrolled. 20249 */ 20250 boolean mViewScrollChanged; 20251 20252 /** 20253 * Set to true if high contrast mode enabled 20254 */ 20255 boolean mHighContrastText; 20256 20257 /** 20258 * Global to the view hierarchy used as a temporary for dealing with 20259 * x/y points in the transparent region computations. 20260 */ 20261 final int[] mTransparentLocation = new int[2]; 20262 20263 /** 20264 * Global to the view hierarchy used as a temporary for dealing with 20265 * x/y points in the ViewGroup.invalidateChild implementation. 20266 */ 20267 final int[] mInvalidateChildLocation = new int[2]; 20268 20269 /** 20270 * Global to the view hierarchy used as a temporary for dealng with 20271 * computing absolute on-screen location. 20272 */ 20273 final int[] mTmpLocation = new int[2]; 20274 20275 /** 20276 * Global to the view hierarchy used as a temporary for dealing with 20277 * x/y location when view is transformed. 20278 */ 20279 final float[] mTmpTransformLocation = new float[2]; 20280 20281 /** 20282 * The view tree observer used to dispatch global events like 20283 * layout, pre-draw, touch mode change, etc. 20284 */ 20285 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 20286 20287 /** 20288 * A Canvas used by the view hierarchy to perform bitmap caching. 20289 */ 20290 Canvas mCanvas; 20291 20292 /** 20293 * The view root impl. 20294 */ 20295 final ViewRootImpl mViewRootImpl; 20296 20297 /** 20298 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 20299 * handler can be used to pump events in the UI events queue. 20300 */ 20301 final Handler mHandler; 20302 20303 /** 20304 * Temporary for use in computing invalidate rectangles while 20305 * calling up the hierarchy. 20306 */ 20307 final Rect mTmpInvalRect = new Rect(); 20308 20309 /** 20310 * Temporary for use in computing hit areas with transformed views 20311 */ 20312 final RectF mTmpTransformRect = new RectF(); 20313 20314 /** 20315 * Temporary for use in computing hit areas with transformed views 20316 */ 20317 final RectF mTmpTransformRect1 = new RectF(); 20318 20319 /** 20320 * Temporary list of rectanges. 20321 */ 20322 final List<RectF> mTmpRectList = new ArrayList<>(); 20323 20324 /** 20325 * Temporary for use in transforming invalidation rect 20326 */ 20327 final Matrix mTmpMatrix = new Matrix(); 20328 20329 /** 20330 * Temporary for use in transforming invalidation rect 20331 */ 20332 final Transformation mTmpTransformation = new Transformation(); 20333 20334 /** 20335 * Temporary for use in querying outlines from OutlineProviders 20336 */ 20337 final Outline mTmpOutline = new Outline(); 20338 20339 /** 20340 * Temporary list for use in collecting focusable descendents of a view. 20341 */ 20342 final ArrayList<View> mTempArrayList = new ArrayList<View>(24); 20343 20344 /** 20345 * The id of the window for accessibility purposes. 20346 */ 20347 int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 20348 20349 /** 20350 * Flags related to accessibility processing. 20351 * 20352 * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS 20353 * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS 20354 */ 20355 int mAccessibilityFetchFlags; 20356 20357 /** 20358 * The drawable for highlighting accessibility focus. 20359 */ 20360 Drawable mAccessibilityFocusDrawable; 20361 20362 /** 20363 * Show where the margins, bounds and layout bounds are for each view. 20364 */ 20365 boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false); 20366 20367 /** 20368 * Point used to compute visible regions. 20369 */ 20370 final Point mPoint = new Point(); 20371 20372 /** 20373 * Used to track which View originated a requestLayout() call, used when 20374 * requestLayout() is called during layout. 20375 */ 20376 View mViewRequestingLayout; 20377 20378 /** 20379 * Creates a new set of attachment information with the specified 20380 * events handler and thread. 20381 * 20382 * @param handler the events handler the view must use 20383 */ 20384 AttachInfo(IWindowSession session, IWindow window, Display display, 20385 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) { 20386 mSession = session; 20387 mWindow = window; 20388 mWindowToken = window.asBinder(); 20389 mDisplay = display; 20390 mViewRootImpl = viewRootImpl; 20391 mHandler = handler; 20392 mRootCallbacks = effectPlayer; 20393 } 20394 } 20395 20396 /** 20397 * <p>ScrollabilityCache holds various fields used by a View when scrolling 20398 * is supported. This avoids keeping too many unused fields in most 20399 * instances of View.</p> 20400 */ 20401 private static class ScrollabilityCache implements Runnable { 20402 20403 /** 20404 * Scrollbars are not visible 20405 */ 20406 public static final int OFF = 0; 20407 20408 /** 20409 * Scrollbars are visible 20410 */ 20411 public static final int ON = 1; 20412 20413 /** 20414 * Scrollbars are fading away 20415 */ 20416 public static final int FADING = 2; 20417 20418 public boolean fadeScrollBars; 20419 20420 public int fadingEdgeLength; 20421 public int scrollBarDefaultDelayBeforeFade; 20422 public int scrollBarFadeDuration; 20423 20424 public int scrollBarSize; 20425 public ScrollBarDrawable scrollBar; 20426 public float[] interpolatorValues; 20427 public View host; 20428 20429 public final Paint paint; 20430 public final Matrix matrix; 20431 public Shader shader; 20432 20433 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 20434 20435 private static final float[] OPAQUE = { 255 }; 20436 private static final float[] TRANSPARENT = { 0.0f }; 20437 20438 /** 20439 * When fading should start. This time moves into the future every time 20440 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 20441 */ 20442 public long fadeStartTime; 20443 20444 20445 /** 20446 * The current state of the scrollbars: ON, OFF, or FADING 20447 */ 20448 public int state = OFF; 20449 20450 private int mLastColor; 20451 20452 public ScrollabilityCache(ViewConfiguration configuration, View host) { 20453 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 20454 scrollBarSize = configuration.getScaledScrollBarSize(); 20455 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 20456 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 20457 20458 paint = new Paint(); 20459 matrix = new Matrix(); 20460 // use use a height of 1, and then wack the matrix each time we 20461 // actually use it. 20462 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 20463 paint.setShader(shader); 20464 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 20465 20466 this.host = host; 20467 } 20468 20469 public void setFadeColor(int color) { 20470 if (color != mLastColor) { 20471 mLastColor = color; 20472 20473 if (color != 0) { 20474 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 20475 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 20476 paint.setShader(shader); 20477 // Restore the default transfer mode (src_over) 20478 paint.setXfermode(null); 20479 } else { 20480 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 20481 paint.setShader(shader); 20482 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 20483 } 20484 } 20485 } 20486 20487 public void run() { 20488 long now = AnimationUtils.currentAnimationTimeMillis(); 20489 if (now >= fadeStartTime) { 20490 20491 // the animation fades the scrollbars out by changing 20492 // the opacity (alpha) from fully opaque to fully 20493 // transparent 20494 int nextFrame = (int) now; 20495 int framesCount = 0; 20496 20497 Interpolator interpolator = scrollBarInterpolator; 20498 20499 // Start opaque 20500 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 20501 20502 // End transparent 20503 nextFrame += scrollBarFadeDuration; 20504 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 20505 20506 state = FADING; 20507 20508 // Kick off the fade animation 20509 host.invalidate(true); 20510 } 20511 } 20512 } 20513 20514 /** 20515 * Resuable callback for sending 20516 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 20517 */ 20518 private class SendViewScrolledAccessibilityEvent implements Runnable { 20519 public volatile boolean mIsPending; 20520 20521 public void run() { 20522 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 20523 mIsPending = false; 20524 } 20525 } 20526 20527 /** 20528 * <p> 20529 * This class represents a delegate that can be registered in a {@link View} 20530 * to enhance accessibility support via composition rather via inheritance. 20531 * It is specifically targeted to widget developers that extend basic View 20532 * classes i.e. classes in package android.view, that would like their 20533 * applications to be backwards compatible. 20534 * </p> 20535 * <div class="special reference"> 20536 * <h3>Developer Guides</h3> 20537 * <p>For more information about making applications accessible, read the 20538 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a> 20539 * developer guide.</p> 20540 * </div> 20541 * <p> 20542 * A scenario in which a developer would like to use an accessibility delegate 20543 * is overriding a method introduced in a later API version then the minimal API 20544 * version supported by the application. For example, the method 20545 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 20546 * in API version 4 when the accessibility APIs were first introduced. If a 20547 * developer would like his application to run on API version 4 devices (assuming 20548 * all other APIs used by the application are version 4 or lower) and take advantage 20549 * of this method, instead of overriding the method which would break the application's 20550 * backwards compatibility, he can override the corresponding method in this 20551 * delegate and register the delegate in the target View if the API version of 20552 * the system is high enough i.e. the API version is same or higher to the API 20553 * version that introduced 20554 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 20555 * </p> 20556 * <p> 20557 * Here is an example implementation: 20558 * </p> 20559 * <code><pre><p> 20560 * if (Build.VERSION.SDK_INT >= 14) { 20561 * // If the API version is equal of higher than the version in 20562 * // which onInitializeAccessibilityNodeInfo was introduced we 20563 * // register a delegate with a customized implementation. 20564 * View view = findViewById(R.id.view_id); 20565 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 20566 * public void onInitializeAccessibilityNodeInfo(View host, 20567 * AccessibilityNodeInfo info) { 20568 * // Let the default implementation populate the info. 20569 * super.onInitializeAccessibilityNodeInfo(host, info); 20570 * // Set some other information. 20571 * info.setEnabled(host.isEnabled()); 20572 * } 20573 * }); 20574 * } 20575 * </code></pre></p> 20576 * <p> 20577 * This delegate contains methods that correspond to the accessibility methods 20578 * in View. If a delegate has been specified the implementation in View hands 20579 * off handling to the corresponding method in this delegate. The default 20580 * implementation the delegate methods behaves exactly as the corresponding 20581 * method in View for the case of no accessibility delegate been set. Hence, 20582 * to customize the behavior of a View method, clients can override only the 20583 * corresponding delegate method without altering the behavior of the rest 20584 * accessibility related methods of the host view. 20585 * </p> 20586 */ 20587 public static class AccessibilityDelegate { 20588 20589 /** 20590 * Sends an accessibility event of the given type. If accessibility is not 20591 * enabled this method has no effect. 20592 * <p> 20593 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 20594 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 20595 * been set. 20596 * </p> 20597 * 20598 * @param host The View hosting the delegate. 20599 * @param eventType The type of the event to send. 20600 * 20601 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 20602 */ 20603 public void sendAccessibilityEvent(View host, int eventType) { 20604 host.sendAccessibilityEventInternal(eventType); 20605 } 20606 20607 /** 20608 * Performs the specified accessibility action on the view. For 20609 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 20610 * <p> 20611 * The default implementation behaves as 20612 * {@link View#performAccessibilityAction(int, Bundle) 20613 * View#performAccessibilityAction(int, Bundle)} for the case of 20614 * no accessibility delegate been set. 20615 * </p> 20616 * 20617 * @param action The action to perform. 20618 * @return Whether the action was performed. 20619 * 20620 * @see View#performAccessibilityAction(int, Bundle) 20621 * View#performAccessibilityAction(int, Bundle) 20622 */ 20623 public boolean performAccessibilityAction(View host, int action, Bundle args) { 20624 return host.performAccessibilityActionInternal(action, args); 20625 } 20626 20627 /** 20628 * Sends an accessibility event. This method behaves exactly as 20629 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 20630 * empty {@link AccessibilityEvent} and does not perform a check whether 20631 * accessibility is enabled. 20632 * <p> 20633 * The default implementation behaves as 20634 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20635 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 20636 * the case of no accessibility delegate been set. 20637 * </p> 20638 * 20639 * @param host The View hosting the delegate. 20640 * @param event The event to send. 20641 * 20642 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20643 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20644 */ 20645 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 20646 host.sendAccessibilityEventUncheckedInternal(event); 20647 } 20648 20649 /** 20650 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 20651 * to its children for adding their text content to the event. 20652 * <p> 20653 * The default implementation behaves as 20654 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20655 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 20656 * the case of no accessibility delegate been set. 20657 * </p> 20658 * 20659 * @param host The View hosting the delegate. 20660 * @param event The event. 20661 * @return True if the event population was completed. 20662 * 20663 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20664 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20665 */ 20666 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 20667 return host.dispatchPopulateAccessibilityEventInternal(event); 20668 } 20669 20670 /** 20671 * Gives a chance to the host View to populate the accessibility event with its 20672 * text content. 20673 * <p> 20674 * The default implementation behaves as 20675 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 20676 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 20677 * the case of no accessibility delegate been set. 20678 * </p> 20679 * 20680 * @param host The View hosting the delegate. 20681 * @param event The accessibility event which to populate. 20682 * 20683 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 20684 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 20685 */ 20686 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 20687 host.onPopulateAccessibilityEventInternal(event); 20688 } 20689 20690 /** 20691 * Initializes an {@link AccessibilityEvent} with information about the 20692 * the host View which is the event source. 20693 * <p> 20694 * The default implementation behaves as 20695 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 20696 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 20697 * the case of no accessibility delegate been set. 20698 * </p> 20699 * 20700 * @param host The View hosting the delegate. 20701 * @param event The event to initialize. 20702 * 20703 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 20704 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 20705 */ 20706 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 20707 host.onInitializeAccessibilityEventInternal(event); 20708 } 20709 20710 /** 20711 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 20712 * <p> 20713 * The default implementation behaves as 20714 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20715 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 20716 * the case of no accessibility delegate been set. 20717 * </p> 20718 * 20719 * @param host The View hosting the delegate. 20720 * @param info The instance to initialize. 20721 * 20722 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20723 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20724 */ 20725 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 20726 host.onInitializeAccessibilityNodeInfoInternal(info); 20727 } 20728 20729 /** 20730 * Called when a child of the host View has requested sending an 20731 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 20732 * to augment the event. 20733 * <p> 20734 * The default implementation behaves as 20735 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20736 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 20737 * the case of no accessibility delegate been set. 20738 * </p> 20739 * 20740 * @param host The View hosting the delegate. 20741 * @param child The child which requests sending the event. 20742 * @param event The event to be sent. 20743 * @return True if the event should be sent 20744 * 20745 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20746 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20747 */ 20748 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 20749 AccessibilityEvent event) { 20750 return host.onRequestSendAccessibilityEventInternal(child, event); 20751 } 20752 20753 /** 20754 * Gets the provider for managing a virtual view hierarchy rooted at this View 20755 * and reported to {@link android.accessibilityservice.AccessibilityService}s 20756 * that explore the window content. 20757 * <p> 20758 * The default implementation behaves as 20759 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 20760 * the case of no accessibility delegate been set. 20761 * </p> 20762 * 20763 * @return The provider. 20764 * 20765 * @see AccessibilityNodeProvider 20766 */ 20767 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 20768 return null; 20769 } 20770 20771 /** 20772 * Returns an {@link AccessibilityNodeInfo} representing the host view from the 20773 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 20774 * This method is responsible for obtaining an accessibility node info from a 20775 * pool of reusable instances and calling 20776 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host 20777 * view to initialize the former. 20778 * <p> 20779 * <strong>Note:</strong> The client is responsible for recycling the obtained 20780 * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object 20781 * creation. 20782 * </p> 20783 * <p> 20784 * The default implementation behaves as 20785 * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for 20786 * the case of no accessibility delegate been set. 20787 * </p> 20788 * @return A populated {@link AccessibilityNodeInfo}. 20789 * 20790 * @see AccessibilityNodeInfo 20791 * 20792 * @hide 20793 */ 20794 public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) { 20795 return host.createAccessibilityNodeInfoInternal(); 20796 } 20797 } 20798 20799 private class MatchIdPredicate implements Predicate<View> { 20800 public int mId; 20801 20802 @Override 20803 public boolean apply(View view) { 20804 return (view.mID == mId); 20805 } 20806 } 20807 20808 private class MatchLabelForPredicate implements Predicate<View> { 20809 private int mLabeledId; 20810 20811 @Override 20812 public boolean apply(View view) { 20813 return (view.mLabelForId == mLabeledId); 20814 } 20815 } 20816 20817 private class SendViewStateChangedAccessibilityEvent implements Runnable { 20818 private int mChangeTypes = 0; 20819 private boolean mPosted; 20820 private boolean mPostedWithDelay; 20821 private long mLastEventTimeMillis; 20822 20823 @Override 20824 public void run() { 20825 mPosted = false; 20826 mPostedWithDelay = false; 20827 mLastEventTimeMillis = SystemClock.uptimeMillis(); 20828 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 20829 final AccessibilityEvent event = AccessibilityEvent.obtain(); 20830 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 20831 event.setContentChangeTypes(mChangeTypes); 20832 sendAccessibilityEventUnchecked(event); 20833 } 20834 mChangeTypes = 0; 20835 } 20836 20837 public void runOrPost(int changeType) { 20838 mChangeTypes |= changeType; 20839 20840 // If this is a live region or the child of a live region, collect 20841 // all events from this frame and send them on the next frame. 20842 if (inLiveRegion()) { 20843 // If we're already posted with a delay, remove that. 20844 if (mPostedWithDelay) { 20845 removeCallbacks(this); 20846 mPostedWithDelay = false; 20847 } 20848 // Only post if we're not already posted. 20849 if (!mPosted) { 20850 post(this); 20851 mPosted = true; 20852 } 20853 return; 20854 } 20855 20856 if (mPosted) { 20857 return; 20858 } 20859 20860 final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis; 20861 final long minEventIntevalMillis = 20862 ViewConfiguration.getSendRecurringAccessibilityEventsInterval(); 20863 if (timeSinceLastMillis >= minEventIntevalMillis) { 20864 removeCallbacks(this); 20865 run(); 20866 } else { 20867 postDelayed(this, minEventIntevalMillis - timeSinceLastMillis); 20868 mPostedWithDelay = true; 20869 } 20870 } 20871 } 20872 20873 private boolean inLiveRegion() { 20874 if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) { 20875 return true; 20876 } 20877 20878 ViewParent parent = getParent(); 20879 while (parent instanceof View) { 20880 if (((View) parent).getAccessibilityLiveRegion() 20881 != View.ACCESSIBILITY_LIVE_REGION_NONE) { 20882 return true; 20883 } 20884 parent = parent.getParent(); 20885 } 20886 20887 return false; 20888 } 20889 20890 /** 20891 * Dump all private flags in readable format, useful for documentation and 20892 * sanity checking. 20893 */ 20894 private static void dumpFlags() { 20895 final HashMap<String, String> found = Maps.newHashMap(); 20896 try { 20897 for (Field field : View.class.getDeclaredFields()) { 20898 final int modifiers = field.getModifiers(); 20899 if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { 20900 if (field.getType().equals(int.class)) { 20901 final int value = field.getInt(null); 20902 dumpFlag(found, field.getName(), value); 20903 } else if (field.getType().equals(int[].class)) { 20904 final int[] values = (int[]) field.get(null); 20905 for (int i = 0; i < values.length; i++) { 20906 dumpFlag(found, field.getName() + "[" + i + "]", values[i]); 20907 } 20908 } 20909 } 20910 } 20911 } catch (IllegalAccessException e) { 20912 throw new RuntimeException(e); 20913 } 20914 20915 final ArrayList<String> keys = Lists.newArrayList(); 20916 keys.addAll(found.keySet()); 20917 Collections.sort(keys); 20918 for (String key : keys) { 20919 Log.d(VIEW_LOG_TAG, found.get(key)); 20920 } 20921 } 20922 20923 private static void dumpFlag(HashMap<String, String> found, String name, int value) { 20924 // Sort flags by prefix, then by bits, always keeping unique keys 20925 final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' '); 20926 final int prefix = name.indexOf('_'); 20927 final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name; 20928 final String output = bits + " " + name; 20929 found.put(key, output); 20930 } 20931} 20932