View.java revision 70850ea258cbf91477efa57a1f1a23cc0044cc93
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.view; 18 19import android.animation.AnimatorInflater; 20import android.animation.StateListAnimator; 21import android.annotation.IntDef; 22import android.annotation.NonNull; 23import android.annotation.Nullable; 24import android.content.ClipData; 25import android.content.Context; 26import android.content.res.ColorStateList; 27import android.content.res.Configuration; 28import android.content.res.Resources; 29import android.content.res.TypedArray; 30import android.graphics.Bitmap; 31import android.graphics.Canvas; 32import android.graphics.Insets; 33import android.graphics.Interpolator; 34import android.graphics.LinearGradient; 35import android.graphics.Matrix; 36import android.graphics.Outline; 37import android.graphics.Paint; 38import android.graphics.Path; 39import android.graphics.PathMeasure; 40import android.graphics.PixelFormat; 41import android.graphics.Point; 42import android.graphics.PorterDuff; 43import android.graphics.PorterDuffXfermode; 44import android.graphics.Rect; 45import android.graphics.RectF; 46import android.graphics.Region; 47import android.graphics.Shader; 48import android.graphics.drawable.ColorDrawable; 49import android.graphics.drawable.Drawable; 50import android.hardware.display.DisplayManagerGlobal; 51import android.os.Bundle; 52import android.os.Handler; 53import android.os.IBinder; 54import android.os.Parcel; 55import android.os.Parcelable; 56import android.os.RemoteException; 57import android.os.SystemClock; 58import android.os.SystemProperties; 59import android.os.Trace; 60import android.text.TextUtils; 61import android.util.AttributeSet; 62import android.util.FloatProperty; 63import android.util.LayoutDirection; 64import android.util.Log; 65import android.util.LongSparseLongArray; 66import android.util.Pools.SynchronizedPool; 67import android.util.Property; 68import android.util.SparseArray; 69import android.util.SuperNotCalledException; 70import android.util.TypedValue; 71import android.view.ContextMenu.ContextMenuInfo; 72import android.view.AccessibilityIterators.TextSegmentIterator; 73import android.view.AccessibilityIterators.CharacterTextSegmentIterator; 74import android.view.AccessibilityIterators.WordTextSegmentIterator; 75import android.view.AccessibilityIterators.ParagraphTextSegmentIterator; 76import android.view.accessibility.AccessibilityEvent; 77import android.view.accessibility.AccessibilityEventSource; 78import android.view.accessibility.AccessibilityManager; 79import android.view.accessibility.AccessibilityNodeInfo; 80import android.view.accessibility.AccessibilityNodeProvider; 81import android.view.animation.Animation; 82import android.view.animation.AnimationUtils; 83import android.view.animation.Transformation; 84import android.view.inputmethod.EditorInfo; 85import android.view.inputmethod.InputConnection; 86import android.view.inputmethod.InputMethodManager; 87import android.widget.ScrollBarDrawable; 88 89import static android.os.Build.VERSION_CODES.*; 90import static java.lang.Math.max; 91 92import com.android.internal.R; 93import com.android.internal.util.Predicate; 94import com.android.internal.view.menu.MenuBuilder; 95import com.google.android.collect.Lists; 96import com.google.android.collect.Maps; 97 98import java.lang.annotation.Retention; 99import java.lang.annotation.RetentionPolicy; 100import java.lang.ref.WeakReference; 101import java.lang.reflect.Field; 102import java.lang.reflect.InvocationTargetException; 103import java.lang.reflect.Method; 104import java.lang.reflect.Modifier; 105import java.util.ArrayList; 106import java.util.Arrays; 107import java.util.Collections; 108import java.util.HashMap; 109import java.util.List; 110import java.util.Locale; 111import java.util.Map; 112import java.util.concurrent.CopyOnWriteArrayList; 113import java.util.concurrent.atomic.AtomicInteger; 114 115/** 116 * <p> 117 * This class represents the basic building block for user interface components. A View 118 * occupies a rectangular area on the screen and is responsible for drawing and 119 * event handling. View is the base class for <em>widgets</em>, which are 120 * used to create interactive UI components (buttons, text fields, etc.). The 121 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which 122 * are invisible containers that hold other Views (or other ViewGroups) and define 123 * their layout properties. 124 * </p> 125 * 126 * <div class="special reference"> 127 * <h3>Developer Guides</h3> 128 * <p>For information about using this class to develop your application's user interface, 129 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide. 130 * </div> 131 * 132 * <a name="Using"></a> 133 * <h3>Using Views</h3> 134 * <p> 135 * All of the views in a window are arranged in a single tree. You can add views 136 * either from code or by specifying a tree of views in one or more XML layout 137 * files. There are many specialized subclasses of views that act as controls or 138 * are capable of displaying text, images, or other content. 139 * </p> 140 * <p> 141 * Once you have created a tree of views, there are typically a few types of 142 * common operations you may wish to perform: 143 * <ul> 144 * <li><strong>Set properties:</strong> for example setting the text of a 145 * {@link android.widget.TextView}. The available properties and the methods 146 * that set them will vary among the different subclasses of views. Note that 147 * properties that are known at build time can be set in the XML layout 148 * files.</li> 149 * <li><strong>Set focus:</strong> The framework will handled moving focus in 150 * response to user input. To force focus to a specific view, call 151 * {@link #requestFocus}.</li> 152 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 153 * that will be notified when something interesting happens to the view. For 154 * example, all views will let you set a listener to be notified when the view 155 * gains or loses focus. You can register such a listener using 156 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}. 157 * Other view subclasses offer more specialized listeners. For example, a Button 158 * exposes a listener to notify clients when the button is clicked.</li> 159 * <li><strong>Set visibility:</strong> You can hide or show views using 160 * {@link #setVisibility(int)}.</li> 161 * </ul> 162 * </p> 163 * <p><em> 164 * Note: The Android framework is responsible for measuring, laying out and 165 * drawing views. You should not call methods that perform these actions on 166 * views yourself unless you are actually implementing a 167 * {@link android.view.ViewGroup}. 168 * </em></p> 169 * 170 * <a name="Lifecycle"></a> 171 * <h3>Implementing a Custom View</h3> 172 * 173 * <p> 174 * To implement a custom view, you will usually begin by providing overrides for 175 * some of the standard methods that the framework calls on all views. You do 176 * not need to override all of these methods. In fact, you can start by just 177 * overriding {@link #onDraw(android.graphics.Canvas)}. 178 * <table border="2" width="85%" align="center" cellpadding="5"> 179 * <thead> 180 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 181 * </thead> 182 * 183 * <tbody> 184 * <tr> 185 * <td rowspan="2">Creation</td> 186 * <td>Constructors</td> 187 * <td>There is a form of the constructor that are called when the view 188 * is created from code and a form that is called when the view is 189 * inflated from a layout file. The second form should parse and apply 190 * any attributes defined in the layout file. 191 * </td> 192 * </tr> 193 * <tr> 194 * <td><code>{@link #onFinishInflate()}</code></td> 195 * <td>Called after a view and all of its children has been inflated 196 * from XML.</td> 197 * </tr> 198 * 199 * <tr> 200 * <td rowspan="3">Layout</td> 201 * <td><code>{@link #onMeasure(int, int)}</code></td> 202 * <td>Called to determine the size requirements for this view and all 203 * of its children. 204 * </td> 205 * </tr> 206 * <tr> 207 * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td> 208 * <td>Called when this view should assign a size and position to all 209 * of its children. 210 * </td> 211 * </tr> 212 * <tr> 213 * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td> 214 * <td>Called when the size of this view has changed. 215 * </td> 216 * </tr> 217 * 218 * <tr> 219 * <td>Drawing</td> 220 * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td> 221 * <td>Called when the view should render its content. 222 * </td> 223 * </tr> 224 * 225 * <tr> 226 * <td rowspan="4">Event processing</td> 227 * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td> 228 * <td>Called when a new hardware key event occurs. 229 * </td> 230 * </tr> 231 * <tr> 232 * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td> 233 * <td>Called when a hardware key up event occurs. 234 * </td> 235 * </tr> 236 * <tr> 237 * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td> 238 * <td>Called when a trackball motion event occurs. 239 * </td> 240 * </tr> 241 * <tr> 242 * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td> 243 * <td>Called when a touch screen motion event occurs. 244 * </td> 245 * </tr> 246 * 247 * <tr> 248 * <td rowspan="2">Focus</td> 249 * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td> 250 * <td>Called when the view gains or loses focus. 251 * </td> 252 * </tr> 253 * 254 * <tr> 255 * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td> 256 * <td>Called when the window containing the view gains or loses focus. 257 * </td> 258 * </tr> 259 * 260 * <tr> 261 * <td rowspan="3">Attaching</td> 262 * <td><code>{@link #onAttachedToWindow()}</code></td> 263 * <td>Called when the view is attached to a window. 264 * </td> 265 * </tr> 266 * 267 * <tr> 268 * <td><code>{@link #onDetachedFromWindow}</code></td> 269 * <td>Called when the view is detached from its window. 270 * </td> 271 * </tr> 272 * 273 * <tr> 274 * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td> 275 * <td>Called when the visibility of the window containing the view 276 * has changed. 277 * </td> 278 * </tr> 279 * </tbody> 280 * 281 * </table> 282 * </p> 283 * 284 * <a name="IDs"></a> 285 * <h3>IDs</h3> 286 * Views may have an integer id associated with them. These ids are typically 287 * assigned in the layout XML files, and are used to find specific views within 288 * the view tree. A common pattern is to: 289 * <ul> 290 * <li>Define a Button in the layout file and assign it a unique ID. 291 * <pre> 292 * <Button 293 * android:id="@+id/my_button" 294 * android:layout_width="wrap_content" 295 * android:layout_height="wrap_content" 296 * android:text="@string/my_button_text"/> 297 * </pre></li> 298 * <li>From the onCreate method of an Activity, find the Button 299 * <pre class="prettyprint"> 300 * Button myButton = (Button) findViewById(R.id.my_button); 301 * </pre></li> 302 * </ul> 303 * <p> 304 * View IDs need not be unique throughout the tree, but it is good practice to 305 * ensure that they are at least unique within the part of the tree you are 306 * searching. 307 * </p> 308 * 309 * <a name="Position"></a> 310 * <h3>Position</h3> 311 * <p> 312 * The geometry of a view is that of a rectangle. A view has a location, 313 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 314 * two dimensions, expressed as a width and a height. The unit for location 315 * and dimensions is the pixel. 316 * </p> 317 * 318 * <p> 319 * It is possible to retrieve the location of a view by invoking the methods 320 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 321 * coordinate of the rectangle representing the view. The latter returns the 322 * top, or Y, coordinate of the rectangle representing the view. These methods 323 * both return the location of the view relative to its parent. For instance, 324 * when getLeft() returns 20, that means the view is located 20 pixels to the 325 * right of the left edge of its direct parent. 326 * </p> 327 * 328 * <p> 329 * In addition, several convenience methods are offered to avoid unnecessary 330 * computations, namely {@link #getRight()} and {@link #getBottom()}. 331 * These methods return the coordinates of the right and bottom edges of the 332 * rectangle representing the view. For instance, calling {@link #getRight()} 333 * is similar to the following computation: <code>getLeft() + getWidth()</code> 334 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 335 * </p> 336 * 337 * <a name="SizePaddingMargins"></a> 338 * <h3>Size, padding and margins</h3> 339 * <p> 340 * The size of a view is expressed with a width and a height. A view actually 341 * possess two pairs of width and height values. 342 * </p> 343 * 344 * <p> 345 * The first pair is known as <em>measured width</em> and 346 * <em>measured height</em>. These dimensions define how big a view wants to be 347 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 348 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 349 * and {@link #getMeasuredHeight()}. 350 * </p> 351 * 352 * <p> 353 * The second pair is simply known as <em>width</em> and <em>height</em>, or 354 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 355 * dimensions define the actual size of the view on screen, at drawing time and 356 * after layout. These values may, but do not have to, be different from the 357 * measured width and height. The width and height can be obtained by calling 358 * {@link #getWidth()} and {@link #getHeight()}. 359 * </p> 360 * 361 * <p> 362 * To measure its dimensions, a view takes into account its padding. The padding 363 * is expressed in pixels for the left, top, right and bottom parts of the view. 364 * Padding can be used to offset the content of the view by a specific amount of 365 * pixels. For instance, a left padding of 2 will push the view's content by 366 * 2 pixels to the right of the left edge. Padding can be set using the 367 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)} 368 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 369 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()}, 370 * {@link #getPaddingEnd()}. 371 * </p> 372 * 373 * <p> 374 * Even though a view can define a padding, it does not provide any support for 375 * margins. However, view groups provide such a support. Refer to 376 * {@link android.view.ViewGroup} and 377 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 378 * </p> 379 * 380 * <a name="Layout"></a> 381 * <h3>Layout</h3> 382 * <p> 383 * Layout is a two pass process: a measure pass and a layout pass. The measuring 384 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 385 * of the view tree. Each view pushes dimension specifications down the tree 386 * during the recursion. At the end of the measure pass, every view has stored 387 * its measurements. The second pass happens in 388 * {@link #layout(int,int,int,int)} and is also top-down. During 389 * this pass each parent is responsible for positioning all of its children 390 * using the sizes computed in the measure pass. 391 * </p> 392 * 393 * <p> 394 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 395 * {@link #getMeasuredHeight()} values must be set, along with those for all of 396 * that view's descendants. A view's measured width and measured height values 397 * must respect the constraints imposed by the view's parents. This guarantees 398 * that at the end of the measure pass, all parents accept all of their 399 * children's measurements. A parent view may call measure() more than once on 400 * its children. For example, the parent may measure each child once with 401 * unspecified dimensions to find out how big they want to be, then call 402 * measure() on them again with actual numbers if the sum of all the children's 403 * unconstrained sizes is too big or too small. 404 * </p> 405 * 406 * <p> 407 * The measure pass uses two classes to communicate dimensions. The 408 * {@link MeasureSpec} class is used by views to tell their parents how they 409 * want to be measured and positioned. The base LayoutParams class just 410 * describes how big the view wants to be for both width and height. For each 411 * dimension, it can specify one of: 412 * <ul> 413 * <li> an exact number 414 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 415 * (minus padding) 416 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 417 * enclose its content (plus padding). 418 * </ul> 419 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 420 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 421 * an X and Y value. 422 * </p> 423 * 424 * <p> 425 * MeasureSpecs are used to push requirements down the tree from parent to 426 * child. A MeasureSpec can be in one of three modes: 427 * <ul> 428 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 429 * of a child view. For example, a LinearLayout may call measure() on its child 430 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 431 * tall the child view wants to be given a width of 240 pixels. 432 * <li>EXACTLY: This is used by the parent to impose an exact size on the 433 * child. The child must use this size, and guarantee that all of its 434 * descendants will fit within this size. 435 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 436 * child. The child must guarantee that it and all of its descendants will fit 437 * within this size. 438 * </ul> 439 * </p> 440 * 441 * <p> 442 * To intiate a layout, call {@link #requestLayout}. This method is typically 443 * called by a view on itself when it believes that is can no longer fit within 444 * its current bounds. 445 * </p> 446 * 447 * <a name="Drawing"></a> 448 * <h3>Drawing</h3> 449 * <p> 450 * Drawing is handled by walking the tree and recording the drawing commands of 451 * any View that needs to update. After this, the drawing commands of the 452 * entire tree are issued to screen, clipped to the newly damaged area. 453 * </p> 454 * 455 * <p> 456 * The tree is largely recorded and drawn in order, with parents drawn before 457 * (i.e., behind) their children, with siblings drawn in the order they appear 458 * in the tree. If you set a background drawable for a View, then the View will 459 * draw it before calling back to its <code>onDraw()</code> method. The child 460 * drawing order can be overridden with 461 * {@link ViewGroup#setChildrenDrawingOrderEnabled(boolean) custom child drawing order} 462 * in a ViewGroup, and with {@link #setZ(float)} custom Z values} set on Views. 463 * </p> 464 * 465 * <p> 466 * To force a view to draw, call {@link #invalidate()}. 467 * </p> 468 * 469 * <a name="EventHandlingThreading"></a> 470 * <h3>Event Handling and Threading</h3> 471 * <p> 472 * The basic cycle of a view is as follows: 473 * <ol> 474 * <li>An event comes in and is dispatched to the appropriate view. The view 475 * handles the event and notifies any listeners.</li> 476 * <li>If in the course of processing the event, the view's bounds may need 477 * to be changed, the view will call {@link #requestLayout()}.</li> 478 * <li>Similarly, if in the course of processing the event the view's appearance 479 * may need to be changed, the view will call {@link #invalidate()}.</li> 480 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 481 * the framework will take care of measuring, laying out, and drawing the tree 482 * as appropriate.</li> 483 * </ol> 484 * </p> 485 * 486 * <p><em>Note: The entire view tree is single threaded. You must always be on 487 * the UI thread when calling any method on any view.</em> 488 * If you are doing work on other threads and want to update the state of a view 489 * from that thread, you should use a {@link Handler}. 490 * </p> 491 * 492 * <a name="FocusHandling"></a> 493 * <h3>Focus Handling</h3> 494 * <p> 495 * The framework will handle routine focus movement in response to user input. 496 * This includes changing the focus as views are removed or hidden, or as new 497 * views become available. Views indicate their willingness to take focus 498 * through the {@link #isFocusable} method. To change whether a view can take 499 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 500 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 501 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 502 * </p> 503 * <p> 504 * Focus movement is based on an algorithm which finds the nearest neighbor in a 505 * given direction. In rare cases, the default algorithm may not match the 506 * intended behavior of the developer. In these situations, you can provide 507 * explicit overrides by using these XML attributes in the layout file: 508 * <pre> 509 * nextFocusDown 510 * nextFocusLeft 511 * nextFocusRight 512 * nextFocusUp 513 * </pre> 514 * </p> 515 * 516 * 517 * <p> 518 * To get a particular view to take focus, call {@link #requestFocus()}. 519 * </p> 520 * 521 * <a name="TouchMode"></a> 522 * <h3>Touch Mode</h3> 523 * <p> 524 * When a user is navigating a user interface via directional keys such as a D-pad, it is 525 * necessary to give focus to actionable items such as buttons so the user can see 526 * what will take input. If the device has touch capabilities, however, and the user 527 * begins interacting with the interface by touching it, it is no longer necessary to 528 * always highlight, or give focus to, a particular view. This motivates a mode 529 * for interaction named 'touch mode'. 530 * </p> 531 * <p> 532 * For a touch capable device, once the user touches the screen, the device 533 * will enter touch mode. From this point onward, only views for which 534 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 535 * Other views that are touchable, like buttons, will not take focus when touched; they will 536 * only fire the on click listeners. 537 * </p> 538 * <p> 539 * Any time a user hits a directional key, such as a D-pad direction, the view device will 540 * exit touch mode, and find a view to take focus, so that the user may resume interacting 541 * with the user interface without touching the screen again. 542 * </p> 543 * <p> 544 * The touch mode state is maintained across {@link android.app.Activity}s. Call 545 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 546 * </p> 547 * 548 * <a name="Scrolling"></a> 549 * <h3>Scrolling</h3> 550 * <p> 551 * The framework provides basic support for views that wish to internally 552 * scroll their content. This includes keeping track of the X and Y scroll 553 * offset as well as mechanisms for drawing scrollbars. See 554 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 555 * {@link #awakenScrollBars()} for more details. 556 * </p> 557 * 558 * <a name="Tags"></a> 559 * <h3>Tags</h3> 560 * <p> 561 * Unlike IDs, tags are not used to identify views. Tags are essentially an 562 * extra piece of information that can be associated with a view. They are most 563 * often used as a convenience to store data related to views in the views 564 * themselves rather than by putting them in a separate structure. 565 * </p> 566 * 567 * <a name="Properties"></a> 568 * <h3>Properties</h3> 569 * <p> 570 * The View class exposes an {@link #ALPHA} property, as well as several transform-related 571 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are 572 * available both in the {@link Property} form as well as in similarly-named setter/getter 573 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can 574 * be used to set persistent state associated with these rendering-related properties on the view. 575 * The properties and methods can also be used in conjunction with 576 * {@link android.animation.Animator Animator}-based animations, described more in the 577 * <a href="#Animation">Animation</a> section. 578 * </p> 579 * 580 * <a name="Animation"></a> 581 * <h3>Animation</h3> 582 * <p> 583 * Starting with Android 3.0, the preferred way of animating views is to use the 584 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based 585 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and 586 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0 587 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only 588 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class 589 * makes animating these View properties particularly easy and efficient. 590 * </p> 591 * <p> 592 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered. 593 * You can attach an {@link Animation} object to a view using 594 * {@link #setAnimation(Animation)} or 595 * {@link #startAnimation(Animation)}. The animation can alter the scale, 596 * rotation, translation and alpha of a view over time. If the animation is 597 * attached to a view that has children, the animation will affect the entire 598 * subtree rooted by that node. When an animation is started, the framework will 599 * take care of redrawing the appropriate views until the animation completes. 600 * </p> 601 * 602 * <a name="Security"></a> 603 * <h3>Security</h3> 604 * <p> 605 * Sometimes it is essential that an application be able to verify that an action 606 * is being performed with the full knowledge and consent of the user, such as 607 * granting a permission request, making a purchase or clicking on an advertisement. 608 * Unfortunately, a malicious application could try to spoof the user into 609 * performing these actions, unaware, by concealing the intended purpose of the view. 610 * As a remedy, the framework offers a touch filtering mechanism that can be used to 611 * improve the security of views that provide access to sensitive functionality. 612 * </p><p> 613 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 614 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 615 * will discard touches that are received whenever the view's window is obscured by 616 * another visible window. As a result, the view will not receive touches whenever a 617 * toast, dialog or other window appears above the view's window. 618 * </p><p> 619 * For more fine-grained control over security, consider overriding the 620 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 621 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 622 * </p> 623 * 624 * @attr ref android.R.styleable#View_alpha 625 * @attr ref android.R.styleable#View_background 626 * @attr ref android.R.styleable#View_clickable 627 * @attr ref android.R.styleable#View_contentDescription 628 * @attr ref android.R.styleable#View_drawingCacheQuality 629 * @attr ref android.R.styleable#View_duplicateParentState 630 * @attr ref android.R.styleable#View_id 631 * @attr ref android.R.styleable#View_requiresFadingEdge 632 * @attr ref android.R.styleable#View_fadeScrollbars 633 * @attr ref android.R.styleable#View_fadingEdgeLength 634 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 635 * @attr ref android.R.styleable#View_fitsSystemWindows 636 * @attr ref android.R.styleable#View_isScrollContainer 637 * @attr ref android.R.styleable#View_focusable 638 * @attr ref android.R.styleable#View_focusableInTouchMode 639 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 640 * @attr ref android.R.styleable#View_keepScreenOn 641 * @attr ref android.R.styleable#View_layerType 642 * @attr ref android.R.styleable#View_layoutDirection 643 * @attr ref android.R.styleable#View_longClickable 644 * @attr ref android.R.styleable#View_minHeight 645 * @attr ref android.R.styleable#View_minWidth 646 * @attr ref android.R.styleable#View_nextFocusDown 647 * @attr ref android.R.styleable#View_nextFocusLeft 648 * @attr ref android.R.styleable#View_nextFocusRight 649 * @attr ref android.R.styleable#View_nextFocusUp 650 * @attr ref android.R.styleable#View_onClick 651 * @attr ref android.R.styleable#View_padding 652 * @attr ref android.R.styleable#View_paddingBottom 653 * @attr ref android.R.styleable#View_paddingLeft 654 * @attr ref android.R.styleable#View_paddingRight 655 * @attr ref android.R.styleable#View_paddingTop 656 * @attr ref android.R.styleable#View_paddingStart 657 * @attr ref android.R.styleable#View_paddingEnd 658 * @attr ref android.R.styleable#View_saveEnabled 659 * @attr ref android.R.styleable#View_rotation 660 * @attr ref android.R.styleable#View_rotationX 661 * @attr ref android.R.styleable#View_rotationY 662 * @attr ref android.R.styleable#View_scaleX 663 * @attr ref android.R.styleable#View_scaleY 664 * @attr ref android.R.styleable#View_scrollX 665 * @attr ref android.R.styleable#View_scrollY 666 * @attr ref android.R.styleable#View_scrollbarSize 667 * @attr ref android.R.styleable#View_scrollbarStyle 668 * @attr ref android.R.styleable#View_scrollbars 669 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 670 * @attr ref android.R.styleable#View_scrollbarFadeDuration 671 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 672 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 673 * @attr ref android.R.styleable#View_scrollbarThumbVertical 674 * @attr ref android.R.styleable#View_scrollbarTrackVertical 675 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 676 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 677 * @attr ref android.R.styleable#View_stateListAnimator 678 * @attr ref android.R.styleable#View_transitionName 679 * @attr ref android.R.styleable#View_soundEffectsEnabled 680 * @attr ref android.R.styleable#View_tag 681 * @attr ref android.R.styleable#View_textAlignment 682 * @attr ref android.R.styleable#View_textDirection 683 * @attr ref android.R.styleable#View_transformPivotX 684 * @attr ref android.R.styleable#View_transformPivotY 685 * @attr ref android.R.styleable#View_translationX 686 * @attr ref android.R.styleable#View_translationY 687 * @attr ref android.R.styleable#View_translationZ 688 * @attr ref android.R.styleable#View_visibility 689 * 690 * @see android.view.ViewGroup 691 */ 692public class View implements Drawable.Callback, KeyEvent.Callback, 693 AccessibilityEventSource { 694 private static final boolean DBG = false; 695 696 /** 697 * The logging tag used by this class with android.util.Log. 698 */ 699 protected static final String VIEW_LOG_TAG = "View"; 700 701 /** 702 * When set to true, apps will draw debugging information about their layouts. 703 * 704 * @hide 705 */ 706 public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout"; 707 708 /** 709 * When set to true, this view will save its attribute data. 710 * 711 * @hide 712 */ 713 public static boolean mDebugViewAttributes = false; 714 715 /** 716 * Used to mark a View that has no ID. 717 */ 718 public static final int NO_ID = -1; 719 720 /** 721 * Signals that compatibility booleans have been initialized according to 722 * target SDK versions. 723 */ 724 private static boolean sCompatibilityDone = false; 725 726 /** 727 * Use the old (broken) way of building MeasureSpecs. 728 */ 729 private static boolean sUseBrokenMakeMeasureSpec = false; 730 731 /** 732 * Ignore any optimizations using the measure cache. 733 */ 734 private static boolean sIgnoreMeasureCache = false; 735 736 /** 737 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 738 * calling setFlags. 739 */ 740 private static final int NOT_FOCUSABLE = 0x00000000; 741 742 /** 743 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 744 * setFlags. 745 */ 746 private static final int FOCUSABLE = 0x00000001; 747 748 /** 749 * Mask for use with setFlags indicating bits used for focus. 750 */ 751 private static final int FOCUSABLE_MASK = 0x00000001; 752 753 /** 754 * This view will adjust its padding to fit sytem windows (e.g. status bar) 755 */ 756 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 757 758 /** @hide */ 759 @IntDef({VISIBLE, INVISIBLE, GONE}) 760 @Retention(RetentionPolicy.SOURCE) 761 public @interface Visibility {} 762 763 /** 764 * This view is visible. 765 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 766 * android:visibility}. 767 */ 768 public static final int VISIBLE = 0x00000000; 769 770 /** 771 * This view is invisible, but it still takes up space for layout purposes. 772 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 773 * android:visibility}. 774 */ 775 public static final int INVISIBLE = 0x00000004; 776 777 /** 778 * This view is invisible, and it doesn't take any space for layout 779 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 780 * android:visibility}. 781 */ 782 public static final int GONE = 0x00000008; 783 784 /** 785 * Mask for use with setFlags indicating bits used for visibility. 786 * {@hide} 787 */ 788 static final int VISIBILITY_MASK = 0x0000000C; 789 790 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 791 792 /** 793 * This view is enabled. Interpretation varies by subclass. 794 * Use with ENABLED_MASK when calling setFlags. 795 * {@hide} 796 */ 797 static final int ENABLED = 0x00000000; 798 799 /** 800 * This view is disabled. Interpretation varies by subclass. 801 * Use with ENABLED_MASK when calling setFlags. 802 * {@hide} 803 */ 804 static final int DISABLED = 0x00000020; 805 806 /** 807 * Mask for use with setFlags indicating bits used for indicating whether 808 * this view is enabled 809 * {@hide} 810 */ 811 static final int ENABLED_MASK = 0x00000020; 812 813 /** 814 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 815 * called and further optimizations will be performed. It is okay to have 816 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 817 * {@hide} 818 */ 819 static final int WILL_NOT_DRAW = 0x00000080; 820 821 /** 822 * Mask for use with setFlags indicating bits used for indicating whether 823 * this view is will draw 824 * {@hide} 825 */ 826 static final int DRAW_MASK = 0x00000080; 827 828 /** 829 * <p>This view doesn't show scrollbars.</p> 830 * {@hide} 831 */ 832 static final int SCROLLBARS_NONE = 0x00000000; 833 834 /** 835 * <p>This view shows horizontal scrollbars.</p> 836 * {@hide} 837 */ 838 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 839 840 /** 841 * <p>This view shows vertical scrollbars.</p> 842 * {@hide} 843 */ 844 static final int SCROLLBARS_VERTICAL = 0x00000200; 845 846 /** 847 * <p>Mask for use with setFlags indicating bits used for indicating which 848 * scrollbars are enabled.</p> 849 * {@hide} 850 */ 851 static final int SCROLLBARS_MASK = 0x00000300; 852 853 /** 854 * Indicates that the view should filter touches when its window is obscured. 855 * Refer to the class comments for more information about this security feature. 856 * {@hide} 857 */ 858 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 859 860 /** 861 * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate 862 * that they are optional and should be skipped if the window has 863 * requested system UI flags that ignore those insets for layout. 864 */ 865 static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800; 866 867 /** 868 * <p>This view doesn't show fading edges.</p> 869 * {@hide} 870 */ 871 static final int FADING_EDGE_NONE = 0x00000000; 872 873 /** 874 * <p>This view shows horizontal fading edges.</p> 875 * {@hide} 876 */ 877 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 878 879 /** 880 * <p>This view shows vertical fading edges.</p> 881 * {@hide} 882 */ 883 static final int FADING_EDGE_VERTICAL = 0x00002000; 884 885 /** 886 * <p>Mask for use with setFlags indicating bits used for indicating which 887 * fading edges are enabled.</p> 888 * {@hide} 889 */ 890 static final int FADING_EDGE_MASK = 0x00003000; 891 892 /** 893 * <p>Indicates this view can be clicked. When clickable, a View reacts 894 * to clicks by notifying the OnClickListener.<p> 895 * {@hide} 896 */ 897 static final int CLICKABLE = 0x00004000; 898 899 /** 900 * <p>Indicates this view is caching its drawing into a bitmap.</p> 901 * {@hide} 902 */ 903 static final int DRAWING_CACHE_ENABLED = 0x00008000; 904 905 /** 906 * <p>Indicates that no icicle should be saved for this view.<p> 907 * {@hide} 908 */ 909 static final int SAVE_DISABLED = 0x000010000; 910 911 /** 912 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 913 * property.</p> 914 * {@hide} 915 */ 916 static final int SAVE_DISABLED_MASK = 0x000010000; 917 918 /** 919 * <p>Indicates that no drawing cache should ever be created for this view.<p> 920 * {@hide} 921 */ 922 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 923 924 /** 925 * <p>Indicates this view can take / keep focus when int touch mode.</p> 926 * {@hide} 927 */ 928 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 929 930 /** @hide */ 931 @Retention(RetentionPolicy.SOURCE) 932 @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO}) 933 public @interface DrawingCacheQuality {} 934 935 /** 936 * <p>Enables low quality mode for the drawing cache.</p> 937 */ 938 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 939 940 /** 941 * <p>Enables high quality mode for the drawing cache.</p> 942 */ 943 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 944 945 /** 946 * <p>Enables automatic quality mode for the drawing cache.</p> 947 */ 948 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 949 950 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 951 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 952 }; 953 954 /** 955 * <p>Mask for use with setFlags indicating bits used for the cache 956 * quality property.</p> 957 * {@hide} 958 */ 959 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 960 961 /** 962 * <p> 963 * Indicates this view can be long clicked. When long clickable, a View 964 * reacts to long clicks by notifying the OnLongClickListener or showing a 965 * context menu. 966 * </p> 967 * {@hide} 968 */ 969 static final int LONG_CLICKABLE = 0x00200000; 970 971 /** 972 * <p>Indicates that this view gets its drawable states from its direct parent 973 * and ignores its original internal states.</p> 974 * 975 * @hide 976 */ 977 static final int DUPLICATE_PARENT_STATE = 0x00400000; 978 979 /** @hide */ 980 @IntDef({ 981 SCROLLBARS_INSIDE_OVERLAY, 982 SCROLLBARS_INSIDE_INSET, 983 SCROLLBARS_OUTSIDE_OVERLAY, 984 SCROLLBARS_OUTSIDE_INSET 985 }) 986 @Retention(RetentionPolicy.SOURCE) 987 public @interface ScrollBarStyle {} 988 989 /** 990 * The scrollbar style to display the scrollbars inside the content area, 991 * without increasing the padding. The scrollbars will be overlaid with 992 * translucency on the view's content. 993 */ 994 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 995 996 /** 997 * The scrollbar style to display the scrollbars inside the padded area, 998 * increasing the padding of the view. The scrollbars will not overlap the 999 * content area of the view. 1000 */ 1001 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 1002 1003 /** 1004 * The scrollbar style to display the scrollbars at the edge of the view, 1005 * without increasing the padding. The scrollbars will be overlaid with 1006 * translucency. 1007 */ 1008 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 1009 1010 /** 1011 * The scrollbar style to display the scrollbars at the edge of the view, 1012 * increasing the padding of the view. The scrollbars will only overlap the 1013 * background, if any. 1014 */ 1015 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 1016 1017 /** 1018 * Mask to check if the scrollbar style is overlay or inset. 1019 * {@hide} 1020 */ 1021 static final int SCROLLBARS_INSET_MASK = 0x01000000; 1022 1023 /** 1024 * Mask to check if the scrollbar style is inside or outside. 1025 * {@hide} 1026 */ 1027 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 1028 1029 /** 1030 * Mask for scrollbar style. 1031 * {@hide} 1032 */ 1033 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 1034 1035 /** 1036 * View flag indicating that the screen should remain on while the 1037 * window containing this view is visible to the user. This effectively 1038 * takes care of automatically setting the WindowManager's 1039 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 1040 */ 1041 public static final int KEEP_SCREEN_ON = 0x04000000; 1042 1043 /** 1044 * View flag indicating whether this view should have sound effects enabled 1045 * for events such as clicking and touching. 1046 */ 1047 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 1048 1049 /** 1050 * View flag indicating whether this view should have haptic feedback 1051 * enabled for events such as long presses. 1052 */ 1053 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 1054 1055 /** 1056 * <p>Indicates that the view hierarchy should stop saving state when 1057 * it reaches this view. If state saving is initiated immediately at 1058 * the view, it will be allowed. 1059 * {@hide} 1060 */ 1061 static final int PARENT_SAVE_DISABLED = 0x20000000; 1062 1063 /** 1064 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 1065 * {@hide} 1066 */ 1067 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 1068 1069 /** @hide */ 1070 @IntDef(flag = true, 1071 value = { 1072 FOCUSABLES_ALL, 1073 FOCUSABLES_TOUCH_MODE 1074 }) 1075 @Retention(RetentionPolicy.SOURCE) 1076 public @interface FocusableMode {} 1077 1078 /** 1079 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1080 * should add all focusable Views regardless if they are focusable in touch mode. 1081 */ 1082 public static final int FOCUSABLES_ALL = 0x00000000; 1083 1084 /** 1085 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1086 * should add only Views focusable in touch mode. 1087 */ 1088 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 1089 1090 /** @hide */ 1091 @IntDef({ 1092 FOCUS_BACKWARD, 1093 FOCUS_FORWARD, 1094 FOCUS_LEFT, 1095 FOCUS_UP, 1096 FOCUS_RIGHT, 1097 FOCUS_DOWN 1098 }) 1099 @Retention(RetentionPolicy.SOURCE) 1100 public @interface FocusDirection {} 1101 1102 /** @hide */ 1103 @IntDef({ 1104 FOCUS_LEFT, 1105 FOCUS_UP, 1106 FOCUS_RIGHT, 1107 FOCUS_DOWN 1108 }) 1109 @Retention(RetentionPolicy.SOURCE) 1110 public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward 1111 1112 /** 1113 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 1114 * item. 1115 */ 1116 public static final int FOCUS_BACKWARD = 0x00000001; 1117 1118 /** 1119 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 1120 * item. 1121 */ 1122 public static final int FOCUS_FORWARD = 0x00000002; 1123 1124 /** 1125 * Use with {@link #focusSearch(int)}. Move focus to the left. 1126 */ 1127 public static final int FOCUS_LEFT = 0x00000011; 1128 1129 /** 1130 * Use with {@link #focusSearch(int)}. Move focus up. 1131 */ 1132 public static final int FOCUS_UP = 0x00000021; 1133 1134 /** 1135 * Use with {@link #focusSearch(int)}. Move focus to the right. 1136 */ 1137 public static final int FOCUS_RIGHT = 0x00000042; 1138 1139 /** 1140 * Use with {@link #focusSearch(int)}. Move focus down. 1141 */ 1142 public static final int FOCUS_DOWN = 0x00000082; 1143 1144 /** 1145 * Bits of {@link #getMeasuredWidthAndState()} and 1146 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1147 */ 1148 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1149 1150 /** 1151 * Bits of {@link #getMeasuredWidthAndState()} and 1152 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1153 */ 1154 public static final int MEASURED_STATE_MASK = 0xff000000; 1155 1156 /** 1157 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1158 * for functions that combine both width and height into a single int, 1159 * such as {@link #getMeasuredState()} and the childState argument of 1160 * {@link #resolveSizeAndState(int, int, int)}. 1161 */ 1162 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1163 1164 /** 1165 * Bit of {@link #getMeasuredWidthAndState()} and 1166 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1167 * is smaller that the space the view would like to have. 1168 */ 1169 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1170 1171 /** 1172 * Base View state sets 1173 */ 1174 // Singles 1175 /** 1176 * Indicates the view has no states set. States are used with 1177 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1178 * view depending on its state. 1179 * 1180 * @see android.graphics.drawable.Drawable 1181 * @see #getDrawableState() 1182 */ 1183 protected static final int[] EMPTY_STATE_SET; 1184 /** 1185 * Indicates the view is enabled. States are used with 1186 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1187 * view depending on its state. 1188 * 1189 * @see android.graphics.drawable.Drawable 1190 * @see #getDrawableState() 1191 */ 1192 protected static final int[] ENABLED_STATE_SET; 1193 /** 1194 * Indicates the view is focused. States are used with 1195 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1196 * view depending on its state. 1197 * 1198 * @see android.graphics.drawable.Drawable 1199 * @see #getDrawableState() 1200 */ 1201 protected static final int[] FOCUSED_STATE_SET; 1202 /** 1203 * Indicates the view is selected. States are used with 1204 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1205 * view depending on its state. 1206 * 1207 * @see android.graphics.drawable.Drawable 1208 * @see #getDrawableState() 1209 */ 1210 protected static final int[] SELECTED_STATE_SET; 1211 /** 1212 * Indicates the view is pressed. States are used with 1213 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1214 * view depending on its state. 1215 * 1216 * @see android.graphics.drawable.Drawable 1217 * @see #getDrawableState() 1218 */ 1219 protected static final int[] PRESSED_STATE_SET; 1220 /** 1221 * Indicates the view's window has focus. States are used with 1222 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1223 * view depending on its state. 1224 * 1225 * @see android.graphics.drawable.Drawable 1226 * @see #getDrawableState() 1227 */ 1228 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1229 // Doubles 1230 /** 1231 * Indicates the view is enabled and has the focus. 1232 * 1233 * @see #ENABLED_STATE_SET 1234 * @see #FOCUSED_STATE_SET 1235 */ 1236 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1237 /** 1238 * Indicates the view is enabled and selected. 1239 * 1240 * @see #ENABLED_STATE_SET 1241 * @see #SELECTED_STATE_SET 1242 */ 1243 protected static final int[] ENABLED_SELECTED_STATE_SET; 1244 /** 1245 * Indicates the view is enabled and that its window has focus. 1246 * 1247 * @see #ENABLED_STATE_SET 1248 * @see #WINDOW_FOCUSED_STATE_SET 1249 */ 1250 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1251 /** 1252 * Indicates the view is focused and selected. 1253 * 1254 * @see #FOCUSED_STATE_SET 1255 * @see #SELECTED_STATE_SET 1256 */ 1257 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1258 /** 1259 * Indicates the view has the focus and that its window has the focus. 1260 * 1261 * @see #FOCUSED_STATE_SET 1262 * @see #WINDOW_FOCUSED_STATE_SET 1263 */ 1264 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1265 /** 1266 * Indicates the view is selected and that its window has the focus. 1267 * 1268 * @see #SELECTED_STATE_SET 1269 * @see #WINDOW_FOCUSED_STATE_SET 1270 */ 1271 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1272 // Triples 1273 /** 1274 * Indicates the view is enabled, focused and selected. 1275 * 1276 * @see #ENABLED_STATE_SET 1277 * @see #FOCUSED_STATE_SET 1278 * @see #SELECTED_STATE_SET 1279 */ 1280 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1281 /** 1282 * Indicates the view is enabled, focused and its window has the focus. 1283 * 1284 * @see #ENABLED_STATE_SET 1285 * @see #FOCUSED_STATE_SET 1286 * @see #WINDOW_FOCUSED_STATE_SET 1287 */ 1288 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1289 /** 1290 * Indicates the view is enabled, selected and its window has the focus. 1291 * 1292 * @see #ENABLED_STATE_SET 1293 * @see #SELECTED_STATE_SET 1294 * @see #WINDOW_FOCUSED_STATE_SET 1295 */ 1296 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1297 /** 1298 * Indicates the view is focused, selected and its window has the focus. 1299 * 1300 * @see #FOCUSED_STATE_SET 1301 * @see #SELECTED_STATE_SET 1302 * @see #WINDOW_FOCUSED_STATE_SET 1303 */ 1304 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1305 /** 1306 * Indicates the view is enabled, focused, selected and its window 1307 * has the focus. 1308 * 1309 * @see #ENABLED_STATE_SET 1310 * @see #FOCUSED_STATE_SET 1311 * @see #SELECTED_STATE_SET 1312 * @see #WINDOW_FOCUSED_STATE_SET 1313 */ 1314 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1315 /** 1316 * Indicates the view is pressed and its window has the focus. 1317 * 1318 * @see #PRESSED_STATE_SET 1319 * @see #WINDOW_FOCUSED_STATE_SET 1320 */ 1321 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1322 /** 1323 * Indicates the view is pressed and selected. 1324 * 1325 * @see #PRESSED_STATE_SET 1326 * @see #SELECTED_STATE_SET 1327 */ 1328 protected static final int[] PRESSED_SELECTED_STATE_SET; 1329 /** 1330 * Indicates the view is pressed, selected and its window has the focus. 1331 * 1332 * @see #PRESSED_STATE_SET 1333 * @see #SELECTED_STATE_SET 1334 * @see #WINDOW_FOCUSED_STATE_SET 1335 */ 1336 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1337 /** 1338 * Indicates the view is pressed and focused. 1339 * 1340 * @see #PRESSED_STATE_SET 1341 * @see #FOCUSED_STATE_SET 1342 */ 1343 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1344 /** 1345 * Indicates the view is pressed, focused and its window has the focus. 1346 * 1347 * @see #PRESSED_STATE_SET 1348 * @see #FOCUSED_STATE_SET 1349 * @see #WINDOW_FOCUSED_STATE_SET 1350 */ 1351 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1352 /** 1353 * Indicates the view is pressed, focused and selected. 1354 * 1355 * @see #PRESSED_STATE_SET 1356 * @see #SELECTED_STATE_SET 1357 * @see #FOCUSED_STATE_SET 1358 */ 1359 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1360 /** 1361 * Indicates the view is pressed, focused, selected and its window has the focus. 1362 * 1363 * @see #PRESSED_STATE_SET 1364 * @see #FOCUSED_STATE_SET 1365 * @see #SELECTED_STATE_SET 1366 * @see #WINDOW_FOCUSED_STATE_SET 1367 */ 1368 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1369 /** 1370 * Indicates the view is pressed and enabled. 1371 * 1372 * @see #PRESSED_STATE_SET 1373 * @see #ENABLED_STATE_SET 1374 */ 1375 protected static final int[] PRESSED_ENABLED_STATE_SET; 1376 /** 1377 * Indicates the view is pressed, enabled and its window has the focus. 1378 * 1379 * @see #PRESSED_STATE_SET 1380 * @see #ENABLED_STATE_SET 1381 * @see #WINDOW_FOCUSED_STATE_SET 1382 */ 1383 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1384 /** 1385 * Indicates the view is pressed, enabled and selected. 1386 * 1387 * @see #PRESSED_STATE_SET 1388 * @see #ENABLED_STATE_SET 1389 * @see #SELECTED_STATE_SET 1390 */ 1391 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1392 /** 1393 * Indicates the view is pressed, enabled, selected and its window has the 1394 * focus. 1395 * 1396 * @see #PRESSED_STATE_SET 1397 * @see #ENABLED_STATE_SET 1398 * @see #SELECTED_STATE_SET 1399 * @see #WINDOW_FOCUSED_STATE_SET 1400 */ 1401 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1402 /** 1403 * Indicates the view is pressed, enabled and focused. 1404 * 1405 * @see #PRESSED_STATE_SET 1406 * @see #ENABLED_STATE_SET 1407 * @see #FOCUSED_STATE_SET 1408 */ 1409 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1410 /** 1411 * Indicates the view is pressed, enabled, focused and its window has the 1412 * focus. 1413 * 1414 * @see #PRESSED_STATE_SET 1415 * @see #ENABLED_STATE_SET 1416 * @see #FOCUSED_STATE_SET 1417 * @see #WINDOW_FOCUSED_STATE_SET 1418 */ 1419 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1420 /** 1421 * Indicates the view is pressed, enabled, focused and selected. 1422 * 1423 * @see #PRESSED_STATE_SET 1424 * @see #ENABLED_STATE_SET 1425 * @see #SELECTED_STATE_SET 1426 * @see #FOCUSED_STATE_SET 1427 */ 1428 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1429 /** 1430 * Indicates the view is pressed, enabled, focused, selected and its window 1431 * has the focus. 1432 * 1433 * @see #PRESSED_STATE_SET 1434 * @see #ENABLED_STATE_SET 1435 * @see #SELECTED_STATE_SET 1436 * @see #FOCUSED_STATE_SET 1437 * @see #WINDOW_FOCUSED_STATE_SET 1438 */ 1439 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1440 1441 /** 1442 * The order here is very important to {@link #getDrawableState()} 1443 */ 1444 private static final int[][] VIEW_STATE_SETS; 1445 1446 static final int VIEW_STATE_WINDOW_FOCUSED = 1; 1447 static final int VIEW_STATE_SELECTED = 1 << 1; 1448 static final int VIEW_STATE_FOCUSED = 1 << 2; 1449 static final int VIEW_STATE_ENABLED = 1 << 3; 1450 static final int VIEW_STATE_PRESSED = 1 << 4; 1451 static final int VIEW_STATE_ACTIVATED = 1 << 5; 1452 static final int VIEW_STATE_ACCELERATED = 1 << 6; 1453 static final int VIEW_STATE_HOVERED = 1 << 7; 1454 static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8; 1455 static final int VIEW_STATE_DRAG_HOVERED = 1 << 9; 1456 1457 static final int[] VIEW_STATE_IDS = new int[] { 1458 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED, 1459 R.attr.state_selected, VIEW_STATE_SELECTED, 1460 R.attr.state_focused, VIEW_STATE_FOCUSED, 1461 R.attr.state_enabled, VIEW_STATE_ENABLED, 1462 R.attr.state_pressed, VIEW_STATE_PRESSED, 1463 R.attr.state_activated, VIEW_STATE_ACTIVATED, 1464 R.attr.state_accelerated, VIEW_STATE_ACCELERATED, 1465 R.attr.state_hovered, VIEW_STATE_HOVERED, 1466 R.attr.state_drag_can_accept, VIEW_STATE_DRAG_CAN_ACCEPT, 1467 R.attr.state_drag_hovered, VIEW_STATE_DRAG_HOVERED 1468 }; 1469 1470 static { 1471 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) { 1472 throw new IllegalStateException( 1473 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array"); 1474 } 1475 int[] orderedIds = new int[VIEW_STATE_IDS.length]; 1476 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) { 1477 int viewState = R.styleable.ViewDrawableStates[i]; 1478 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) { 1479 if (VIEW_STATE_IDS[j] == viewState) { 1480 orderedIds[i * 2] = viewState; 1481 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1]; 1482 } 1483 } 1484 } 1485 final int NUM_BITS = VIEW_STATE_IDS.length / 2; 1486 VIEW_STATE_SETS = new int[1 << NUM_BITS][]; 1487 for (int i = 0; i < VIEW_STATE_SETS.length; i++) { 1488 int numBits = Integer.bitCount(i); 1489 int[] set = new int[numBits]; 1490 int pos = 0; 1491 for (int j = 0; j < orderedIds.length; j += 2) { 1492 if ((i & orderedIds[j+1]) != 0) { 1493 set[pos++] = orderedIds[j]; 1494 } 1495 } 1496 VIEW_STATE_SETS[i] = set; 1497 } 1498 1499 EMPTY_STATE_SET = VIEW_STATE_SETS[0]; 1500 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED]; 1501 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED]; 1502 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1503 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED]; 1504 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED]; 1505 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1506 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED]; 1507 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1508 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED]; 1509 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1510 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1511 | VIEW_STATE_FOCUSED]; 1512 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED]; 1513 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1514 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED]; 1515 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1516 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED]; 1517 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1518 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1519 | VIEW_STATE_ENABLED]; 1520 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1521 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED]; 1522 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1523 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1524 | VIEW_STATE_ENABLED]; 1525 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1526 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1527 | VIEW_STATE_ENABLED]; 1528 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1529 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1530 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED]; 1531 1532 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED]; 1533 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1534 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED]; 1535 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1536 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED]; 1537 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1538 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1539 | VIEW_STATE_PRESSED]; 1540 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1541 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1542 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1543 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1544 | VIEW_STATE_PRESSED]; 1545 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1546 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1547 | VIEW_STATE_PRESSED]; 1548 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1549 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1550 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1551 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[ 1552 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1553 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1554 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED 1555 | VIEW_STATE_PRESSED]; 1556 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1557 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED 1558 | VIEW_STATE_PRESSED]; 1559 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1560 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1561 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1562 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1563 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED 1564 | VIEW_STATE_PRESSED]; 1565 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1566 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1567 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1568 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1569 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1570 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1571 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1572 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1573 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED 1574 | VIEW_STATE_PRESSED]; 1575 } 1576 1577 /** 1578 * Accessibility event types that are dispatched for text population. 1579 */ 1580 private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES = 1581 AccessibilityEvent.TYPE_VIEW_CLICKED 1582 | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED 1583 | AccessibilityEvent.TYPE_VIEW_SELECTED 1584 | AccessibilityEvent.TYPE_VIEW_FOCUSED 1585 | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED 1586 | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER 1587 | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT 1588 | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED 1589 | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED 1590 | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED 1591 | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY; 1592 1593 /** 1594 * Temporary Rect currently for use in setBackground(). This will probably 1595 * be extended in the future to hold our own class with more than just 1596 * a Rect. :) 1597 */ 1598 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1599 1600 /** 1601 * Map used to store views' tags. 1602 */ 1603 private SparseArray<Object> mKeyedTags; 1604 1605 /** 1606 * The next available accessibility id. 1607 */ 1608 private static int sNextAccessibilityViewId; 1609 1610 /** 1611 * The animation currently associated with this view. 1612 * @hide 1613 */ 1614 protected Animation mCurrentAnimation = null; 1615 1616 /** 1617 * Width as measured during measure pass. 1618 * {@hide} 1619 */ 1620 @ViewDebug.ExportedProperty(category = "measurement") 1621 int mMeasuredWidth; 1622 1623 /** 1624 * Height as measured during measure pass. 1625 * {@hide} 1626 */ 1627 @ViewDebug.ExportedProperty(category = "measurement") 1628 int mMeasuredHeight; 1629 1630 /** 1631 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1632 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1633 * its display list. This flag, used only when hw accelerated, allows us to clear the 1634 * flag while retaining this information until it's needed (at getDisplayList() time and 1635 * in drawChild(), when we decide to draw a view's children's display lists into our own). 1636 * 1637 * {@hide} 1638 */ 1639 boolean mRecreateDisplayList = false; 1640 1641 /** 1642 * The view's identifier. 1643 * {@hide} 1644 * 1645 * @see #setId(int) 1646 * @see #getId() 1647 */ 1648 @ViewDebug.ExportedProperty(resolveId = true) 1649 int mID = NO_ID; 1650 1651 /** 1652 * The stable ID of this view for accessibility purposes. 1653 */ 1654 int mAccessibilityViewId = NO_ID; 1655 1656 private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 1657 1658 SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent; 1659 1660 /** 1661 * The view's tag. 1662 * {@hide} 1663 * 1664 * @see #setTag(Object) 1665 * @see #getTag() 1666 */ 1667 protected Object mTag = null; 1668 1669 // for mPrivateFlags: 1670 /** {@hide} */ 1671 static final int PFLAG_WANTS_FOCUS = 0x00000001; 1672 /** {@hide} */ 1673 static final int PFLAG_FOCUSED = 0x00000002; 1674 /** {@hide} */ 1675 static final int PFLAG_SELECTED = 0x00000004; 1676 /** {@hide} */ 1677 static final int PFLAG_IS_ROOT_NAMESPACE = 0x00000008; 1678 /** {@hide} */ 1679 static final int PFLAG_HAS_BOUNDS = 0x00000010; 1680 /** {@hide} */ 1681 static final int PFLAG_DRAWN = 0x00000020; 1682 /** 1683 * When this flag is set, this view is running an animation on behalf of its 1684 * children and should therefore not cancel invalidate requests, even if they 1685 * lie outside of this view's bounds. 1686 * 1687 * {@hide} 1688 */ 1689 static final int PFLAG_DRAW_ANIMATION = 0x00000040; 1690 /** {@hide} */ 1691 static final int PFLAG_SKIP_DRAW = 0x00000080; 1692 /** {@hide} */ 1693 static final int PFLAG_ONLY_DRAWS_BACKGROUND = 0x00000100; 1694 /** {@hide} */ 1695 static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1696 /** {@hide} */ 1697 static final int PFLAG_DRAWABLE_STATE_DIRTY = 0x00000400; 1698 /** {@hide} */ 1699 static final int PFLAG_MEASURED_DIMENSION_SET = 0x00000800; 1700 /** {@hide} */ 1701 static final int PFLAG_FORCE_LAYOUT = 0x00001000; 1702 /** {@hide} */ 1703 static final int PFLAG_LAYOUT_REQUIRED = 0x00002000; 1704 1705 private static final int PFLAG_PRESSED = 0x00004000; 1706 1707 /** {@hide} */ 1708 static final int PFLAG_DRAWING_CACHE_VALID = 0x00008000; 1709 /** 1710 * Flag used to indicate that this view should be drawn once more (and only once 1711 * more) after its animation has completed. 1712 * {@hide} 1713 */ 1714 static final int PFLAG_ANIMATION_STARTED = 0x00010000; 1715 1716 private static final int PFLAG_SAVE_STATE_CALLED = 0x00020000; 1717 1718 /** 1719 * Indicates that the View returned true when onSetAlpha() was called and that 1720 * the alpha must be restored. 1721 * {@hide} 1722 */ 1723 static final int PFLAG_ALPHA_SET = 0x00040000; 1724 1725 /** 1726 * Set by {@link #setScrollContainer(boolean)}. 1727 */ 1728 static final int PFLAG_SCROLL_CONTAINER = 0x00080000; 1729 1730 /** 1731 * Set by {@link #setScrollContainer(boolean)}. 1732 */ 1733 static final int PFLAG_SCROLL_CONTAINER_ADDED = 0x00100000; 1734 1735 /** 1736 * View flag indicating whether this view was invalidated (fully or partially.) 1737 * 1738 * @hide 1739 */ 1740 static final int PFLAG_DIRTY = 0x00200000; 1741 1742 /** 1743 * View flag indicating whether this view was invalidated by an opaque 1744 * invalidate request. 1745 * 1746 * @hide 1747 */ 1748 static final int PFLAG_DIRTY_OPAQUE = 0x00400000; 1749 1750 /** 1751 * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}. 1752 * 1753 * @hide 1754 */ 1755 static final int PFLAG_DIRTY_MASK = 0x00600000; 1756 1757 /** 1758 * Indicates whether the background is opaque. 1759 * 1760 * @hide 1761 */ 1762 static final int PFLAG_OPAQUE_BACKGROUND = 0x00800000; 1763 1764 /** 1765 * Indicates whether the scrollbars are opaque. 1766 * 1767 * @hide 1768 */ 1769 static final int PFLAG_OPAQUE_SCROLLBARS = 0x01000000; 1770 1771 /** 1772 * Indicates whether the view is opaque. 1773 * 1774 * @hide 1775 */ 1776 static final int PFLAG_OPAQUE_MASK = 0x01800000; 1777 1778 /** 1779 * Indicates a prepressed state; 1780 * the short time between ACTION_DOWN and recognizing 1781 * a 'real' press. Prepressed is used to recognize quick taps 1782 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1783 * 1784 * @hide 1785 */ 1786 private static final int PFLAG_PREPRESSED = 0x02000000; 1787 1788 /** 1789 * Indicates whether the view is temporarily detached. 1790 * 1791 * @hide 1792 */ 1793 static final int PFLAG_CANCEL_NEXT_UP_EVENT = 0x04000000; 1794 1795 /** 1796 * Indicates that we should awaken scroll bars once attached 1797 * 1798 * @hide 1799 */ 1800 private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1801 1802 /** 1803 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 1804 * @hide 1805 */ 1806 private static final int PFLAG_HOVERED = 0x10000000; 1807 1808 /** 1809 * no longer needed, should be reused 1810 */ 1811 private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000; 1812 1813 /** {@hide} */ 1814 static final int PFLAG_ACTIVATED = 0x40000000; 1815 1816 /** 1817 * Indicates that this view was specifically invalidated, not just dirtied because some 1818 * child view was invalidated. The flag is used to determine when we need to recreate 1819 * a view's display list (as opposed to just returning a reference to its existing 1820 * display list). 1821 * 1822 * @hide 1823 */ 1824 static final int PFLAG_INVALIDATED = 0x80000000; 1825 1826 /** 1827 * Masks for mPrivateFlags2, as generated by dumpFlags(): 1828 * 1829 * |-------|-------|-------|-------| 1830 * 1 PFLAG2_DRAG_CAN_ACCEPT 1831 * 1 PFLAG2_DRAG_HOVERED 1832 * 11 PFLAG2_LAYOUT_DIRECTION_MASK 1833 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL 1834 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED 1835 * 11 PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK 1836 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[1] 1837 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[2] 1838 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[3] 1839 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[4] 1840 * 1 1 PFLAG2_TEXT_DIRECTION_FLAGS[5] 1841 * 111 PFLAG2_TEXT_DIRECTION_MASK 1842 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED 1843 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT 1844 * 111 PFLAG2_TEXT_DIRECTION_RESOLVED_MASK 1845 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[1] 1846 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[2] 1847 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[3] 1848 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[4] 1849 * 1 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[5] 1850 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[6] 1851 * 111 PFLAG2_TEXT_ALIGNMENT_MASK 1852 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED 1853 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT 1854 * 111 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK 1855 * 111 PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK 1856 * 11 PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK 1857 * 1 PFLAG2_ACCESSIBILITY_FOCUSED 1858 * 1 PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED 1859 * 1 PFLAG2_VIEW_QUICK_REJECTED 1860 * 1 PFLAG2_PADDING_RESOLVED 1861 * 1 PFLAG2_DRAWABLE_RESOLVED 1862 * 1 PFLAG2_HAS_TRANSIENT_STATE 1863 * |-------|-------|-------|-------| 1864 */ 1865 1866 /** 1867 * Indicates that this view has reported that it can accept the current drag's content. 1868 * Cleared when the drag operation concludes. 1869 * @hide 1870 */ 1871 static final int PFLAG2_DRAG_CAN_ACCEPT = 0x00000001; 1872 1873 /** 1874 * Indicates that this view is currently directly under the drag location in a 1875 * drag-and-drop operation involving content that it can accept. Cleared when 1876 * the drag exits the view, or when the drag operation concludes. 1877 * @hide 1878 */ 1879 static final int PFLAG2_DRAG_HOVERED = 0x00000002; 1880 1881 /** @hide */ 1882 @IntDef({ 1883 LAYOUT_DIRECTION_LTR, 1884 LAYOUT_DIRECTION_RTL, 1885 LAYOUT_DIRECTION_INHERIT, 1886 LAYOUT_DIRECTION_LOCALE 1887 }) 1888 @Retention(RetentionPolicy.SOURCE) 1889 // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection 1890 public @interface LayoutDir {} 1891 1892 /** @hide */ 1893 @IntDef({ 1894 LAYOUT_DIRECTION_LTR, 1895 LAYOUT_DIRECTION_RTL 1896 }) 1897 @Retention(RetentionPolicy.SOURCE) 1898 public @interface ResolvedLayoutDir {} 1899 1900 /** 1901 * Horizontal layout direction of this view is from Left to Right. 1902 * Use with {@link #setLayoutDirection}. 1903 */ 1904 public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR; 1905 1906 /** 1907 * Horizontal layout direction of this view is from Right to Left. 1908 * Use with {@link #setLayoutDirection}. 1909 */ 1910 public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL; 1911 1912 /** 1913 * Horizontal layout direction of this view is inherited from its parent. 1914 * Use with {@link #setLayoutDirection}. 1915 */ 1916 public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT; 1917 1918 /** 1919 * Horizontal layout direction of this view is from deduced from the default language 1920 * script for the locale. Use with {@link #setLayoutDirection}. 1921 */ 1922 public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE; 1923 1924 /** 1925 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 1926 * @hide 1927 */ 1928 static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2; 1929 1930 /** 1931 * Mask for use with private flags indicating bits used for horizontal layout direction. 1932 * @hide 1933 */ 1934 static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1935 1936 /** 1937 * Indicates whether the view horizontal layout direction has been resolved and drawn to the 1938 * right-to-left direction. 1939 * @hide 1940 */ 1941 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1942 1943 /** 1944 * Indicates whether the view horizontal layout direction has been resolved. 1945 * @hide 1946 */ 1947 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1948 1949 /** 1950 * Mask for use with private flags indicating bits used for resolved horizontal layout direction. 1951 * @hide 1952 */ 1953 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C 1954 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1955 1956 /* 1957 * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct 1958 * flag value. 1959 * @hide 1960 */ 1961 private static final int[] LAYOUT_DIRECTION_FLAGS = { 1962 LAYOUT_DIRECTION_LTR, 1963 LAYOUT_DIRECTION_RTL, 1964 LAYOUT_DIRECTION_INHERIT, 1965 LAYOUT_DIRECTION_LOCALE 1966 }; 1967 1968 /** 1969 * Default horizontal layout direction. 1970 */ 1971 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 1972 1973 /** 1974 * Default horizontal layout direction. 1975 * @hide 1976 */ 1977 static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR; 1978 1979 /** 1980 * Text direction is inherited thru {@link ViewGroup} 1981 */ 1982 public static final int TEXT_DIRECTION_INHERIT = 0; 1983 1984 /** 1985 * Text direction is using "first strong algorithm". The first strong directional character 1986 * determines the paragraph direction. If there is no strong directional character, the 1987 * paragraph direction is the view's resolved layout direction. 1988 */ 1989 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 1990 1991 /** 1992 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 1993 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 1994 * If there are neither, the paragraph direction is the view's resolved layout direction. 1995 */ 1996 public static final int TEXT_DIRECTION_ANY_RTL = 2; 1997 1998 /** 1999 * Text direction is forced to LTR. 2000 */ 2001 public static final int TEXT_DIRECTION_LTR = 3; 2002 2003 /** 2004 * Text direction is forced to RTL. 2005 */ 2006 public static final int TEXT_DIRECTION_RTL = 4; 2007 2008 /** 2009 * Text direction is coming from the system Locale. 2010 */ 2011 public static final int TEXT_DIRECTION_LOCALE = 5; 2012 2013 /** 2014 * Default text direction is inherited 2015 */ 2016 private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT; 2017 2018 /** 2019 * Default resolved text direction 2020 * @hide 2021 */ 2022 static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG; 2023 2024 /** 2025 * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED) 2026 * @hide 2027 */ 2028 static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6; 2029 2030 /** 2031 * Mask for use with private flags indicating bits used for text direction. 2032 * @hide 2033 */ 2034 static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007 2035 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2036 2037 /** 2038 * Array of text direction flags for mapping attribute "textDirection" to correct 2039 * flag value. 2040 * @hide 2041 */ 2042 private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = { 2043 TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2044 TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2045 TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2046 TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2047 TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2048 TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT 2049 }; 2050 2051 /** 2052 * Indicates whether the view text direction has been resolved. 2053 * @hide 2054 */ 2055 static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008 2056 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2057 2058 /** 2059 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2060 * @hide 2061 */ 2062 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10; 2063 2064 /** 2065 * Mask for use with private flags indicating bits used for resolved text direction. 2066 * @hide 2067 */ 2068 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 2069 << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2070 2071 /** 2072 * Indicates whether the view text direction has been resolved to the "first strong" heuristic. 2073 * @hide 2074 */ 2075 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT = 2076 TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2077 2078 /** @hide */ 2079 @IntDef({ 2080 TEXT_ALIGNMENT_INHERIT, 2081 TEXT_ALIGNMENT_GRAVITY, 2082 TEXT_ALIGNMENT_CENTER, 2083 TEXT_ALIGNMENT_TEXT_START, 2084 TEXT_ALIGNMENT_TEXT_END, 2085 TEXT_ALIGNMENT_VIEW_START, 2086 TEXT_ALIGNMENT_VIEW_END 2087 }) 2088 @Retention(RetentionPolicy.SOURCE) 2089 public @interface TextAlignment {} 2090 2091 /** 2092 * Default text alignment. The text alignment of this View is inherited from its parent. 2093 * Use with {@link #setTextAlignment(int)} 2094 */ 2095 public static final int TEXT_ALIGNMENT_INHERIT = 0; 2096 2097 /** 2098 * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL, 2099 * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction. 2100 * 2101 * Use with {@link #setTextAlignment(int)} 2102 */ 2103 public static final int TEXT_ALIGNMENT_GRAVITY = 1; 2104 2105 /** 2106 * Align to the start of the paragraph, e.g. ALIGN_NORMAL. 2107 * 2108 * Use with {@link #setTextAlignment(int)} 2109 */ 2110 public static final int TEXT_ALIGNMENT_TEXT_START = 2; 2111 2112 /** 2113 * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE. 2114 * 2115 * Use with {@link #setTextAlignment(int)} 2116 */ 2117 public static final int TEXT_ALIGNMENT_TEXT_END = 3; 2118 2119 /** 2120 * Center the paragraph, e.g. ALIGN_CENTER. 2121 * 2122 * Use with {@link #setTextAlignment(int)} 2123 */ 2124 public static final int TEXT_ALIGNMENT_CENTER = 4; 2125 2126 /** 2127 * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved 2128 * layoutDirection is LTR, and ALIGN_RIGHT otherwise. 2129 * 2130 * Use with {@link #setTextAlignment(int)} 2131 */ 2132 public static final int TEXT_ALIGNMENT_VIEW_START = 5; 2133 2134 /** 2135 * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved 2136 * layoutDirection is LTR, and ALIGN_LEFT otherwise. 2137 * 2138 * Use with {@link #setTextAlignment(int)} 2139 */ 2140 public static final int TEXT_ALIGNMENT_VIEW_END = 6; 2141 2142 /** 2143 * Default text alignment is inherited 2144 */ 2145 private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2146 2147 /** 2148 * Default resolved text alignment 2149 * @hide 2150 */ 2151 static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2152 2153 /** 2154 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2155 * @hide 2156 */ 2157 static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13; 2158 2159 /** 2160 * Mask for use with private flags indicating bits used for text alignment. 2161 * @hide 2162 */ 2163 static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2164 2165 /** 2166 * Array of text direction flags for mapping attribute "textAlignment" to correct 2167 * flag value. 2168 * @hide 2169 */ 2170 private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = { 2171 TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2172 TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2173 TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2174 TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2175 TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2176 TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2177 TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT 2178 }; 2179 2180 /** 2181 * Indicates whether the view text alignment has been resolved. 2182 * @hide 2183 */ 2184 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2185 2186 /** 2187 * Bit shift to get the resolved text alignment. 2188 * @hide 2189 */ 2190 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17; 2191 2192 /** 2193 * Mask for use with private flags indicating bits used for text alignment. 2194 * @hide 2195 */ 2196 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 2197 << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2198 2199 /** 2200 * Indicates whether if the view text alignment has been resolved to gravity 2201 */ 2202 private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT = 2203 TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2204 2205 // Accessiblity constants for mPrivateFlags2 2206 2207 /** 2208 * Shift for the bits in {@link #mPrivateFlags2} related to the 2209 * "importantForAccessibility" attribute. 2210 */ 2211 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20; 2212 2213 /** 2214 * Automatically determine whether a view is important for accessibility. 2215 */ 2216 public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000; 2217 2218 /** 2219 * The view is important for accessibility. 2220 */ 2221 public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001; 2222 2223 /** 2224 * The view is not important for accessibility. 2225 */ 2226 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002; 2227 2228 /** 2229 * The view is not important for accessibility, nor are any of its 2230 * descendant views. 2231 */ 2232 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004; 2233 2234 /** 2235 * The default whether the view is important for accessibility. 2236 */ 2237 static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO; 2238 2239 /** 2240 * Mask for obtainig the bits which specify how to determine 2241 * whether a view is important for accessibility. 2242 */ 2243 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO 2244 | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO 2245 | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) 2246 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2247 2248 /** 2249 * Shift for the bits in {@link #mPrivateFlags2} related to the 2250 * "accessibilityLiveRegion" attribute. 2251 */ 2252 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23; 2253 2254 /** 2255 * Live region mode specifying that accessibility services should not 2256 * automatically announce changes to this view. This is the default live 2257 * region mode for most views. 2258 * <p> 2259 * Use with {@link #setAccessibilityLiveRegion(int)}. 2260 */ 2261 public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000; 2262 2263 /** 2264 * Live region mode specifying that accessibility services should announce 2265 * changes to this view. 2266 * <p> 2267 * Use with {@link #setAccessibilityLiveRegion(int)}. 2268 */ 2269 public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001; 2270 2271 /** 2272 * Live region mode specifying that accessibility services should interrupt 2273 * ongoing speech to immediately announce changes to this view. 2274 * <p> 2275 * Use with {@link #setAccessibilityLiveRegion(int)}. 2276 */ 2277 public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002; 2278 2279 /** 2280 * The default whether the view is important for accessibility. 2281 */ 2282 static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE; 2283 2284 /** 2285 * Mask for obtaining the bits which specify a view's accessibility live 2286 * region mode. 2287 */ 2288 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE 2289 | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE) 2290 << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 2291 2292 /** 2293 * Flag indicating whether a view has accessibility focus. 2294 */ 2295 static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000; 2296 2297 /** 2298 * Flag whether the accessibility state of the subtree rooted at this view changed. 2299 */ 2300 static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000; 2301 2302 /** 2303 * Flag indicating whether a view failed the quickReject() check in draw(). This condition 2304 * is used to check whether later changes to the view's transform should invalidate the 2305 * view to force the quickReject test to run again. 2306 */ 2307 static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000; 2308 2309 /** 2310 * Flag indicating that start/end padding has been resolved into left/right padding 2311 * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()} 2312 * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved 2313 * during measurement. In some special cases this is required such as when an adapter-based 2314 * view measures prospective children without attaching them to a window. 2315 */ 2316 static final int PFLAG2_PADDING_RESOLVED = 0x20000000; 2317 2318 /** 2319 * Flag indicating that the start/end drawables has been resolved into left/right ones. 2320 */ 2321 static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000; 2322 2323 /** 2324 * Indicates that the view is tracking some sort of transient state 2325 * that the app should not need to be aware of, but that the framework 2326 * should take special care to preserve. 2327 */ 2328 static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000; 2329 2330 /** 2331 * Group of bits indicating that RTL properties resolution is done. 2332 */ 2333 static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED | 2334 PFLAG2_TEXT_DIRECTION_RESOLVED | 2335 PFLAG2_TEXT_ALIGNMENT_RESOLVED | 2336 PFLAG2_PADDING_RESOLVED | 2337 PFLAG2_DRAWABLE_RESOLVED; 2338 2339 // There are a couple of flags left in mPrivateFlags2 2340 2341 /* End of masks for mPrivateFlags2 */ 2342 2343 /** 2344 * Masks for mPrivateFlags3, as generated by dumpFlags(): 2345 * 2346 * |-------|-------|-------|-------| 2347 * 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM 2348 * 1 PFLAG3_VIEW_IS_ANIMATING_ALPHA 2349 * 1 PFLAG3_IS_LAID_OUT 2350 * 1 PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT 2351 * 1 PFLAG3_CALLED_SUPER 2352 * |-------|-------|-------|-------| 2353 */ 2354 2355 /** 2356 * Flag indicating that view has a transform animation set on it. This is used to track whether 2357 * an animation is cleared between successive frames, in order to tell the associated 2358 * DisplayList to clear its animation matrix. 2359 */ 2360 static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1; 2361 2362 /** 2363 * Flag indicating that view has an alpha animation set on it. This is used to track whether an 2364 * animation is cleared between successive frames, in order to tell the associated 2365 * DisplayList to restore its alpha value. 2366 */ 2367 static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2; 2368 2369 /** 2370 * Flag indicating that the view has been through at least one layout since it 2371 * was last attached to a window. 2372 */ 2373 static final int PFLAG3_IS_LAID_OUT = 0x4; 2374 2375 /** 2376 * Flag indicating that a call to measure() was skipped and should be done 2377 * instead when layout() is invoked. 2378 */ 2379 static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8; 2380 2381 /** 2382 * Flag indicating that an overridden method correctly called down to 2383 * the superclass implementation as required by the API spec. 2384 */ 2385 static final int PFLAG3_CALLED_SUPER = 0x10; 2386 2387 /** 2388 * Flag indicating that we're in the process of applying window insets. 2389 */ 2390 static final int PFLAG3_APPLYING_INSETS = 0x20; 2391 2392 /** 2393 * Flag indicating that we're in the process of fitting system windows using the old method. 2394 */ 2395 static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40; 2396 2397 /** 2398 * Flag indicating that nested scrolling is enabled for this view. 2399 * The view will optionally cooperate with views up its parent chain to allow for 2400 * integrated nested scrolling along the same axis. 2401 */ 2402 static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80; 2403 2404 /** 2405 * Flag indicating that outline was invalidated and should be rebuilt the next time 2406 * the DisplayList is updated. 2407 */ 2408 static final int PFLAG3_OUTLINE_INVALID = 0x100; 2409 2410 /* End of masks for mPrivateFlags3 */ 2411 2412 static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED; 2413 2414 /** 2415 * Always allow a user to over-scroll this view, provided it is a 2416 * view that can scroll. 2417 * 2418 * @see #getOverScrollMode() 2419 * @see #setOverScrollMode(int) 2420 */ 2421 public static final int OVER_SCROLL_ALWAYS = 0; 2422 2423 /** 2424 * Allow a user to over-scroll this view only if the content is large 2425 * enough to meaningfully scroll, provided it is a view that can scroll. 2426 * 2427 * @see #getOverScrollMode() 2428 * @see #setOverScrollMode(int) 2429 */ 2430 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 2431 2432 /** 2433 * Never allow a user to over-scroll this view. 2434 * 2435 * @see #getOverScrollMode() 2436 * @see #setOverScrollMode(int) 2437 */ 2438 public static final int OVER_SCROLL_NEVER = 2; 2439 2440 /** 2441 * Special constant for {@link #setSystemUiVisibility(int)}: View has 2442 * requested the system UI (status bar) to be visible (the default). 2443 * 2444 * @see #setSystemUiVisibility(int) 2445 */ 2446 public static final int SYSTEM_UI_FLAG_VISIBLE = 0; 2447 2448 /** 2449 * Flag for {@link #setSystemUiVisibility(int)}: View has requested the 2450 * system UI to enter an unobtrusive "low profile" mode. 2451 * 2452 * <p>This is for use in games, book readers, video players, or any other 2453 * "immersive" application where the usual system chrome is deemed too distracting. 2454 * 2455 * <p>In low profile mode, the status bar and/or navigation icons may dim. 2456 * 2457 * @see #setSystemUiVisibility(int) 2458 */ 2459 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001; 2460 2461 /** 2462 * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the 2463 * system navigation be temporarily hidden. 2464 * 2465 * <p>This is an even less obtrusive state than that called for by 2466 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls 2467 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause 2468 * those to disappear. This is useful (in conjunction with the 2469 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and 2470 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN} 2471 * window flags) for displaying content using every last pixel on the display. 2472 * 2473 * <p>There is a limitation: because navigation controls are so important, the least user 2474 * interaction will cause them to reappear immediately. When this happens, both 2475 * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically, 2476 * so that both elements reappear at the same time. 2477 * 2478 * @see #setSystemUiVisibility(int) 2479 */ 2480 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002; 2481 2482 /** 2483 * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go 2484 * into the normal fullscreen mode so that its content can take over the screen 2485 * while still allowing the user to interact with the application. 2486 * 2487 * <p>This has the same visual effect as 2488 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN 2489 * WindowManager.LayoutParams.FLAG_FULLSCREEN}, 2490 * meaning that non-critical screen decorations (such as the status bar) will be 2491 * hidden while the user is in the View's window, focusing the experience on 2492 * that content. Unlike the window flag, if you are using ActionBar in 2493 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2494 * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also 2495 * hide the action bar. 2496 * 2497 * <p>This approach to going fullscreen is best used over the window flag when 2498 * it is a transient state -- that is, the application does this at certain 2499 * points in its user interaction where it wants to allow the user to focus 2500 * on content, but not as a continuous state. For situations where the application 2501 * would like to simply stay full screen the entire time (such as a game that 2502 * wants to take over the screen), the 2503 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag} 2504 * is usually a better approach. The state set here will be removed by the system 2505 * in various situations (such as the user moving to another application) like 2506 * the other system UI states. 2507 * 2508 * <p>When using this flag, the application should provide some easy facility 2509 * for the user to go out of it. A common example would be in an e-book 2510 * reader, where tapping on the screen brings back whatever screen and UI 2511 * decorations that had been hidden while the user was immersed in reading 2512 * the book. 2513 * 2514 * @see #setSystemUiVisibility(int) 2515 */ 2516 public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004; 2517 2518 /** 2519 * Flag for {@link #setSystemUiVisibility(int)}: When using other layout 2520 * flags, we would like a stable view of the content insets given to 2521 * {@link #fitSystemWindows(Rect)}. This means that the insets seen there 2522 * will always represent the worst case that the application can expect 2523 * as a continuous state. In the stock Android UI this is the space for 2524 * the system bar, nav bar, and status bar, but not more transient elements 2525 * such as an input method. 2526 * 2527 * The stable layout your UI sees is based on the system UI modes you can 2528 * switch to. That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 2529 * then you will get a stable layout for changes of the 2530 * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify 2531 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and 2532 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition 2533 * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} 2534 * with a stable layout. (Note that you should avoid using 2535 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.) 2536 * 2537 * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN} 2538 * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}), 2539 * then a hidden status bar will be considered a "stable" state for purposes 2540 * here. This allows your UI to continually hide the status bar, while still 2541 * using the system UI flags to hide the action bar while still retaining 2542 * a stable layout. Note that changing the window fullscreen flag will never 2543 * provide a stable layout for a clean transition. 2544 * 2545 * <p>If you are using ActionBar in 2546 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2547 * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the 2548 * insets it adds to those given to the application. 2549 */ 2550 public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100; 2551 2552 /** 2553 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2554 * to be layed out as if it has requested 2555 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't. This 2556 * allows it to avoid artifacts when switching in and out of that mode, at 2557 * the expense that some of its user interface may be covered by screen 2558 * decorations when they are shown. You can perform layout of your inner 2559 * UI elements to account for the navigation system UI through the 2560 * {@link #fitSystemWindows(Rect)} method. 2561 */ 2562 public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200; 2563 2564 /** 2565 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2566 * to be layed out as if it has requested 2567 * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't. This 2568 * allows it to avoid artifacts when switching in and out of that mode, at 2569 * the expense that some of its user interface may be covered by screen 2570 * decorations when they are shown. You can perform layout of your inner 2571 * UI elements to account for non-fullscreen system UI through the 2572 * {@link #fitSystemWindows(Rect)} method. 2573 */ 2574 public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400; 2575 2576 /** 2577 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2578 * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. If this flag is 2579 * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any 2580 * user interaction. 2581 * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only 2582 * has an effect when used in combination with that flag.</p> 2583 */ 2584 public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800; 2585 2586 /** 2587 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2588 * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation 2589 * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. Use this flag to create an immersive 2590 * experience while also hiding the system bars. If this flag is not set, 2591 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user 2592 * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system 2593 * if the user swipes from the top of the screen. 2594 * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with 2595 * system gestures, such as swiping from the top of the screen. These transient system bars 2596 * will overlay app’s content, may have some degree of transparency, and will automatically 2597 * hide after a short timeout. 2598 * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and 2599 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination 2600 * with one or both of those flags.</p> 2601 */ 2602 public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000; 2603 2604 /** 2605 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead. 2606 */ 2607 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE; 2608 2609 /** 2610 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead. 2611 */ 2612 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE; 2613 2614 /** 2615 * @hide 2616 * 2617 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2618 * out of the public fields to keep the undefined bits out of the developer's way. 2619 * 2620 * Flag to make the status bar not expandable. Unless you also 2621 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 2622 */ 2623 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 2624 2625 /** 2626 * @hide 2627 * 2628 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2629 * out of the public fields to keep the undefined bits out of the developer's way. 2630 * 2631 * Flag to hide notification icons and scrolling ticker text. 2632 */ 2633 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 2634 2635 /** 2636 * @hide 2637 * 2638 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2639 * out of the public fields to keep the undefined bits out of the developer's way. 2640 * 2641 * Flag to disable incoming notification alerts. This will not block 2642 * icons, but it will block sound, vibrating and other visual or aural notifications. 2643 */ 2644 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 2645 2646 /** 2647 * @hide 2648 * 2649 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2650 * out of the public fields to keep the undefined bits out of the developer's way. 2651 * 2652 * Flag to hide only the scrolling ticker. Note that 2653 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 2654 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 2655 */ 2656 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 2657 2658 /** 2659 * @hide 2660 * 2661 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2662 * out of the public fields to keep the undefined bits out of the developer's way. 2663 * 2664 * Flag to hide the center system info area. 2665 */ 2666 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 2667 2668 /** 2669 * @hide 2670 * 2671 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2672 * out of the public fields to keep the undefined bits out of the developer's way. 2673 * 2674 * Flag to hide only the home button. Don't use this 2675 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2676 */ 2677 public static final int STATUS_BAR_DISABLE_HOME = 0x00200000; 2678 2679 /** 2680 * @hide 2681 * 2682 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2683 * out of the public fields to keep the undefined bits out of the developer's way. 2684 * 2685 * Flag to hide only the back button. Don't use this 2686 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2687 */ 2688 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 2689 2690 /** 2691 * @hide 2692 * 2693 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2694 * out of the public fields to keep the undefined bits out of the developer's way. 2695 * 2696 * Flag to hide only the clock. You might use this if your activity has 2697 * its own clock making the status bar's clock redundant. 2698 */ 2699 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 2700 2701 /** 2702 * @hide 2703 * 2704 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2705 * out of the public fields to keep the undefined bits out of the developer's way. 2706 * 2707 * Flag to hide only the recent apps button. Don't use this 2708 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2709 */ 2710 public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000; 2711 2712 /** 2713 * @hide 2714 * 2715 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2716 * out of the public fields to keep the undefined bits out of the developer's way. 2717 * 2718 * Flag to disable the global search gesture. Don't use this 2719 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2720 */ 2721 public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000; 2722 2723 /** 2724 * @hide 2725 * 2726 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2727 * out of the public fields to keep the undefined bits out of the developer's way. 2728 * 2729 * Flag to specify that the status bar is displayed in transient mode. 2730 */ 2731 public static final int STATUS_BAR_TRANSIENT = 0x04000000; 2732 2733 /** 2734 * @hide 2735 * 2736 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2737 * out of the public fields to keep the undefined bits out of the developer's way. 2738 * 2739 * Flag to specify that the navigation bar is displayed in transient mode. 2740 */ 2741 public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000; 2742 2743 /** 2744 * @hide 2745 * 2746 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2747 * out of the public fields to keep the undefined bits out of the developer's way. 2748 * 2749 * Flag to specify that the hidden status bar would like to be shown. 2750 */ 2751 public static final int STATUS_BAR_UNHIDE = 0x10000000; 2752 2753 /** 2754 * @hide 2755 * 2756 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2757 * out of the public fields to keep the undefined bits out of the developer's way. 2758 * 2759 * Flag to specify that the hidden navigation bar would like to be shown. 2760 */ 2761 public static final int NAVIGATION_BAR_UNHIDE = 0x20000000; 2762 2763 /** 2764 * @hide 2765 * 2766 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2767 * out of the public fields to keep the undefined bits out of the developer's way. 2768 * 2769 * Flag to specify that the status bar is displayed in translucent mode. 2770 */ 2771 public static final int STATUS_BAR_TRANSLUCENT = 0x40000000; 2772 2773 /** 2774 * @hide 2775 * 2776 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2777 * out of the public fields to keep the undefined bits out of the developer's way. 2778 * 2779 * Flag to specify that the navigation bar is displayed in translucent mode. 2780 */ 2781 public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000; 2782 2783 /** 2784 * @hide 2785 * 2786 * Whether Recents is visible or not. 2787 */ 2788 public static final int RECENT_APPS_VISIBLE = 0x00004000; 2789 2790 /** 2791 * @hide 2792 * 2793 * Makes system ui transparent. 2794 */ 2795 public static final int SYSTEM_UI_TRANSPARENT = 0x00008000; 2796 2797 /** 2798 * @hide 2799 */ 2800 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FFF; 2801 2802 /** 2803 * These are the system UI flags that can be cleared by events outside 2804 * of an application. Currently this is just the ability to tap on the 2805 * screen while hiding the navigation bar to have it return. 2806 * @hide 2807 */ 2808 public static final int SYSTEM_UI_CLEARABLE_FLAGS = 2809 SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION 2810 | SYSTEM_UI_FLAG_FULLSCREEN; 2811 2812 /** 2813 * Flags that can impact the layout in relation to system UI. 2814 */ 2815 public static final int SYSTEM_UI_LAYOUT_FLAGS = 2816 SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 2817 | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; 2818 2819 /** @hide */ 2820 @IntDef(flag = true, 2821 value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION }) 2822 @Retention(RetentionPolicy.SOURCE) 2823 public @interface FindViewFlags {} 2824 2825 /** 2826 * Find views that render the specified text. 2827 * 2828 * @see #findViewsWithText(ArrayList, CharSequence, int) 2829 */ 2830 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001; 2831 2832 /** 2833 * Find find views that contain the specified content description. 2834 * 2835 * @see #findViewsWithText(ArrayList, CharSequence, int) 2836 */ 2837 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002; 2838 2839 /** 2840 * Find views that contain {@link AccessibilityNodeProvider}. Such 2841 * a View is a root of virtual view hierarchy and may contain the searched 2842 * text. If this flag is set Views with providers are automatically 2843 * added and it is a responsibility of the client to call the APIs of 2844 * the provider to determine whether the virtual tree rooted at this View 2845 * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s 2846 * representing the virtual views with this text. 2847 * 2848 * @see #findViewsWithText(ArrayList, CharSequence, int) 2849 * 2850 * @hide 2851 */ 2852 public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004; 2853 2854 /** 2855 * The undefined cursor position. 2856 * 2857 * @hide 2858 */ 2859 public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1; 2860 2861 /** 2862 * Indicates that the screen has changed state and is now off. 2863 * 2864 * @see #onScreenStateChanged(int) 2865 */ 2866 public static final int SCREEN_STATE_OFF = 0x0; 2867 2868 /** 2869 * Indicates that the screen has changed state and is now on. 2870 * 2871 * @see #onScreenStateChanged(int) 2872 */ 2873 public static final int SCREEN_STATE_ON = 0x1; 2874 2875 /** 2876 * Indicates no axis of view scrolling. 2877 */ 2878 public static final int SCROLL_AXIS_NONE = 0; 2879 2880 /** 2881 * Indicates scrolling along the horizontal axis. 2882 */ 2883 public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0; 2884 2885 /** 2886 * Indicates scrolling along the vertical axis. 2887 */ 2888 public static final int SCROLL_AXIS_VERTICAL = 1 << 1; 2889 2890 /** 2891 * Controls the over-scroll mode for this view. 2892 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 2893 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 2894 * and {@link #OVER_SCROLL_NEVER}. 2895 */ 2896 private int mOverScrollMode; 2897 2898 /** 2899 * The parent this view is attached to. 2900 * {@hide} 2901 * 2902 * @see #getParent() 2903 */ 2904 protected ViewParent mParent; 2905 2906 /** 2907 * {@hide} 2908 */ 2909 AttachInfo mAttachInfo; 2910 2911 /** 2912 * {@hide} 2913 */ 2914 @ViewDebug.ExportedProperty(flagMapping = { 2915 @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT, 2916 name = "FORCE_LAYOUT"), 2917 @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED, 2918 name = "LAYOUT_REQUIRED"), 2919 @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID, 2920 name = "DRAWING_CACHE_INVALID", outputIf = false), 2921 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true), 2922 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false), 2923 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 2924 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY") 2925 }, formatToHexString = true) 2926 int mPrivateFlags; 2927 int mPrivateFlags2; 2928 int mPrivateFlags3; 2929 2930 /** 2931 * This view's request for the visibility of the status bar. 2932 * @hide 2933 */ 2934 @ViewDebug.ExportedProperty(flagMapping = { 2935 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 2936 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 2937 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 2938 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2939 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2940 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 2941 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 2942 equals = SYSTEM_UI_FLAG_VISIBLE, 2943 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 2944 }, formatToHexString = true) 2945 int mSystemUiVisibility; 2946 2947 /** 2948 * Reference count for transient state. 2949 * @see #setHasTransientState(boolean) 2950 */ 2951 int mTransientStateCount = 0; 2952 2953 /** 2954 * Count of how many windows this view has been attached to. 2955 */ 2956 int mWindowAttachCount; 2957 2958 /** 2959 * The layout parameters associated with this view and used by the parent 2960 * {@link android.view.ViewGroup} to determine how this view should be 2961 * laid out. 2962 * {@hide} 2963 */ 2964 protected ViewGroup.LayoutParams mLayoutParams; 2965 2966 /** 2967 * The view flags hold various views states. 2968 * {@hide} 2969 */ 2970 @ViewDebug.ExportedProperty(formatToHexString = true) 2971 int mViewFlags; 2972 2973 static class TransformationInfo { 2974 /** 2975 * The transform matrix for the View. This transform is calculated internally 2976 * based on the translation, rotation, and scale properties. 2977 * 2978 * Do *not* use this variable directly; instead call getMatrix(), which will 2979 * load the value from the View's RenderNode. 2980 */ 2981 private final Matrix mMatrix = new Matrix(); 2982 2983 /** 2984 * The inverse transform matrix for the View. This transform is calculated 2985 * internally based on the translation, rotation, and scale properties. 2986 * 2987 * Do *not* use this variable directly; instead call getInverseMatrix(), 2988 * which will load the value from the View's RenderNode. 2989 */ 2990 private Matrix mInverseMatrix; 2991 2992 /** 2993 * The opacity of the View. This is a value from 0 to 1, where 0 means 2994 * completely transparent and 1 means completely opaque. 2995 */ 2996 @ViewDebug.ExportedProperty 2997 float mAlpha = 1f; 2998 2999 /** 3000 * The opacity of the view as manipulated by the Fade transition. This is a hidden 3001 * property only used by transitions, which is composited with the other alpha 3002 * values to calculate the final visual alpha value. 3003 */ 3004 float mTransitionAlpha = 1f; 3005 } 3006 3007 TransformationInfo mTransformationInfo; 3008 3009 /** 3010 * Current clip bounds. to which all drawing of this view are constrained. 3011 */ 3012 Rect mClipBounds = null; 3013 3014 private boolean mLastIsOpaque; 3015 3016 /** 3017 * The distance in pixels from the left edge of this view's parent 3018 * to the left edge of this view. 3019 * {@hide} 3020 */ 3021 @ViewDebug.ExportedProperty(category = "layout") 3022 protected int mLeft; 3023 /** 3024 * The distance in pixels from the left edge of this view's parent 3025 * to the right edge of this view. 3026 * {@hide} 3027 */ 3028 @ViewDebug.ExportedProperty(category = "layout") 3029 protected int mRight; 3030 /** 3031 * The distance in pixels from the top edge of this view's parent 3032 * to the top edge of this view. 3033 * {@hide} 3034 */ 3035 @ViewDebug.ExportedProperty(category = "layout") 3036 protected int mTop; 3037 /** 3038 * The distance in pixels from the top edge of this view's parent 3039 * to the bottom edge of this view. 3040 * {@hide} 3041 */ 3042 @ViewDebug.ExportedProperty(category = "layout") 3043 protected int mBottom; 3044 3045 /** 3046 * The offset, in pixels, by which the content of this view is scrolled 3047 * horizontally. 3048 * {@hide} 3049 */ 3050 @ViewDebug.ExportedProperty(category = "scrolling") 3051 protected int mScrollX; 3052 /** 3053 * The offset, in pixels, by which the content of this view is scrolled 3054 * vertically. 3055 * {@hide} 3056 */ 3057 @ViewDebug.ExportedProperty(category = "scrolling") 3058 protected int mScrollY; 3059 3060 /** 3061 * The left padding in pixels, that is the distance in pixels between the 3062 * left edge of this view and the left edge of its content. 3063 * {@hide} 3064 */ 3065 @ViewDebug.ExportedProperty(category = "padding") 3066 protected int mPaddingLeft = 0; 3067 /** 3068 * The right padding in pixels, that is the distance in pixels between the 3069 * right edge of this view and the right edge of its content. 3070 * {@hide} 3071 */ 3072 @ViewDebug.ExportedProperty(category = "padding") 3073 protected int mPaddingRight = 0; 3074 /** 3075 * The top padding in pixels, that is the distance in pixels between the 3076 * top edge of this view and the top edge of its content. 3077 * {@hide} 3078 */ 3079 @ViewDebug.ExportedProperty(category = "padding") 3080 protected int mPaddingTop; 3081 /** 3082 * The bottom padding in pixels, that is the distance in pixels between the 3083 * bottom edge of this view and the bottom edge of its content. 3084 * {@hide} 3085 */ 3086 @ViewDebug.ExportedProperty(category = "padding") 3087 protected int mPaddingBottom; 3088 3089 /** 3090 * The layout insets in pixels, that is the distance in pixels between the 3091 * visible edges of this view its bounds. 3092 */ 3093 private Insets mLayoutInsets; 3094 3095 /** 3096 * Briefly describes the view and is primarily used for accessibility support. 3097 */ 3098 private CharSequence mContentDescription; 3099 3100 /** 3101 * Specifies the id of a view for which this view serves as a label for 3102 * accessibility purposes. 3103 */ 3104 private int mLabelForId = View.NO_ID; 3105 3106 /** 3107 * Predicate for matching labeled view id with its label for 3108 * accessibility purposes. 3109 */ 3110 private MatchLabelForPredicate mMatchLabelForPredicate; 3111 3112 /** 3113 * Specifies a view before which this one is visited in accessibility traversal. 3114 */ 3115 private int mAccessibilityTraversalBeforeId = NO_ID; 3116 3117 /** 3118 * Specifies a view after which this one is visited in accessibility traversal. 3119 */ 3120 private int mAccessibilityTraversalAfterId = NO_ID; 3121 3122 /** 3123 * Predicate for matching a view by its id. 3124 */ 3125 private MatchIdPredicate mMatchIdPredicate; 3126 3127 /** 3128 * Cache the paddingRight set by the user to append to the scrollbar's size. 3129 * 3130 * @hide 3131 */ 3132 @ViewDebug.ExportedProperty(category = "padding") 3133 protected int mUserPaddingRight; 3134 3135 /** 3136 * Cache the paddingBottom set by the user to append to the scrollbar's size. 3137 * 3138 * @hide 3139 */ 3140 @ViewDebug.ExportedProperty(category = "padding") 3141 protected int mUserPaddingBottom; 3142 3143 /** 3144 * Cache the paddingLeft set by the user to append to the scrollbar's size. 3145 * 3146 * @hide 3147 */ 3148 @ViewDebug.ExportedProperty(category = "padding") 3149 protected int mUserPaddingLeft; 3150 3151 /** 3152 * Cache the paddingStart set by the user to append to the scrollbar's size. 3153 * 3154 */ 3155 @ViewDebug.ExportedProperty(category = "padding") 3156 int mUserPaddingStart; 3157 3158 /** 3159 * Cache the paddingEnd set by the user to append to the scrollbar's size. 3160 * 3161 */ 3162 @ViewDebug.ExportedProperty(category = "padding") 3163 int mUserPaddingEnd; 3164 3165 /** 3166 * Cache initial left padding. 3167 * 3168 * @hide 3169 */ 3170 int mUserPaddingLeftInitial; 3171 3172 /** 3173 * Cache initial right padding. 3174 * 3175 * @hide 3176 */ 3177 int mUserPaddingRightInitial; 3178 3179 /** 3180 * Default undefined padding 3181 */ 3182 private static final int UNDEFINED_PADDING = Integer.MIN_VALUE; 3183 3184 /** 3185 * Cache if a left padding has been defined 3186 */ 3187 private boolean mLeftPaddingDefined = false; 3188 3189 /** 3190 * Cache if a right padding has been defined 3191 */ 3192 private boolean mRightPaddingDefined = false; 3193 3194 /** 3195 * @hide 3196 */ 3197 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 3198 /** 3199 * @hide 3200 */ 3201 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 3202 3203 private LongSparseLongArray mMeasureCache; 3204 3205 @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_") 3206 private Drawable mBackground; 3207 private TintInfo mBackgroundTint; 3208 3209 /** 3210 * RenderNode used for backgrounds. 3211 * <p> 3212 * When non-null and valid, this is expected to contain an up-to-date copy 3213 * of the background drawable. It is cleared on temporary detach, and reset 3214 * on cleanup. 3215 */ 3216 private RenderNode mBackgroundRenderNode; 3217 3218 private int mBackgroundResource; 3219 private boolean mBackgroundSizeChanged; 3220 3221 private String mTransitionName; 3222 3223 private static class TintInfo { 3224 ColorStateList mTintList; 3225 PorterDuff.Mode mTintMode; 3226 boolean mHasTintMode; 3227 boolean mHasTintList; 3228 } 3229 3230 static class ListenerInfo { 3231 /** 3232 * Listener used to dispatch focus change events. 3233 * This field should be made private, so it is hidden from the SDK. 3234 * {@hide} 3235 */ 3236 protected OnFocusChangeListener mOnFocusChangeListener; 3237 3238 /** 3239 * Listeners for layout change events. 3240 */ 3241 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 3242 3243 protected OnScrollChangeListener mOnScrollChangeListener; 3244 3245 /** 3246 * Listeners for attach events. 3247 */ 3248 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 3249 3250 /** 3251 * Listener used to dispatch click events. 3252 * This field should be made private, so it is hidden from the SDK. 3253 * {@hide} 3254 */ 3255 public OnClickListener mOnClickListener; 3256 3257 /** 3258 * Listener used to dispatch long click events. 3259 * This field should be made private, so it is hidden from the SDK. 3260 * {@hide} 3261 */ 3262 protected OnLongClickListener mOnLongClickListener; 3263 3264 /** 3265 * Listener used to build the context menu. 3266 * This field should be made private, so it is hidden from the SDK. 3267 * {@hide} 3268 */ 3269 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 3270 3271 private OnKeyListener mOnKeyListener; 3272 3273 private OnTouchListener mOnTouchListener; 3274 3275 private OnHoverListener mOnHoverListener; 3276 3277 private OnGenericMotionListener mOnGenericMotionListener; 3278 3279 private OnDragListener mOnDragListener; 3280 3281 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 3282 3283 OnApplyWindowInsetsListener mOnApplyWindowInsetsListener; 3284 } 3285 3286 ListenerInfo mListenerInfo; 3287 3288 /** 3289 * The application environment this view lives in. 3290 * This field should be made private, so it is hidden from the SDK. 3291 * {@hide} 3292 */ 3293 @ViewDebug.ExportedProperty(deepExport = true) 3294 protected Context mContext; 3295 3296 private final Resources mResources; 3297 3298 private ScrollabilityCache mScrollCache; 3299 3300 private int[] mDrawableState = null; 3301 3302 ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND; 3303 3304 /** 3305 * Animator that automatically runs based on state changes. 3306 */ 3307 private StateListAnimator mStateListAnimator; 3308 3309 /** 3310 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 3311 * the user may specify which view to go to next. 3312 */ 3313 private int mNextFocusLeftId = View.NO_ID; 3314 3315 /** 3316 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 3317 * the user may specify which view to go to next. 3318 */ 3319 private int mNextFocusRightId = View.NO_ID; 3320 3321 /** 3322 * When this view has focus and the next focus is {@link #FOCUS_UP}, 3323 * the user may specify which view to go to next. 3324 */ 3325 private int mNextFocusUpId = View.NO_ID; 3326 3327 /** 3328 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 3329 * the user may specify which view to go to next. 3330 */ 3331 private int mNextFocusDownId = View.NO_ID; 3332 3333 /** 3334 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 3335 * the user may specify which view to go to next. 3336 */ 3337 int mNextFocusForwardId = View.NO_ID; 3338 3339 private CheckForLongPress mPendingCheckForLongPress; 3340 private CheckForTap mPendingCheckForTap = null; 3341 private PerformClick mPerformClick; 3342 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 3343 3344 private UnsetPressedState mUnsetPressedState; 3345 3346 /** 3347 * Whether the long press's action has been invoked. The tap's action is invoked on the 3348 * up event while a long press is invoked as soon as the long press duration is reached, so 3349 * a long press could be performed before the tap is checked, in which case the tap's action 3350 * should not be invoked. 3351 */ 3352 private boolean mHasPerformedLongPress; 3353 3354 /** 3355 * The minimum height of the view. We'll try our best to have the height 3356 * of this view to at least this amount. 3357 */ 3358 @ViewDebug.ExportedProperty(category = "measurement") 3359 private int mMinHeight; 3360 3361 /** 3362 * The minimum width of the view. We'll try our best to have the width 3363 * of this view to at least this amount. 3364 */ 3365 @ViewDebug.ExportedProperty(category = "measurement") 3366 private int mMinWidth; 3367 3368 /** 3369 * The delegate to handle touch events that are physically in this view 3370 * but should be handled by another view. 3371 */ 3372 private TouchDelegate mTouchDelegate = null; 3373 3374 /** 3375 * Solid color to use as a background when creating the drawing cache. Enables 3376 * the cache to use 16 bit bitmaps instead of 32 bit. 3377 */ 3378 private int mDrawingCacheBackgroundColor = 0; 3379 3380 /** 3381 * Special tree observer used when mAttachInfo is null. 3382 */ 3383 private ViewTreeObserver mFloatingTreeObserver; 3384 3385 /** 3386 * Cache the touch slop from the context that created the view. 3387 */ 3388 private int mTouchSlop; 3389 3390 /** 3391 * Object that handles automatic animation of view properties. 3392 */ 3393 private ViewPropertyAnimator mAnimator = null; 3394 3395 /** 3396 * Flag indicating that a drag can cross window boundaries. When 3397 * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called 3398 * with this flag set, all visible applications will be able to participate 3399 * in the drag operation and receive the dragged content. 3400 * 3401 * @hide 3402 */ 3403 public static final int DRAG_FLAG_GLOBAL = 1; 3404 3405 /** 3406 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 3407 */ 3408 private float mVerticalScrollFactor; 3409 3410 /** 3411 * Position of the vertical scroll bar. 3412 */ 3413 private int mVerticalScrollbarPosition; 3414 3415 /** 3416 * Position the scroll bar at the default position as determined by the system. 3417 */ 3418 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 3419 3420 /** 3421 * Position the scroll bar along the left edge. 3422 */ 3423 public static final int SCROLLBAR_POSITION_LEFT = 1; 3424 3425 /** 3426 * Position the scroll bar along the right edge. 3427 */ 3428 public static final int SCROLLBAR_POSITION_RIGHT = 2; 3429 3430 /** 3431 * Indicates that the view does not have a layer. 3432 * 3433 * @see #getLayerType() 3434 * @see #setLayerType(int, android.graphics.Paint) 3435 * @see #LAYER_TYPE_SOFTWARE 3436 * @see #LAYER_TYPE_HARDWARE 3437 */ 3438 public static final int LAYER_TYPE_NONE = 0; 3439 3440 /** 3441 * <p>Indicates that the view has a software layer. A software layer is backed 3442 * by a bitmap and causes the view to be rendered using Android's software 3443 * rendering pipeline, even if hardware acceleration is enabled.</p> 3444 * 3445 * <p>Software layers have various usages:</p> 3446 * <p>When the application is not using hardware acceleration, a software layer 3447 * is useful to apply a specific color filter and/or blending mode and/or 3448 * translucency to a view and all its children.</p> 3449 * <p>When the application is using hardware acceleration, a software layer 3450 * is useful to render drawing primitives not supported by the hardware 3451 * accelerated pipeline. It can also be used to cache a complex view tree 3452 * into a texture and reduce the complexity of drawing operations. For instance, 3453 * when animating a complex view tree with a translation, a software layer can 3454 * be used to render the view tree only once.</p> 3455 * <p>Software layers should be avoided when the affected view tree updates 3456 * often. Every update will require to re-render the software layer, which can 3457 * potentially be slow (particularly when hardware acceleration is turned on 3458 * since the layer will have to be uploaded into a hardware texture after every 3459 * update.)</p> 3460 * 3461 * @see #getLayerType() 3462 * @see #setLayerType(int, android.graphics.Paint) 3463 * @see #LAYER_TYPE_NONE 3464 * @see #LAYER_TYPE_HARDWARE 3465 */ 3466 public static final int LAYER_TYPE_SOFTWARE = 1; 3467 3468 /** 3469 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 3470 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 3471 * OpenGL hardware) and causes the view to be rendered using Android's hardware 3472 * rendering pipeline, but only if hardware acceleration is turned on for the 3473 * view hierarchy. When hardware acceleration is turned off, hardware layers 3474 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 3475 * 3476 * <p>A hardware layer is useful to apply a specific color filter and/or 3477 * blending mode and/or translucency to a view and all its children.</p> 3478 * <p>A hardware layer can be used to cache a complex view tree into a 3479 * texture and reduce the complexity of drawing operations. For instance, 3480 * when animating a complex view tree with a translation, a hardware layer can 3481 * be used to render the view tree only once.</p> 3482 * <p>A hardware layer can also be used to increase the rendering quality when 3483 * rotation transformations are applied on a view. It can also be used to 3484 * prevent potential clipping issues when applying 3D transforms on a view.</p> 3485 * 3486 * @see #getLayerType() 3487 * @see #setLayerType(int, android.graphics.Paint) 3488 * @see #LAYER_TYPE_NONE 3489 * @see #LAYER_TYPE_SOFTWARE 3490 */ 3491 public static final int LAYER_TYPE_HARDWARE = 2; 3492 3493 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 3494 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 3495 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 3496 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 3497 }) 3498 int mLayerType = LAYER_TYPE_NONE; 3499 Paint mLayerPaint; 3500 3501 /** 3502 * Set to true when drawing cache is enabled and cannot be created. 3503 * 3504 * @hide 3505 */ 3506 public boolean mCachingFailed; 3507 private Bitmap mDrawingCache; 3508 private Bitmap mUnscaledDrawingCache; 3509 3510 /** 3511 * RenderNode holding View properties, potentially holding a DisplayList of View content. 3512 * <p> 3513 * When non-null and valid, this is expected to contain an up-to-date copy 3514 * of the View content. Its DisplayList content is cleared on temporary detach and reset on 3515 * cleanup. 3516 */ 3517 final RenderNode mRenderNode; 3518 3519 /** 3520 * Set to true when the view is sending hover accessibility events because it 3521 * is the innermost hovered view. 3522 */ 3523 private boolean mSendingHoverAccessibilityEvents; 3524 3525 /** 3526 * Delegate for injecting accessibility functionality. 3527 */ 3528 AccessibilityDelegate mAccessibilityDelegate; 3529 3530 /** 3531 * The view's overlay layer. Developers get a reference to the overlay via getOverlay() 3532 * and add/remove objects to/from the overlay directly through the Overlay methods. 3533 */ 3534 ViewOverlay mOverlay; 3535 3536 /** 3537 * The currently active parent view for receiving delegated nested scrolling events. 3538 * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared 3539 * by {@link #stopNestedScroll()} at the same point where we clear 3540 * requestDisallowInterceptTouchEvent. 3541 */ 3542 private ViewParent mNestedScrollingParent; 3543 3544 /** 3545 * Consistency verifier for debugging purposes. 3546 * @hide 3547 */ 3548 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 3549 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 3550 new InputEventConsistencyVerifier(this, 0) : null; 3551 3552 private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); 3553 3554 private int[] mTempNestedScrollConsumed; 3555 3556 /** 3557 * An overlay is going to draw this View instead of being drawn as part of this 3558 * View's parent. mGhostView is the View in the Overlay that must be invalidated 3559 * when this view is invalidated. 3560 */ 3561 GhostView mGhostView; 3562 3563 /** 3564 * Holds pairs of adjacent attribute data: attribute name followed by its value. 3565 * @hide 3566 */ 3567 @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true) 3568 public String[] mAttributes; 3569 3570 /** 3571 * Maps a Resource id to its name. 3572 */ 3573 private static SparseArray<String> mAttributeMap; 3574 3575 /** 3576 * Simple constructor to use when creating a view from code. 3577 * 3578 * @param context The Context the view is running in, through which it can 3579 * access the current theme, resources, etc. 3580 */ 3581 public View(Context context) { 3582 mContext = context; 3583 mResources = context != null ? context.getResources() : null; 3584 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED; 3585 // Set some flags defaults 3586 mPrivateFlags2 = 3587 (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) | 3588 (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) | 3589 (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) | 3590 (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) | 3591 (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) | 3592 (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT); 3593 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 3594 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 3595 mUserPaddingStart = UNDEFINED_PADDING; 3596 mUserPaddingEnd = UNDEFINED_PADDING; 3597 mRenderNode = RenderNode.create(getClass().getName(), this); 3598 3599 if (!sCompatibilityDone && context != null) { 3600 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3601 3602 // Older apps may need this compatibility hack for measurement. 3603 sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1; 3604 3605 // Older apps expect onMeasure() to always be called on a layout pass, regardless 3606 // of whether a layout was requested on that View. 3607 sIgnoreMeasureCache = targetSdkVersion < KITKAT; 3608 3609 sCompatibilityDone = true; 3610 } 3611 } 3612 3613 /** 3614 * Constructor that is called when inflating a view from XML. This is called 3615 * when a view is being constructed from an XML file, supplying attributes 3616 * that were specified in the XML file. This version uses a default style of 3617 * 0, so the only attribute values applied are those in the Context's Theme 3618 * and the given AttributeSet. 3619 * 3620 * <p> 3621 * The method onFinishInflate() will be called after all children have been 3622 * added. 3623 * 3624 * @param context The Context the view is running in, through which it can 3625 * access the current theme, resources, etc. 3626 * @param attrs The attributes of the XML tag that is inflating the view. 3627 * @see #View(Context, AttributeSet, int) 3628 */ 3629 public View(Context context, AttributeSet attrs) { 3630 this(context, attrs, 0); 3631 } 3632 3633 /** 3634 * Perform inflation from XML and apply a class-specific base style from a 3635 * theme attribute. This constructor of View allows subclasses to use their 3636 * own base style when they are inflating. For example, a Button class's 3637 * constructor would call this version of the super class constructor and 3638 * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this 3639 * allows the theme's button style to modify all of the base view attributes 3640 * (in particular its background) as well as the Button class's attributes. 3641 * 3642 * @param context The Context the view is running in, through which it can 3643 * access the current theme, resources, etc. 3644 * @param attrs The attributes of the XML tag that is inflating the view. 3645 * @param defStyleAttr An attribute in the current theme that contains a 3646 * reference to a style resource that supplies default values for 3647 * the view. Can be 0 to not look for defaults. 3648 * @see #View(Context, AttributeSet) 3649 */ 3650 public View(Context context, AttributeSet attrs, int defStyleAttr) { 3651 this(context, attrs, defStyleAttr, 0); 3652 } 3653 3654 /** 3655 * Perform inflation from XML and apply a class-specific base style from a 3656 * theme attribute or style resource. This constructor of View allows 3657 * subclasses to use their own base style when they are inflating. 3658 * <p> 3659 * When determining the final value of a particular attribute, there are 3660 * four inputs that come into play: 3661 * <ol> 3662 * <li>Any attribute values in the given AttributeSet. 3663 * <li>The style resource specified in the AttributeSet (named "style"). 3664 * <li>The default style specified by <var>defStyleAttr</var>. 3665 * <li>The default style specified by <var>defStyleRes</var>. 3666 * <li>The base values in this theme. 3667 * </ol> 3668 * <p> 3669 * Each of these inputs is considered in-order, with the first listed taking 3670 * precedence over the following ones. In other words, if in the 3671 * AttributeSet you have supplied <code><Button * textColor="#ff000000"></code> 3672 * , then the button's text will <em>always</em> be black, regardless of 3673 * what is specified in any of the styles. 3674 * 3675 * @param context The Context the view is running in, through which it can 3676 * access the current theme, resources, etc. 3677 * @param attrs The attributes of the XML tag that is inflating the view. 3678 * @param defStyleAttr An attribute in the current theme that contains a 3679 * reference to a style resource that supplies default values for 3680 * the view. Can be 0 to not look for defaults. 3681 * @param defStyleRes A resource identifier of a style resource that 3682 * supplies default values for the view, used only if 3683 * defStyleAttr is 0 or can not be found in the theme. Can be 0 3684 * to not look for defaults. 3685 * @see #View(Context, AttributeSet, int) 3686 */ 3687 public View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { 3688 this(context); 3689 3690 final TypedArray a = context.obtainStyledAttributes( 3691 attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes); 3692 3693 if (mDebugViewAttributes) { 3694 saveAttributeData(attrs, a); 3695 } 3696 3697 Drawable background = null; 3698 3699 int leftPadding = -1; 3700 int topPadding = -1; 3701 int rightPadding = -1; 3702 int bottomPadding = -1; 3703 int startPadding = UNDEFINED_PADDING; 3704 int endPadding = UNDEFINED_PADDING; 3705 3706 int padding = -1; 3707 3708 int viewFlagValues = 0; 3709 int viewFlagMasks = 0; 3710 3711 boolean setScrollContainer = false; 3712 3713 int x = 0; 3714 int y = 0; 3715 3716 float tx = 0; 3717 float ty = 0; 3718 float tz = 0; 3719 float elevation = 0; 3720 float rotation = 0; 3721 float rotationX = 0; 3722 float rotationY = 0; 3723 float sx = 1f; 3724 float sy = 1f; 3725 boolean transformSet = false; 3726 3727 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 3728 int overScrollMode = mOverScrollMode; 3729 boolean initializeScrollbars = false; 3730 3731 boolean startPaddingDefined = false; 3732 boolean endPaddingDefined = false; 3733 boolean leftPaddingDefined = false; 3734 boolean rightPaddingDefined = false; 3735 3736 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3737 3738 final int N = a.getIndexCount(); 3739 for (int i = 0; i < N; i++) { 3740 int attr = a.getIndex(i); 3741 switch (attr) { 3742 case com.android.internal.R.styleable.View_background: 3743 background = a.getDrawable(attr); 3744 break; 3745 case com.android.internal.R.styleable.View_padding: 3746 padding = a.getDimensionPixelSize(attr, -1); 3747 mUserPaddingLeftInitial = padding; 3748 mUserPaddingRightInitial = padding; 3749 leftPaddingDefined = true; 3750 rightPaddingDefined = true; 3751 break; 3752 case com.android.internal.R.styleable.View_paddingLeft: 3753 leftPadding = a.getDimensionPixelSize(attr, -1); 3754 mUserPaddingLeftInitial = leftPadding; 3755 leftPaddingDefined = true; 3756 break; 3757 case com.android.internal.R.styleable.View_paddingTop: 3758 topPadding = a.getDimensionPixelSize(attr, -1); 3759 break; 3760 case com.android.internal.R.styleable.View_paddingRight: 3761 rightPadding = a.getDimensionPixelSize(attr, -1); 3762 mUserPaddingRightInitial = rightPadding; 3763 rightPaddingDefined = true; 3764 break; 3765 case com.android.internal.R.styleable.View_paddingBottom: 3766 bottomPadding = a.getDimensionPixelSize(attr, -1); 3767 break; 3768 case com.android.internal.R.styleable.View_paddingStart: 3769 startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3770 startPaddingDefined = (startPadding != UNDEFINED_PADDING); 3771 break; 3772 case com.android.internal.R.styleable.View_paddingEnd: 3773 endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3774 endPaddingDefined = (endPadding != UNDEFINED_PADDING); 3775 break; 3776 case com.android.internal.R.styleable.View_scrollX: 3777 x = a.getDimensionPixelOffset(attr, 0); 3778 break; 3779 case com.android.internal.R.styleable.View_scrollY: 3780 y = a.getDimensionPixelOffset(attr, 0); 3781 break; 3782 case com.android.internal.R.styleable.View_alpha: 3783 setAlpha(a.getFloat(attr, 1f)); 3784 break; 3785 case com.android.internal.R.styleable.View_transformPivotX: 3786 setPivotX(a.getDimensionPixelOffset(attr, 0)); 3787 break; 3788 case com.android.internal.R.styleable.View_transformPivotY: 3789 setPivotY(a.getDimensionPixelOffset(attr, 0)); 3790 break; 3791 case com.android.internal.R.styleable.View_translationX: 3792 tx = a.getDimensionPixelOffset(attr, 0); 3793 transformSet = true; 3794 break; 3795 case com.android.internal.R.styleable.View_translationY: 3796 ty = a.getDimensionPixelOffset(attr, 0); 3797 transformSet = true; 3798 break; 3799 case com.android.internal.R.styleable.View_translationZ: 3800 tz = a.getDimensionPixelOffset(attr, 0); 3801 transformSet = true; 3802 break; 3803 case com.android.internal.R.styleable.View_elevation: 3804 elevation = a.getDimensionPixelOffset(attr, 0); 3805 transformSet = true; 3806 break; 3807 case com.android.internal.R.styleable.View_rotation: 3808 rotation = a.getFloat(attr, 0); 3809 transformSet = true; 3810 break; 3811 case com.android.internal.R.styleable.View_rotationX: 3812 rotationX = a.getFloat(attr, 0); 3813 transformSet = true; 3814 break; 3815 case com.android.internal.R.styleable.View_rotationY: 3816 rotationY = a.getFloat(attr, 0); 3817 transformSet = true; 3818 break; 3819 case com.android.internal.R.styleable.View_scaleX: 3820 sx = a.getFloat(attr, 1f); 3821 transformSet = true; 3822 break; 3823 case com.android.internal.R.styleable.View_scaleY: 3824 sy = a.getFloat(attr, 1f); 3825 transformSet = true; 3826 break; 3827 case com.android.internal.R.styleable.View_id: 3828 mID = a.getResourceId(attr, NO_ID); 3829 break; 3830 case com.android.internal.R.styleable.View_tag: 3831 mTag = a.getText(attr); 3832 break; 3833 case com.android.internal.R.styleable.View_fitsSystemWindows: 3834 if (a.getBoolean(attr, false)) { 3835 viewFlagValues |= FITS_SYSTEM_WINDOWS; 3836 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 3837 } 3838 break; 3839 case com.android.internal.R.styleable.View_focusable: 3840 if (a.getBoolean(attr, false)) { 3841 viewFlagValues |= FOCUSABLE; 3842 viewFlagMasks |= FOCUSABLE_MASK; 3843 } 3844 break; 3845 case com.android.internal.R.styleable.View_focusableInTouchMode: 3846 if (a.getBoolean(attr, false)) { 3847 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 3848 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 3849 } 3850 break; 3851 case com.android.internal.R.styleable.View_clickable: 3852 if (a.getBoolean(attr, false)) { 3853 viewFlagValues |= CLICKABLE; 3854 viewFlagMasks |= CLICKABLE; 3855 } 3856 break; 3857 case com.android.internal.R.styleable.View_longClickable: 3858 if (a.getBoolean(attr, false)) { 3859 viewFlagValues |= LONG_CLICKABLE; 3860 viewFlagMasks |= LONG_CLICKABLE; 3861 } 3862 break; 3863 case com.android.internal.R.styleable.View_saveEnabled: 3864 if (!a.getBoolean(attr, true)) { 3865 viewFlagValues |= SAVE_DISABLED; 3866 viewFlagMasks |= SAVE_DISABLED_MASK; 3867 } 3868 break; 3869 case com.android.internal.R.styleable.View_duplicateParentState: 3870 if (a.getBoolean(attr, false)) { 3871 viewFlagValues |= DUPLICATE_PARENT_STATE; 3872 viewFlagMasks |= DUPLICATE_PARENT_STATE; 3873 } 3874 break; 3875 case com.android.internal.R.styleable.View_visibility: 3876 final int visibility = a.getInt(attr, 0); 3877 if (visibility != 0) { 3878 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 3879 viewFlagMasks |= VISIBILITY_MASK; 3880 } 3881 break; 3882 case com.android.internal.R.styleable.View_layoutDirection: 3883 // Clear any layout direction flags (included resolved bits) already set 3884 mPrivateFlags2 &= 3885 ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK); 3886 // Set the layout direction flags depending on the value of the attribute 3887 final int layoutDirection = a.getInt(attr, -1); 3888 final int value = (layoutDirection != -1) ? 3889 LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT; 3890 mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT); 3891 break; 3892 case com.android.internal.R.styleable.View_drawingCacheQuality: 3893 final int cacheQuality = a.getInt(attr, 0); 3894 if (cacheQuality != 0) { 3895 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 3896 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 3897 } 3898 break; 3899 case com.android.internal.R.styleable.View_contentDescription: 3900 setContentDescription(a.getString(attr)); 3901 break; 3902 case com.android.internal.R.styleable.View_accessibilityTraversalBefore: 3903 setAccessibilityTraversalBefore(a.getResourceId(attr, NO_ID)); 3904 break; 3905 case com.android.internal.R.styleable.View_accessibilityTraversalAfter: 3906 setAccessibilityTraversalAfter(a.getResourceId(attr, NO_ID)); 3907 break; 3908 case com.android.internal.R.styleable.View_labelFor: 3909 setLabelFor(a.getResourceId(attr, NO_ID)); 3910 break; 3911 case com.android.internal.R.styleable.View_soundEffectsEnabled: 3912 if (!a.getBoolean(attr, true)) { 3913 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 3914 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 3915 } 3916 break; 3917 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 3918 if (!a.getBoolean(attr, true)) { 3919 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 3920 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 3921 } 3922 break; 3923 case R.styleable.View_scrollbars: 3924 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 3925 if (scrollbars != SCROLLBARS_NONE) { 3926 viewFlagValues |= scrollbars; 3927 viewFlagMasks |= SCROLLBARS_MASK; 3928 initializeScrollbars = true; 3929 } 3930 break; 3931 //noinspection deprecation 3932 case R.styleable.View_fadingEdge: 3933 if (targetSdkVersion >= ICE_CREAM_SANDWICH) { 3934 // Ignore the attribute starting with ICS 3935 break; 3936 } 3937 // With builds < ICS, fall through and apply fading edges 3938 case R.styleable.View_requiresFadingEdge: 3939 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 3940 if (fadingEdge != FADING_EDGE_NONE) { 3941 viewFlagValues |= fadingEdge; 3942 viewFlagMasks |= FADING_EDGE_MASK; 3943 initializeFadingEdgeInternal(a); 3944 } 3945 break; 3946 case R.styleable.View_scrollbarStyle: 3947 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 3948 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3949 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 3950 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 3951 } 3952 break; 3953 case R.styleable.View_isScrollContainer: 3954 setScrollContainer = true; 3955 if (a.getBoolean(attr, false)) { 3956 setScrollContainer(true); 3957 } 3958 break; 3959 case com.android.internal.R.styleable.View_keepScreenOn: 3960 if (a.getBoolean(attr, false)) { 3961 viewFlagValues |= KEEP_SCREEN_ON; 3962 viewFlagMasks |= KEEP_SCREEN_ON; 3963 } 3964 break; 3965 case R.styleable.View_filterTouchesWhenObscured: 3966 if (a.getBoolean(attr, false)) { 3967 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 3968 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 3969 } 3970 break; 3971 case R.styleable.View_nextFocusLeft: 3972 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 3973 break; 3974 case R.styleable.View_nextFocusRight: 3975 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 3976 break; 3977 case R.styleable.View_nextFocusUp: 3978 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 3979 break; 3980 case R.styleable.View_nextFocusDown: 3981 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 3982 break; 3983 case R.styleable.View_nextFocusForward: 3984 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 3985 break; 3986 case R.styleable.View_minWidth: 3987 mMinWidth = a.getDimensionPixelSize(attr, 0); 3988 break; 3989 case R.styleable.View_minHeight: 3990 mMinHeight = a.getDimensionPixelSize(attr, 0); 3991 break; 3992 case R.styleable.View_onClick: 3993 if (context.isRestricted()) { 3994 throw new IllegalStateException("The android:onClick attribute cannot " 3995 + "be used within a restricted context"); 3996 } 3997 3998 final String handlerName = a.getString(attr); 3999 if (handlerName != null) { 4000 setOnClickListener(new OnClickListener() { 4001 private Method mHandler; 4002 4003 public void onClick(View v) { 4004 if (mHandler == null) { 4005 try { 4006 mHandler = getContext().getClass().getMethod(handlerName, 4007 View.class); 4008 } catch (NoSuchMethodException e) { 4009 int id = getId(); 4010 String idText = id == NO_ID ? "" : " with id '" 4011 + getContext().getResources().getResourceEntryName( 4012 id) + "'"; 4013 throw new IllegalStateException("Could not find a method " + 4014 handlerName + "(View) in the activity " 4015 + getContext().getClass() + " for onClick handler" 4016 + " on view " + View.this.getClass() + idText, e); 4017 } 4018 } 4019 4020 try { 4021 mHandler.invoke(getContext(), View.this); 4022 } catch (IllegalAccessException e) { 4023 throw new IllegalStateException("Could not execute non " 4024 + "public method of the activity", e); 4025 } catch (InvocationTargetException e) { 4026 throw new IllegalStateException("Could not execute " 4027 + "method of the activity", e); 4028 } 4029 } 4030 }); 4031 } 4032 break; 4033 case R.styleable.View_overScrollMode: 4034 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 4035 break; 4036 case R.styleable.View_verticalScrollbarPosition: 4037 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 4038 break; 4039 case R.styleable.View_layerType: 4040 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 4041 break; 4042 case R.styleable.View_textDirection: 4043 // Clear any text direction flag already set 4044 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 4045 // Set the text direction flags depending on the value of the attribute 4046 final int textDirection = a.getInt(attr, -1); 4047 if (textDirection != -1) { 4048 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection]; 4049 } 4050 break; 4051 case R.styleable.View_textAlignment: 4052 // Clear any text alignment flag already set 4053 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 4054 // Set the text alignment flag depending on the value of the attribute 4055 final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT); 4056 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment]; 4057 break; 4058 case R.styleable.View_importantForAccessibility: 4059 setImportantForAccessibility(a.getInt(attr, 4060 IMPORTANT_FOR_ACCESSIBILITY_DEFAULT)); 4061 break; 4062 case R.styleable.View_accessibilityLiveRegion: 4063 setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT)); 4064 break; 4065 case R.styleable.View_transitionName: 4066 setTransitionName(a.getString(attr)); 4067 break; 4068 case R.styleable.View_nestedScrollingEnabled: 4069 setNestedScrollingEnabled(a.getBoolean(attr, false)); 4070 break; 4071 case R.styleable.View_stateListAnimator: 4072 setStateListAnimator(AnimatorInflater.loadStateListAnimator(context, 4073 a.getResourceId(attr, 0))); 4074 break; 4075 case R.styleable.View_backgroundTint: 4076 // This will get applied later during setBackground(). 4077 if (mBackgroundTint == null) { 4078 mBackgroundTint = new TintInfo(); 4079 } 4080 mBackgroundTint.mTintList = a.getColorStateList( 4081 R.styleable.View_backgroundTint); 4082 mBackgroundTint.mHasTintList = true; 4083 break; 4084 case R.styleable.View_backgroundTintMode: 4085 // This will get applied later during setBackground(). 4086 if (mBackgroundTint == null) { 4087 mBackgroundTint = new TintInfo(); 4088 } 4089 mBackgroundTint.mTintMode = Drawable.parseTintMode(a.getInt( 4090 R.styleable.View_backgroundTintMode, -1), null); 4091 mBackgroundTint.mHasTintMode = true; 4092 break; 4093 case R.styleable.View_outlineProvider: 4094 setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider, 4095 PROVIDER_BACKGROUND)); 4096 break; 4097 } 4098 } 4099 4100 setOverScrollMode(overScrollMode); 4101 4102 // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet 4103 // the resolved layout direction). Those cached values will be used later during padding 4104 // resolution. 4105 mUserPaddingStart = startPadding; 4106 mUserPaddingEnd = endPadding; 4107 4108 if (background != null) { 4109 setBackground(background); 4110 } 4111 4112 // setBackground above will record that padding is currently provided by the background. 4113 // If we have padding specified via xml, record that here instead and use it. 4114 mLeftPaddingDefined = leftPaddingDefined; 4115 mRightPaddingDefined = rightPaddingDefined; 4116 4117 if (padding >= 0) { 4118 leftPadding = padding; 4119 topPadding = padding; 4120 rightPadding = padding; 4121 bottomPadding = padding; 4122 mUserPaddingLeftInitial = padding; 4123 mUserPaddingRightInitial = padding; 4124 } 4125 4126 if (isRtlCompatibilityMode()) { 4127 // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case. 4128 // left / right padding are used if defined (meaning here nothing to do). If they are not 4129 // defined and start / end padding are defined (e.g. in Frameworks resources), then we use 4130 // start / end and resolve them as left / right (layout direction is not taken into account). 4131 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4132 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4133 // defined. 4134 if (!mLeftPaddingDefined && startPaddingDefined) { 4135 leftPadding = startPadding; 4136 } 4137 mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial; 4138 if (!mRightPaddingDefined && endPaddingDefined) { 4139 rightPadding = endPadding; 4140 } 4141 mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial; 4142 } else { 4143 // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right 4144 // values defined. Otherwise, left /right values are used. 4145 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4146 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4147 // defined. 4148 final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined; 4149 4150 if (mLeftPaddingDefined && !hasRelativePadding) { 4151 mUserPaddingLeftInitial = leftPadding; 4152 } 4153 if (mRightPaddingDefined && !hasRelativePadding) { 4154 mUserPaddingRightInitial = rightPadding; 4155 } 4156 } 4157 4158 internalSetPadding( 4159 mUserPaddingLeftInitial, 4160 topPadding >= 0 ? topPadding : mPaddingTop, 4161 mUserPaddingRightInitial, 4162 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 4163 4164 if (viewFlagMasks != 0) { 4165 setFlags(viewFlagValues, viewFlagMasks); 4166 } 4167 4168 if (initializeScrollbars) { 4169 initializeScrollbarsInternal(a); 4170 } 4171 4172 a.recycle(); 4173 4174 // Needs to be called after mViewFlags is set 4175 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 4176 recomputePadding(); 4177 } 4178 4179 if (x != 0 || y != 0) { 4180 scrollTo(x, y); 4181 } 4182 4183 if (transformSet) { 4184 setTranslationX(tx); 4185 setTranslationY(ty); 4186 setTranslationZ(tz); 4187 setElevation(elevation); 4188 setRotation(rotation); 4189 setRotationX(rotationX); 4190 setRotationY(rotationY); 4191 setScaleX(sx); 4192 setScaleY(sy); 4193 } 4194 4195 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 4196 setScrollContainer(true); 4197 } 4198 4199 computeOpaqueFlags(); 4200 } 4201 4202 /** 4203 * Non-public constructor for use in testing 4204 */ 4205 View() { 4206 mResources = null; 4207 mRenderNode = RenderNode.create(getClass().getName(), this); 4208 } 4209 4210 private static SparseArray<String> getAttributeMap() { 4211 if (mAttributeMap == null) { 4212 mAttributeMap = new SparseArray<String>(); 4213 } 4214 return mAttributeMap; 4215 } 4216 4217 private void saveAttributeData(AttributeSet attrs, TypedArray a) { 4218 int length = ((attrs == null ? 0 : attrs.getAttributeCount()) + a.getIndexCount()) * 2; 4219 mAttributes = new String[length]; 4220 4221 int i = 0; 4222 if (attrs != null) { 4223 for (i = 0; i < attrs.getAttributeCount(); i += 2) { 4224 mAttributes[i] = attrs.getAttributeName(i); 4225 mAttributes[i + 1] = attrs.getAttributeValue(i); 4226 } 4227 4228 } 4229 4230 SparseArray<String> attributeMap = getAttributeMap(); 4231 for (int j = 0; j < a.length(); ++j) { 4232 if (a.hasValue(j)) { 4233 try { 4234 int resourceId = a.getResourceId(j, 0); 4235 if (resourceId == 0) { 4236 continue; 4237 } 4238 4239 String resourceName = attributeMap.get(resourceId); 4240 if (resourceName == null) { 4241 resourceName = a.getResources().getResourceName(resourceId); 4242 attributeMap.put(resourceId, resourceName); 4243 } 4244 4245 mAttributes[i] = resourceName; 4246 mAttributes[i + 1] = a.getText(j).toString(); 4247 i += 2; 4248 } catch (Resources.NotFoundException e) { 4249 // if we can't get the resource name, we just ignore it 4250 } 4251 } 4252 } 4253 } 4254 4255 public String toString() { 4256 StringBuilder out = new StringBuilder(128); 4257 out.append(getClass().getName()); 4258 out.append('{'); 4259 out.append(Integer.toHexString(System.identityHashCode(this))); 4260 out.append(' '); 4261 switch (mViewFlags&VISIBILITY_MASK) { 4262 case VISIBLE: out.append('V'); break; 4263 case INVISIBLE: out.append('I'); break; 4264 case GONE: out.append('G'); break; 4265 default: out.append('.'); break; 4266 } 4267 out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.'); 4268 out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.'); 4269 out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D'); 4270 out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.'); 4271 out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.'); 4272 out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.'); 4273 out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.'); 4274 out.append(' '); 4275 out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.'); 4276 out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.'); 4277 out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.'); 4278 if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) { 4279 out.append('p'); 4280 } else { 4281 out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.'); 4282 } 4283 out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.'); 4284 out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.'); 4285 out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.'); 4286 out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.'); 4287 out.append(' '); 4288 out.append(mLeft); 4289 out.append(','); 4290 out.append(mTop); 4291 out.append('-'); 4292 out.append(mRight); 4293 out.append(','); 4294 out.append(mBottom); 4295 final int id = getId(); 4296 if (id != NO_ID) { 4297 out.append(" #"); 4298 out.append(Integer.toHexString(id)); 4299 final Resources r = mResources; 4300 if (Resources.resourceHasPackage(id) && r != null) { 4301 try { 4302 String pkgname; 4303 switch (id&0xff000000) { 4304 case 0x7f000000: 4305 pkgname="app"; 4306 break; 4307 case 0x01000000: 4308 pkgname="android"; 4309 break; 4310 default: 4311 pkgname = r.getResourcePackageName(id); 4312 break; 4313 } 4314 String typename = r.getResourceTypeName(id); 4315 String entryname = r.getResourceEntryName(id); 4316 out.append(" "); 4317 out.append(pkgname); 4318 out.append(":"); 4319 out.append(typename); 4320 out.append("/"); 4321 out.append(entryname); 4322 } catch (Resources.NotFoundException e) { 4323 } 4324 } 4325 } 4326 out.append("}"); 4327 return out.toString(); 4328 } 4329 4330 /** 4331 * <p> 4332 * Initializes the fading edges from a given set of styled attributes. This 4333 * method should be called by subclasses that need fading edges and when an 4334 * instance of these subclasses is created programmatically rather than 4335 * being inflated from XML. This method is automatically called when the XML 4336 * is inflated. 4337 * </p> 4338 * 4339 * @param a the styled attributes set to initialize the fading edges from 4340 * 4341 * @removed 4342 */ 4343 protected void initializeFadingEdge(TypedArray a) { 4344 // This method probably shouldn't have been included in the SDK to begin with. 4345 // It relies on 'a' having been initialized using an attribute filter array that is 4346 // not publicly available to the SDK. The old method has been renamed 4347 // to initializeFadingEdgeInternal and hidden for framework use only; 4348 // this one initializes using defaults to make it safe to call for apps. 4349 4350 TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View); 4351 4352 initializeFadingEdgeInternal(arr); 4353 4354 arr.recycle(); 4355 } 4356 4357 /** 4358 * <p> 4359 * Initializes the fading edges from a given set of styled attributes. This 4360 * method should be called by subclasses that need fading edges and when an 4361 * instance of these subclasses is created programmatically rather than 4362 * being inflated from XML. This method is automatically called when the XML 4363 * is inflated. 4364 * </p> 4365 * 4366 * @param a the styled attributes set to initialize the fading edges from 4367 * @hide This is the real method; the public one is shimmed to be safe to call from apps. 4368 */ 4369 protected void initializeFadingEdgeInternal(TypedArray a) { 4370 initScrollCache(); 4371 4372 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 4373 R.styleable.View_fadingEdgeLength, 4374 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 4375 } 4376 4377 /** 4378 * Returns the size of the vertical faded edges used to indicate that more 4379 * content in this view is visible. 4380 * 4381 * @return The size in pixels of the vertical faded edge or 0 if vertical 4382 * faded edges are not enabled for this view. 4383 * @attr ref android.R.styleable#View_fadingEdgeLength 4384 */ 4385 public int getVerticalFadingEdgeLength() { 4386 if (isVerticalFadingEdgeEnabled()) { 4387 ScrollabilityCache cache = mScrollCache; 4388 if (cache != null) { 4389 return cache.fadingEdgeLength; 4390 } 4391 } 4392 return 0; 4393 } 4394 4395 /** 4396 * Set the size of the faded edge used to indicate that more content in this 4397 * view is available. Will not change whether the fading edge is enabled; use 4398 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 4399 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 4400 * for the vertical or horizontal fading edges. 4401 * 4402 * @param length The size in pixels of the faded edge used to indicate that more 4403 * content in this view is visible. 4404 */ 4405 public void setFadingEdgeLength(int length) { 4406 initScrollCache(); 4407 mScrollCache.fadingEdgeLength = length; 4408 } 4409 4410 /** 4411 * Returns the size of the horizontal faded edges used to indicate that more 4412 * content in this view is visible. 4413 * 4414 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 4415 * faded edges are not enabled for this view. 4416 * @attr ref android.R.styleable#View_fadingEdgeLength 4417 */ 4418 public int getHorizontalFadingEdgeLength() { 4419 if (isHorizontalFadingEdgeEnabled()) { 4420 ScrollabilityCache cache = mScrollCache; 4421 if (cache != null) { 4422 return cache.fadingEdgeLength; 4423 } 4424 } 4425 return 0; 4426 } 4427 4428 /** 4429 * Returns the width of the vertical scrollbar. 4430 * 4431 * @return The width in pixels of the vertical scrollbar or 0 if there 4432 * is no vertical scrollbar. 4433 */ 4434 public int getVerticalScrollbarWidth() { 4435 ScrollabilityCache cache = mScrollCache; 4436 if (cache != null) { 4437 ScrollBarDrawable scrollBar = cache.scrollBar; 4438 if (scrollBar != null) { 4439 int size = scrollBar.getSize(true); 4440 if (size <= 0) { 4441 size = cache.scrollBarSize; 4442 } 4443 return size; 4444 } 4445 return 0; 4446 } 4447 return 0; 4448 } 4449 4450 /** 4451 * Returns the height of the horizontal scrollbar. 4452 * 4453 * @return The height in pixels of the horizontal scrollbar or 0 if 4454 * there is no horizontal scrollbar. 4455 */ 4456 protected int getHorizontalScrollbarHeight() { 4457 ScrollabilityCache cache = mScrollCache; 4458 if (cache != null) { 4459 ScrollBarDrawable scrollBar = cache.scrollBar; 4460 if (scrollBar != null) { 4461 int size = scrollBar.getSize(false); 4462 if (size <= 0) { 4463 size = cache.scrollBarSize; 4464 } 4465 return size; 4466 } 4467 return 0; 4468 } 4469 return 0; 4470 } 4471 4472 /** 4473 * <p> 4474 * Initializes the scrollbars from a given set of styled attributes. This 4475 * method should be called by subclasses that need scrollbars and when an 4476 * instance of these subclasses is created programmatically rather than 4477 * being inflated from XML. This method is automatically called when the XML 4478 * is inflated. 4479 * </p> 4480 * 4481 * @param a the styled attributes set to initialize the scrollbars from 4482 * 4483 * @removed 4484 */ 4485 protected void initializeScrollbars(TypedArray a) { 4486 // It's not safe to use this method from apps. The parameter 'a' must have been obtained 4487 // using the View filter array which is not available to the SDK. As such, internal 4488 // framework usage now uses initializeScrollbarsInternal and we grab a default 4489 // TypedArray with the right filter instead here. 4490 TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View); 4491 4492 initializeScrollbarsInternal(arr); 4493 4494 // We ignored the method parameter. Recycle the one we actually did use. 4495 arr.recycle(); 4496 } 4497 4498 /** 4499 * <p> 4500 * Initializes the scrollbars from a given set of styled attributes. This 4501 * method should be called by subclasses that need scrollbars and when an 4502 * instance of these subclasses is created programmatically rather than 4503 * being inflated from XML. This method is automatically called when the XML 4504 * is inflated. 4505 * </p> 4506 * 4507 * @param a the styled attributes set to initialize the scrollbars from 4508 * @hide 4509 */ 4510 protected void initializeScrollbarsInternal(TypedArray a) { 4511 initScrollCache(); 4512 4513 final ScrollabilityCache scrollabilityCache = mScrollCache; 4514 4515 if (scrollabilityCache.scrollBar == null) { 4516 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 4517 } 4518 4519 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 4520 4521 if (!fadeScrollbars) { 4522 scrollabilityCache.state = ScrollabilityCache.ON; 4523 } 4524 scrollabilityCache.fadeScrollBars = fadeScrollbars; 4525 4526 4527 scrollabilityCache.scrollBarFadeDuration = a.getInt( 4528 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 4529 .getScrollBarFadeDuration()); 4530 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 4531 R.styleable.View_scrollbarDefaultDelayBeforeFade, 4532 ViewConfiguration.getScrollDefaultDelay()); 4533 4534 4535 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 4536 com.android.internal.R.styleable.View_scrollbarSize, 4537 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 4538 4539 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 4540 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 4541 4542 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 4543 if (thumb != null) { 4544 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 4545 } 4546 4547 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 4548 false); 4549 if (alwaysDraw) { 4550 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 4551 } 4552 4553 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 4554 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 4555 4556 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 4557 if (thumb != null) { 4558 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 4559 } 4560 4561 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 4562 false); 4563 if (alwaysDraw) { 4564 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 4565 } 4566 4567 // Apply layout direction to the new Drawables if needed 4568 final int layoutDirection = getLayoutDirection(); 4569 if (track != null) { 4570 track.setLayoutDirection(layoutDirection); 4571 } 4572 if (thumb != null) { 4573 thumb.setLayoutDirection(layoutDirection); 4574 } 4575 4576 // Re-apply user/background padding so that scrollbar(s) get added 4577 resolvePadding(); 4578 } 4579 4580 /** 4581 * <p> 4582 * Initalizes the scrollability cache if necessary. 4583 * </p> 4584 */ 4585 private void initScrollCache() { 4586 if (mScrollCache == null) { 4587 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 4588 } 4589 } 4590 4591 private ScrollabilityCache getScrollCache() { 4592 initScrollCache(); 4593 return mScrollCache; 4594 } 4595 4596 /** 4597 * Set the position of the vertical scroll bar. Should be one of 4598 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 4599 * {@link #SCROLLBAR_POSITION_RIGHT}. 4600 * 4601 * @param position Where the vertical scroll bar should be positioned. 4602 */ 4603 public void setVerticalScrollbarPosition(int position) { 4604 if (mVerticalScrollbarPosition != position) { 4605 mVerticalScrollbarPosition = position; 4606 computeOpaqueFlags(); 4607 resolvePadding(); 4608 } 4609 } 4610 4611 /** 4612 * @return The position where the vertical scroll bar will show, if applicable. 4613 * @see #setVerticalScrollbarPosition(int) 4614 */ 4615 public int getVerticalScrollbarPosition() { 4616 return mVerticalScrollbarPosition; 4617 } 4618 4619 ListenerInfo getListenerInfo() { 4620 if (mListenerInfo != null) { 4621 return mListenerInfo; 4622 } 4623 mListenerInfo = new ListenerInfo(); 4624 return mListenerInfo; 4625 } 4626 4627 /** 4628 * Register a callback to be invoked when the scroll position of this view 4629 * changed. 4630 * 4631 * @param l The callback that will run. 4632 * @hide Only used internally. 4633 */ 4634 public void setOnScrollChangeListener(OnScrollChangeListener l) { 4635 getListenerInfo().mOnScrollChangeListener = l; 4636 } 4637 4638 /** 4639 * Register a callback to be invoked when focus of this view changed. 4640 * 4641 * @param l The callback that will run. 4642 */ 4643 public void setOnFocusChangeListener(OnFocusChangeListener l) { 4644 getListenerInfo().mOnFocusChangeListener = l; 4645 } 4646 4647 /** 4648 * Add a listener that will be called when the bounds of the view change due to 4649 * layout processing. 4650 * 4651 * @param listener The listener that will be called when layout bounds change. 4652 */ 4653 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 4654 ListenerInfo li = getListenerInfo(); 4655 if (li.mOnLayoutChangeListeners == null) { 4656 li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 4657 } 4658 if (!li.mOnLayoutChangeListeners.contains(listener)) { 4659 li.mOnLayoutChangeListeners.add(listener); 4660 } 4661 } 4662 4663 /** 4664 * Remove a listener for layout changes. 4665 * 4666 * @param listener The listener for layout bounds change. 4667 */ 4668 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 4669 ListenerInfo li = mListenerInfo; 4670 if (li == null || li.mOnLayoutChangeListeners == null) { 4671 return; 4672 } 4673 li.mOnLayoutChangeListeners.remove(listener); 4674 } 4675 4676 /** 4677 * Add a listener for attach state changes. 4678 * 4679 * This listener will be called whenever this view is attached or detached 4680 * from a window. Remove the listener using 4681 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 4682 * 4683 * @param listener Listener to attach 4684 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 4685 */ 4686 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4687 ListenerInfo li = getListenerInfo(); 4688 if (li.mOnAttachStateChangeListeners == null) { 4689 li.mOnAttachStateChangeListeners 4690 = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 4691 } 4692 li.mOnAttachStateChangeListeners.add(listener); 4693 } 4694 4695 /** 4696 * Remove a listener for attach state changes. The listener will receive no further 4697 * notification of window attach/detach events. 4698 * 4699 * @param listener Listener to remove 4700 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 4701 */ 4702 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4703 ListenerInfo li = mListenerInfo; 4704 if (li == null || li.mOnAttachStateChangeListeners == null) { 4705 return; 4706 } 4707 li.mOnAttachStateChangeListeners.remove(listener); 4708 } 4709 4710 /** 4711 * Returns the focus-change callback registered for this view. 4712 * 4713 * @return The callback, or null if one is not registered. 4714 */ 4715 public OnFocusChangeListener getOnFocusChangeListener() { 4716 ListenerInfo li = mListenerInfo; 4717 return li != null ? li.mOnFocusChangeListener : null; 4718 } 4719 4720 /** 4721 * Register a callback to be invoked when this view is clicked. If this view is not 4722 * clickable, it becomes clickable. 4723 * 4724 * @param l The callback that will run 4725 * 4726 * @see #setClickable(boolean) 4727 */ 4728 public void setOnClickListener(OnClickListener l) { 4729 if (!isClickable()) { 4730 setClickable(true); 4731 } 4732 getListenerInfo().mOnClickListener = l; 4733 } 4734 4735 /** 4736 * Return whether this view has an attached OnClickListener. Returns 4737 * true if there is a listener, false if there is none. 4738 */ 4739 public boolean hasOnClickListeners() { 4740 ListenerInfo li = mListenerInfo; 4741 return (li != null && li.mOnClickListener != null); 4742 } 4743 4744 /** 4745 * Register a callback to be invoked when this view is clicked and held. If this view is not 4746 * long clickable, it becomes long clickable. 4747 * 4748 * @param l The callback that will run 4749 * 4750 * @see #setLongClickable(boolean) 4751 */ 4752 public void setOnLongClickListener(OnLongClickListener l) { 4753 if (!isLongClickable()) { 4754 setLongClickable(true); 4755 } 4756 getListenerInfo().mOnLongClickListener = l; 4757 } 4758 4759 /** 4760 * Register a callback to be invoked when the context menu for this view is 4761 * being built. If this view is not long clickable, it becomes long clickable. 4762 * 4763 * @param l The callback that will run 4764 * 4765 */ 4766 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 4767 if (!isLongClickable()) { 4768 setLongClickable(true); 4769 } 4770 getListenerInfo().mOnCreateContextMenuListener = l; 4771 } 4772 4773 /** 4774 * Call this view's OnClickListener, if it is defined. Performs all normal 4775 * actions associated with clicking: reporting accessibility event, playing 4776 * a sound, etc. 4777 * 4778 * @return True there was an assigned OnClickListener that was called, false 4779 * otherwise is returned. 4780 */ 4781 public boolean performClick() { 4782 final boolean result; 4783 final ListenerInfo li = mListenerInfo; 4784 if (li != null && li.mOnClickListener != null) { 4785 playSoundEffect(SoundEffectConstants.CLICK); 4786 li.mOnClickListener.onClick(this); 4787 result = true; 4788 } else { 4789 result = false; 4790 } 4791 4792 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 4793 return result; 4794 } 4795 4796 /** 4797 * Directly call any attached OnClickListener. Unlike {@link #performClick()}, 4798 * this only calls the listener, and does not do any associated clicking 4799 * actions like reporting an accessibility event. 4800 * 4801 * @return True there was an assigned OnClickListener that was called, false 4802 * otherwise is returned. 4803 */ 4804 public boolean callOnClick() { 4805 ListenerInfo li = mListenerInfo; 4806 if (li != null && li.mOnClickListener != null) { 4807 li.mOnClickListener.onClick(this); 4808 return true; 4809 } 4810 return false; 4811 } 4812 4813 /** 4814 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the 4815 * OnLongClickListener did not consume the event. 4816 * 4817 * @return True if one of the above receivers consumed the event, false otherwise. 4818 */ 4819 public boolean performLongClick() { 4820 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 4821 4822 boolean handled = false; 4823 ListenerInfo li = mListenerInfo; 4824 if (li != null && li.mOnLongClickListener != null) { 4825 handled = li.mOnLongClickListener.onLongClick(View.this); 4826 } 4827 if (!handled) { 4828 handled = showContextMenu(); 4829 } 4830 if (handled) { 4831 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 4832 } 4833 return handled; 4834 } 4835 4836 /** 4837 * Performs button-related actions during a touch down event. 4838 * 4839 * @param event The event. 4840 * @return True if the down was consumed. 4841 * 4842 * @hide 4843 */ 4844 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 4845 if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 4846 if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) { 4847 return true; 4848 } 4849 } 4850 return false; 4851 } 4852 4853 /** 4854 * Bring up the context menu for this view. 4855 * 4856 * @return Whether a context menu was displayed. 4857 */ 4858 public boolean showContextMenu() { 4859 return getParent().showContextMenuForChild(this); 4860 } 4861 4862 /** 4863 * Bring up the context menu for this view, referring to the item under the specified point. 4864 * 4865 * @param x The referenced x coordinate. 4866 * @param y The referenced y coordinate. 4867 * @param metaState The keyboard modifiers that were pressed. 4868 * @return Whether a context menu was displayed. 4869 * 4870 * @hide 4871 */ 4872 public boolean showContextMenu(float x, float y, int metaState) { 4873 return showContextMenu(); 4874 } 4875 4876 /** 4877 * Start an action mode. 4878 * 4879 * @param callback Callback that will control the lifecycle of the action mode 4880 * @return The new action mode if it is started, null otherwise 4881 * 4882 * @see ActionMode 4883 */ 4884 public ActionMode startActionMode(ActionMode.Callback callback) { 4885 ViewParent parent = getParent(); 4886 if (parent == null) return null; 4887 return parent.startActionModeForChild(this, callback); 4888 } 4889 4890 /** 4891 * Register a callback to be invoked when a hardware key is pressed in this view. 4892 * Key presses in software input methods will generally not trigger the methods of 4893 * this listener. 4894 * @param l the key listener to attach to this view 4895 */ 4896 public void setOnKeyListener(OnKeyListener l) { 4897 getListenerInfo().mOnKeyListener = l; 4898 } 4899 4900 /** 4901 * Register a callback to be invoked when a touch event is sent to this view. 4902 * @param l the touch listener to attach to this view 4903 */ 4904 public void setOnTouchListener(OnTouchListener l) { 4905 getListenerInfo().mOnTouchListener = l; 4906 } 4907 4908 /** 4909 * Register a callback to be invoked when a generic motion event is sent to this view. 4910 * @param l the generic motion listener to attach to this view 4911 */ 4912 public void setOnGenericMotionListener(OnGenericMotionListener l) { 4913 getListenerInfo().mOnGenericMotionListener = l; 4914 } 4915 4916 /** 4917 * Register a callback to be invoked when a hover event is sent to this view. 4918 * @param l the hover listener to attach to this view 4919 */ 4920 public void setOnHoverListener(OnHoverListener l) { 4921 getListenerInfo().mOnHoverListener = l; 4922 } 4923 4924 /** 4925 * Register a drag event listener callback object for this View. The parameter is 4926 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 4927 * View, the system calls the 4928 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 4929 * @param l An implementation of {@link android.view.View.OnDragListener}. 4930 */ 4931 public void setOnDragListener(OnDragListener l) { 4932 getListenerInfo().mOnDragListener = l; 4933 } 4934 4935 /** 4936 * Give this view focus. This will cause 4937 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 4938 * 4939 * Note: this does not check whether this {@link View} should get focus, it just 4940 * gives it focus no matter what. It should only be called internally by framework 4941 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 4942 * 4943 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 4944 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 4945 * focus moved when requestFocus() is called. It may not always 4946 * apply, in which case use the default View.FOCUS_DOWN. 4947 * @param previouslyFocusedRect The rectangle of the view that had focus 4948 * prior in this View's coordinate system. 4949 */ 4950 void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) { 4951 if (DBG) { 4952 System.out.println(this + " requestFocus()"); 4953 } 4954 4955 if ((mPrivateFlags & PFLAG_FOCUSED) == 0) { 4956 mPrivateFlags |= PFLAG_FOCUSED; 4957 4958 View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null; 4959 4960 if (mParent != null) { 4961 mParent.requestChildFocus(this, this); 4962 } 4963 4964 if (mAttachInfo != null) { 4965 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this); 4966 } 4967 4968 onFocusChanged(true, direction, previouslyFocusedRect); 4969 refreshDrawableState(); 4970 } 4971 } 4972 4973 /** 4974 * Populates <code>outRect</code> with the hotspot bounds. By default, 4975 * the hotspot bounds are identical to the screen bounds. 4976 * 4977 * @param outRect rect to populate with hotspot bounds 4978 * @hide Only for internal use by views and widgets. 4979 */ 4980 public void getHotspotBounds(Rect outRect) { 4981 final Drawable background = getBackground(); 4982 if (background != null) { 4983 background.getHotspotBounds(outRect); 4984 } else { 4985 getBoundsOnScreen(outRect); 4986 } 4987 } 4988 4989 /** 4990 * Request that a rectangle of this view be visible on the screen, 4991 * scrolling if necessary just enough. 4992 * 4993 * <p>A View should call this if it maintains some notion of which part 4994 * of its content is interesting. For example, a text editing view 4995 * should call this when its cursor moves. 4996 * 4997 * @param rectangle The rectangle. 4998 * @return Whether any parent scrolled. 4999 */ 5000 public boolean requestRectangleOnScreen(Rect rectangle) { 5001 return requestRectangleOnScreen(rectangle, false); 5002 } 5003 5004 /** 5005 * Request that a rectangle of this view be visible on the screen, 5006 * scrolling if necessary just enough. 5007 * 5008 * <p>A View should call this if it maintains some notion of which part 5009 * of its content is interesting. For example, a text editing view 5010 * should call this when its cursor moves. 5011 * 5012 * <p>When <code>immediate</code> is set to true, scrolling will not be 5013 * animated. 5014 * 5015 * @param rectangle The rectangle. 5016 * @param immediate True to forbid animated scrolling, false otherwise 5017 * @return Whether any parent scrolled. 5018 */ 5019 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 5020 if (mParent == null) { 5021 return false; 5022 } 5023 5024 View child = this; 5025 5026 RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF(); 5027 position.set(rectangle); 5028 5029 ViewParent parent = mParent; 5030 boolean scrolled = false; 5031 while (parent != null) { 5032 rectangle.set((int) position.left, (int) position.top, 5033 (int) position.right, (int) position.bottom); 5034 5035 scrolled |= parent.requestChildRectangleOnScreen(child, 5036 rectangle, immediate); 5037 5038 if (!child.hasIdentityMatrix()) { 5039 child.getMatrix().mapRect(position); 5040 } 5041 5042 position.offset(child.mLeft, child.mTop); 5043 5044 if (!(parent instanceof View)) { 5045 break; 5046 } 5047 5048 View parentView = (View) parent; 5049 5050 position.offset(-parentView.getScrollX(), -parentView.getScrollY()); 5051 5052 child = parentView; 5053 parent = child.getParent(); 5054 } 5055 5056 return scrolled; 5057 } 5058 5059 /** 5060 * Called when this view wants to give up focus. If focus is cleared 5061 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called. 5062 * <p> 5063 * <strong>Note:</strong> When a View clears focus the framework is trying 5064 * to give focus to the first focusable View from the top. Hence, if this 5065 * View is the first from the top that can take focus, then all callbacks 5066 * related to clearing focus will be invoked after which the framework will 5067 * give focus to this view. 5068 * </p> 5069 */ 5070 public void clearFocus() { 5071 if (DBG) { 5072 System.out.println(this + " clearFocus()"); 5073 } 5074 5075 clearFocusInternal(null, true, true); 5076 } 5077 5078 /** 5079 * Clears focus from the view, optionally propagating the change up through 5080 * the parent hierarchy and requesting that the root view place new focus. 5081 * 5082 * @param propagate whether to propagate the change up through the parent 5083 * hierarchy 5084 * @param refocus when propagate is true, specifies whether to request the 5085 * root view place new focus 5086 */ 5087 void clearFocusInternal(View focused, boolean propagate, boolean refocus) { 5088 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 5089 mPrivateFlags &= ~PFLAG_FOCUSED; 5090 5091 if (propagate && mParent != null) { 5092 mParent.clearChildFocus(this); 5093 } 5094 5095 onFocusChanged(false, 0, null); 5096 refreshDrawableState(); 5097 5098 if (propagate && (!refocus || !rootViewRequestFocus())) { 5099 notifyGlobalFocusCleared(this); 5100 } 5101 } 5102 } 5103 5104 void notifyGlobalFocusCleared(View oldFocus) { 5105 if (oldFocus != null && mAttachInfo != null) { 5106 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null); 5107 } 5108 } 5109 5110 boolean rootViewRequestFocus() { 5111 final View root = getRootView(); 5112 return root != null && root.requestFocus(); 5113 } 5114 5115 /** 5116 * Called internally by the view system when a new view is getting focus. 5117 * This is what clears the old focus. 5118 * <p> 5119 * <b>NOTE:</b> The parent view's focused child must be updated manually 5120 * after calling this method. Otherwise, the view hierarchy may be left in 5121 * an inconstent state. 5122 */ 5123 void unFocus(View focused) { 5124 if (DBG) { 5125 System.out.println(this + " unFocus()"); 5126 } 5127 5128 clearFocusInternal(focused, false, false); 5129 } 5130 5131 /** 5132 * Returns true if this view has focus iteself, or is the ancestor of the 5133 * view that has focus. 5134 * 5135 * @return True if this view has or contains focus, false otherwise. 5136 */ 5137 @ViewDebug.ExportedProperty(category = "focus") 5138 public boolean hasFocus() { 5139 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 5140 } 5141 5142 /** 5143 * Returns true if this view is focusable or if it contains a reachable View 5144 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 5145 * is a View whose parents do not block descendants focus. 5146 * 5147 * Only {@link #VISIBLE} views are considered focusable. 5148 * 5149 * @return True if the view is focusable or if the view contains a focusable 5150 * View, false otherwise. 5151 * 5152 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 5153 * @see ViewGroup#getTouchscreenBlocksFocus() 5154 */ 5155 public boolean hasFocusable() { 5156 if (!isFocusableInTouchMode()) { 5157 for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) { 5158 final ViewGroup g = (ViewGroup) p; 5159 if (g.shouldBlockFocusForTouchscreen()) { 5160 return false; 5161 } 5162 } 5163 } 5164 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 5165 } 5166 5167 /** 5168 * Called by the view system when the focus state of this view changes. 5169 * When the focus change event is caused by directional navigation, direction 5170 * and previouslyFocusedRect provide insight into where the focus is coming from. 5171 * When overriding, be sure to call up through to the super class so that 5172 * the standard focus handling will occur. 5173 * 5174 * @param gainFocus True if the View has focus; false otherwise. 5175 * @param direction The direction focus has moved when requestFocus() 5176 * is called to give this view focus. Values are 5177 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 5178 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 5179 * It may not always apply, in which case use the default. 5180 * @param previouslyFocusedRect The rectangle, in this view's coordinate 5181 * system, of the previously focused view. If applicable, this will be 5182 * passed in as finer grained information about where the focus is coming 5183 * from (in addition to direction). Will be <code>null</code> otherwise. 5184 */ 5185 protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction, 5186 @Nullable Rect previouslyFocusedRect) { 5187 if (gainFocus) { 5188 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 5189 } else { 5190 notifyViewAccessibilityStateChangedIfNeeded( 5191 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 5192 } 5193 5194 InputMethodManager imm = InputMethodManager.peekInstance(); 5195 if (!gainFocus) { 5196 if (isPressed()) { 5197 setPressed(false); 5198 } 5199 if (imm != null && mAttachInfo != null 5200 && mAttachInfo.mHasWindowFocus) { 5201 imm.focusOut(this); 5202 } 5203 onFocusLost(); 5204 } else if (imm != null && mAttachInfo != null 5205 && mAttachInfo.mHasWindowFocus) { 5206 imm.focusIn(this); 5207 } 5208 5209 invalidate(true); 5210 ListenerInfo li = mListenerInfo; 5211 if (li != null && li.mOnFocusChangeListener != null) { 5212 li.mOnFocusChangeListener.onFocusChange(this, gainFocus); 5213 } 5214 5215 if (mAttachInfo != null) { 5216 mAttachInfo.mKeyDispatchState.reset(this); 5217 } 5218 } 5219 5220 /** 5221 * Sends an accessibility event of the given type. If accessibility is 5222 * not enabled this method has no effect. The default implementation calls 5223 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 5224 * to populate information about the event source (this View), then calls 5225 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 5226 * populate the text content of the event source including its descendants, 5227 * and last calls 5228 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 5229 * on its parent to resuest sending of the event to interested parties. 5230 * <p> 5231 * If an {@link AccessibilityDelegate} has been specified via calling 5232 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5233 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 5234 * responsible for handling this call. 5235 * </p> 5236 * 5237 * @param eventType The type of the event to send, as defined by several types from 5238 * {@link android.view.accessibility.AccessibilityEvent}, such as 5239 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or 5240 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}. 5241 * 5242 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 5243 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5244 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 5245 * @see AccessibilityDelegate 5246 */ 5247 public void sendAccessibilityEvent(int eventType) { 5248 if (mAccessibilityDelegate != null) { 5249 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 5250 } else { 5251 sendAccessibilityEventInternal(eventType); 5252 } 5253 } 5254 5255 /** 5256 * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT} 5257 * {@link AccessibilityEvent} to make an announcement which is related to some 5258 * sort of a context change for which none of the events representing UI transitions 5259 * is a good fit. For example, announcing a new page in a book. If accessibility 5260 * is not enabled this method does nothing. 5261 * 5262 * @param text The announcement text. 5263 */ 5264 public void announceForAccessibility(CharSequence text) { 5265 if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) { 5266 AccessibilityEvent event = AccessibilityEvent.obtain( 5267 AccessibilityEvent.TYPE_ANNOUNCEMENT); 5268 onInitializeAccessibilityEvent(event); 5269 event.getText().add(text); 5270 event.setContentDescription(null); 5271 mParent.requestSendAccessibilityEvent(this, event); 5272 } 5273 } 5274 5275 /** 5276 * @see #sendAccessibilityEvent(int) 5277 * 5278 * Note: Called from the default {@link AccessibilityDelegate}. 5279 */ 5280 void sendAccessibilityEventInternal(int eventType) { 5281 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 5282 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 5283 } 5284 } 5285 5286 /** 5287 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 5288 * takes as an argument an empty {@link AccessibilityEvent} and does not 5289 * perform a check whether accessibility is enabled. 5290 * <p> 5291 * If an {@link AccessibilityDelegate} has been specified via calling 5292 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5293 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 5294 * is responsible for handling this call. 5295 * </p> 5296 * 5297 * @param event The event to send. 5298 * 5299 * @see #sendAccessibilityEvent(int) 5300 */ 5301 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 5302 if (mAccessibilityDelegate != null) { 5303 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 5304 } else { 5305 sendAccessibilityEventUncheckedInternal(event); 5306 } 5307 } 5308 5309 /** 5310 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 5311 * 5312 * Note: Called from the default {@link AccessibilityDelegate}. 5313 */ 5314 void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 5315 if (!isShown()) { 5316 return; 5317 } 5318 onInitializeAccessibilityEvent(event); 5319 // Only a subset of accessibility events populates text content. 5320 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) { 5321 dispatchPopulateAccessibilityEvent(event); 5322 } 5323 // In the beginning we called #isShown(), so we know that getParent() is not null. 5324 getParent().requestSendAccessibilityEvent(this, event); 5325 } 5326 5327 /** 5328 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 5329 * to its children for adding their text content to the event. Note that the 5330 * event text is populated in a separate dispatch path since we add to the 5331 * event not only the text of the source but also the text of all its descendants. 5332 * A typical implementation will call 5333 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 5334 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 5335 * on each child. Override this method if custom population of the event text 5336 * content is required. 5337 * <p> 5338 * If an {@link AccessibilityDelegate} has been specified via calling 5339 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5340 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 5341 * is responsible for handling this call. 5342 * </p> 5343 * <p> 5344 * <em>Note:</em> Accessibility events of certain types are not dispatched for 5345 * populating the event text via this method. For details refer to {@link AccessibilityEvent}. 5346 * </p> 5347 * 5348 * @param event The event. 5349 * 5350 * @return True if the event population was completed. 5351 */ 5352 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 5353 if (mAccessibilityDelegate != null) { 5354 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 5355 } else { 5356 return dispatchPopulateAccessibilityEventInternal(event); 5357 } 5358 } 5359 5360 /** 5361 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5362 * 5363 * Note: Called from the default {@link AccessibilityDelegate}. 5364 */ 5365 boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5366 onPopulateAccessibilityEvent(event); 5367 return false; 5368 } 5369 5370 /** 5371 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 5372 * giving a chance to this View to populate the accessibility event with its 5373 * text content. While this method is free to modify event 5374 * attributes other than text content, doing so should normally be performed in 5375 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 5376 * <p> 5377 * Example: Adding formatted date string to an accessibility event in addition 5378 * to the text added by the super implementation: 5379 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5380 * super.onPopulateAccessibilityEvent(event); 5381 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 5382 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 5383 * mCurrentDate.getTimeInMillis(), flags); 5384 * event.getText().add(selectedDateUtterance); 5385 * }</pre> 5386 * <p> 5387 * If an {@link AccessibilityDelegate} has been specified via calling 5388 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5389 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 5390 * is responsible for handling this call. 5391 * </p> 5392 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5393 * information to the event, in case the default implementation has basic information to add. 5394 * </p> 5395 * 5396 * @param event The accessibility event which to populate. 5397 * 5398 * @see #sendAccessibilityEvent(int) 5399 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5400 */ 5401 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5402 if (mAccessibilityDelegate != null) { 5403 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 5404 } else { 5405 onPopulateAccessibilityEventInternal(event); 5406 } 5407 } 5408 5409 /** 5410 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 5411 * 5412 * Note: Called from the default {@link AccessibilityDelegate}. 5413 */ 5414 void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5415 } 5416 5417 /** 5418 * Initializes an {@link AccessibilityEvent} with information about 5419 * this View which is the event source. In other words, the source of 5420 * an accessibility event is the view whose state change triggered firing 5421 * the event. 5422 * <p> 5423 * Example: Setting the password property of an event in addition 5424 * to properties set by the super implementation: 5425 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5426 * super.onInitializeAccessibilityEvent(event); 5427 * event.setPassword(true); 5428 * }</pre> 5429 * <p> 5430 * If an {@link AccessibilityDelegate} has been specified via calling 5431 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5432 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 5433 * is responsible for handling this call. 5434 * </p> 5435 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5436 * information to the event, in case the default implementation has basic information to add. 5437 * </p> 5438 * @param event The event to initialize. 5439 * 5440 * @see #sendAccessibilityEvent(int) 5441 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5442 */ 5443 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5444 if (mAccessibilityDelegate != null) { 5445 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 5446 } else { 5447 onInitializeAccessibilityEventInternal(event); 5448 } 5449 } 5450 5451 /** 5452 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 5453 * 5454 * Note: Called from the default {@link AccessibilityDelegate}. 5455 */ 5456 void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 5457 event.setSource(this); 5458 event.setClassName(View.class.getName()); 5459 event.setPackageName(getContext().getPackageName()); 5460 event.setEnabled(isEnabled()); 5461 event.setContentDescription(mContentDescription); 5462 5463 switch (event.getEventType()) { 5464 case AccessibilityEvent.TYPE_VIEW_FOCUSED: { 5465 ArrayList<View> focusablesTempList = (mAttachInfo != null) 5466 ? mAttachInfo.mTempArrayList : new ArrayList<View>(); 5467 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL); 5468 event.setItemCount(focusablesTempList.size()); 5469 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 5470 if (mAttachInfo != null) { 5471 focusablesTempList.clear(); 5472 } 5473 } break; 5474 case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: { 5475 CharSequence text = getIterableTextForAccessibility(); 5476 if (text != null && text.length() > 0) { 5477 event.setFromIndex(getAccessibilitySelectionStart()); 5478 event.setToIndex(getAccessibilitySelectionEnd()); 5479 event.setItemCount(text.length()); 5480 } 5481 } break; 5482 } 5483 } 5484 5485 /** 5486 * Returns an {@link AccessibilityNodeInfo} representing this view from the 5487 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 5488 * This method is responsible for obtaining an accessibility node info from a 5489 * pool of reusable instances and calling 5490 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 5491 * initialize the former. 5492 * <p> 5493 * Note: The client is responsible for recycling the obtained instance by calling 5494 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 5495 * </p> 5496 * 5497 * @return A populated {@link AccessibilityNodeInfo}. 5498 * 5499 * @see AccessibilityNodeInfo 5500 */ 5501 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 5502 if (mAccessibilityDelegate != null) { 5503 return mAccessibilityDelegate.createAccessibilityNodeInfo(this); 5504 } else { 5505 return createAccessibilityNodeInfoInternal(); 5506 } 5507 } 5508 5509 /** 5510 * @see #createAccessibilityNodeInfo() 5511 */ 5512 AccessibilityNodeInfo createAccessibilityNodeInfoInternal() { 5513 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 5514 if (provider != null) { 5515 return provider.createAccessibilityNodeInfo(View.NO_ID); 5516 } else { 5517 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 5518 onInitializeAccessibilityNodeInfo(info); 5519 return info; 5520 } 5521 } 5522 5523 /** 5524 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 5525 * The base implementation sets: 5526 * <ul> 5527 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 5528 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 5529 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 5530 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 5531 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 5532 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 5533 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 5534 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 5535 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 5536 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 5537 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 5538 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 5539 * </ul> 5540 * <p> 5541 * Subclasses should override this method, call the super implementation, 5542 * and set additional attributes. 5543 * </p> 5544 * <p> 5545 * If an {@link AccessibilityDelegate} has been specified via calling 5546 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5547 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 5548 * is responsible for handling this call. 5549 * </p> 5550 * 5551 * @param info The instance to initialize. 5552 */ 5553 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 5554 if (mAccessibilityDelegate != null) { 5555 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 5556 } else { 5557 onInitializeAccessibilityNodeInfoInternal(info); 5558 } 5559 } 5560 5561 /** 5562 * Gets the location of this view in screen coordintates. 5563 * 5564 * @param outRect The output location 5565 * @hide 5566 */ 5567 public void getBoundsOnScreen(Rect outRect) { 5568 if (mAttachInfo == null) { 5569 return; 5570 } 5571 5572 RectF position = mAttachInfo.mTmpTransformRect; 5573 position.set(0, 0, mRight - mLeft, mBottom - mTop); 5574 5575 if (!hasIdentityMatrix()) { 5576 getMatrix().mapRect(position); 5577 } 5578 5579 position.offset(mLeft, mTop); 5580 5581 ViewParent parent = mParent; 5582 while (parent instanceof View) { 5583 View parentView = (View) parent; 5584 5585 position.offset(-parentView.mScrollX, -parentView.mScrollY); 5586 5587 if (!parentView.hasIdentityMatrix()) { 5588 parentView.getMatrix().mapRect(position); 5589 } 5590 5591 position.offset(parentView.mLeft, parentView.mTop); 5592 5593 parent = parentView.mParent; 5594 } 5595 5596 if (parent instanceof ViewRootImpl) { 5597 ViewRootImpl viewRootImpl = (ViewRootImpl) parent; 5598 position.offset(0, -viewRootImpl.mCurScrollY); 5599 } 5600 5601 position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 5602 5603 outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f), 5604 (int) (position.right + 0.5f), (int) (position.bottom + 0.5f)); 5605 } 5606 5607 /** 5608 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 5609 * 5610 * Note: Called from the default {@link AccessibilityDelegate}. 5611 */ 5612 void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 5613 Rect bounds = mAttachInfo.mTmpInvalRect; 5614 5615 getDrawingRect(bounds); 5616 info.setBoundsInParent(bounds); 5617 5618 getBoundsOnScreen(bounds); 5619 info.setBoundsInScreen(bounds); 5620 5621 ViewParent parent = getParentForAccessibility(); 5622 if (parent instanceof View) { 5623 info.setParent((View) parent); 5624 } 5625 5626 if (mID != View.NO_ID) { 5627 View rootView = getRootView(); 5628 if (rootView == null) { 5629 rootView = this; 5630 } 5631 5632 View label = rootView.findLabelForView(this, mID); 5633 if (label != null) { 5634 info.setLabeledBy(label); 5635 } 5636 5637 if ((mAttachInfo.mAccessibilityFetchFlags 5638 & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0 5639 && Resources.resourceHasPackage(mID)) { 5640 try { 5641 String viewId = getResources().getResourceName(mID); 5642 info.setViewIdResourceName(viewId); 5643 } catch (Resources.NotFoundException nfe) { 5644 /* ignore */ 5645 } 5646 } 5647 } 5648 5649 if (mLabelForId != View.NO_ID) { 5650 View rootView = getRootView(); 5651 if (rootView == null) { 5652 rootView = this; 5653 } 5654 View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId); 5655 if (labeled != null) { 5656 info.setLabelFor(labeled); 5657 } 5658 } 5659 5660 if (mAccessibilityTraversalBeforeId != View.NO_ID) { 5661 View rootView = getRootView(); 5662 if (rootView == null) { 5663 rootView = this; 5664 } 5665 View next = rootView.findViewInsideOutShouldExist(this, 5666 mAccessibilityTraversalBeforeId); 5667 if (next != null) { 5668 info.setTraversalBefore(next); 5669 } 5670 } 5671 5672 if (mAccessibilityTraversalAfterId != View.NO_ID) { 5673 View rootView = getRootView(); 5674 if (rootView == null) { 5675 rootView = this; 5676 } 5677 View next = rootView.findViewInsideOutShouldExist(this, 5678 mAccessibilityTraversalAfterId); 5679 if (next != null) { 5680 info.setTraversalAfter(next); 5681 } 5682 } 5683 5684 info.setVisibleToUser(isVisibleToUser()); 5685 5686 info.setPackageName(mContext.getPackageName()); 5687 info.setClassName(View.class.getName()); 5688 info.setContentDescription(getContentDescription()); 5689 5690 info.setEnabled(isEnabled()); 5691 info.setClickable(isClickable()); 5692 info.setFocusable(isFocusable()); 5693 info.setFocused(isFocused()); 5694 info.setAccessibilityFocused(isAccessibilityFocused()); 5695 info.setSelected(isSelected()); 5696 info.setLongClickable(isLongClickable()); 5697 info.setLiveRegion(getAccessibilityLiveRegion()); 5698 5699 // TODO: These make sense only if we are in an AdapterView but all 5700 // views can be selected. Maybe from accessibility perspective 5701 // we should report as selectable view in an AdapterView. 5702 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 5703 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 5704 5705 if (isFocusable()) { 5706 if (isFocused()) { 5707 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 5708 } else { 5709 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 5710 } 5711 } 5712 5713 if (!isAccessibilityFocused()) { 5714 info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); 5715 } else { 5716 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); 5717 } 5718 5719 if (isClickable() && isEnabled()) { 5720 info.addAction(AccessibilityNodeInfo.ACTION_CLICK); 5721 } 5722 5723 if (isLongClickable() && isEnabled()) { 5724 info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); 5725 } 5726 5727 CharSequence text = getIterableTextForAccessibility(); 5728 if (text != null && text.length() > 0) { 5729 info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd()); 5730 5731 info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION); 5732 info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); 5733 info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); 5734 info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER 5735 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD 5736 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH); 5737 } 5738 } 5739 5740 private View findLabelForView(View view, int labeledId) { 5741 if (mMatchLabelForPredicate == null) { 5742 mMatchLabelForPredicate = new MatchLabelForPredicate(); 5743 } 5744 mMatchLabelForPredicate.mLabeledId = labeledId; 5745 return findViewByPredicateInsideOut(view, mMatchLabelForPredicate); 5746 } 5747 5748 /** 5749 * Computes whether this view is visible to the user. Such a view is 5750 * attached, visible, all its predecessors are visible, it is not clipped 5751 * entirely by its predecessors, and has an alpha greater than zero. 5752 * 5753 * @return Whether the view is visible on the screen. 5754 * 5755 * @hide 5756 */ 5757 protected boolean isVisibleToUser() { 5758 return isVisibleToUser(null); 5759 } 5760 5761 /** 5762 * Computes whether the given portion of this view is visible to the user. 5763 * Such a view is attached, visible, all its predecessors are visible, 5764 * has an alpha greater than zero, and the specified portion is not 5765 * clipped entirely by its predecessors. 5766 * 5767 * @param boundInView the portion of the view to test; coordinates should be relative; may be 5768 * <code>null</code>, and the entire view will be tested in this case. 5769 * When <code>true</code> is returned by the function, the actual visible 5770 * region will be stored in this parameter; that is, if boundInView is fully 5771 * contained within the view, no modification will be made, otherwise regions 5772 * outside of the visible area of the view will be clipped. 5773 * 5774 * @return Whether the specified portion of the view is visible on the screen. 5775 * 5776 * @hide 5777 */ 5778 protected boolean isVisibleToUser(Rect boundInView) { 5779 if (mAttachInfo != null) { 5780 // Attached to invisible window means this view is not visible. 5781 if (mAttachInfo.mWindowVisibility != View.VISIBLE) { 5782 return false; 5783 } 5784 // An invisible predecessor or one with alpha zero means 5785 // that this view is not visible to the user. 5786 Object current = this; 5787 while (current instanceof View) { 5788 View view = (View) current; 5789 // We have attach info so this view is attached and there is no 5790 // need to check whether we reach to ViewRootImpl on the way up. 5791 if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 || 5792 view.getVisibility() != VISIBLE) { 5793 return false; 5794 } 5795 current = view.mParent; 5796 } 5797 // Check if the view is entirely covered by its predecessors. 5798 Rect visibleRect = mAttachInfo.mTmpInvalRect; 5799 Point offset = mAttachInfo.mPoint; 5800 if (!getGlobalVisibleRect(visibleRect, offset)) { 5801 return false; 5802 } 5803 // Check if the visible portion intersects the rectangle of interest. 5804 if (boundInView != null) { 5805 visibleRect.offset(-offset.x, -offset.y); 5806 return boundInView.intersect(visibleRect); 5807 } 5808 return true; 5809 } 5810 return false; 5811 } 5812 5813 /** 5814 * Computes a point on which a sequence of a down/up event can be sent to 5815 * trigger clicking this view. This method is for the exclusive use by the 5816 * accessibility layer to determine where to send a click event in explore 5817 * by touch mode. 5818 * 5819 * @param interactiveRegion The interactive portion of this window. 5820 * @param outPoint The point to populate. 5821 * @return True of such a point exists. 5822 */ 5823 boolean computeClickPointInScreenForAccessibility(Region interactiveRegion, 5824 Point outPoint) { 5825 // Since the interactive portion of the view is a region but as a view 5826 // may have a transformation matrix which cannot be applied to a 5827 // region we compute the view bounds rectangle and all interactive 5828 // predecessor's and sibling's (siblings of predecessors included) 5829 // rectangles that intersect the view bounds. At the 5830 // end if the view was partially covered by another interactive 5831 // view we compute the view's interactive region and pick a point 5832 // on its boundary path as regions do not offer APIs to get inner 5833 // points. Note that the the code is optimized to fail early and 5834 // avoid unnecessary allocations plus computations. 5835 5836 // The current approach has edge cases that may produce false 5837 // positives or false negatives. For example, a portion of the 5838 // view may be covered by an interactive descendant of a 5839 // predecessor, which we do not compute. Also a view may be handling 5840 // raw touch events instead registering click listeners, which 5841 // we cannot compute. Despite these limitations this approach will 5842 // work most of the time and it is a huge improvement over just 5843 // blindly sending the down and up events in the center of the 5844 // view. 5845 5846 // Cannot click on an unattached view. 5847 if (mAttachInfo == null) { 5848 return false; 5849 } 5850 5851 // Attached to an invisible window means this view is not visible. 5852 if (mAttachInfo.mWindowVisibility != View.VISIBLE) { 5853 return false; 5854 } 5855 5856 RectF bounds = mAttachInfo.mTmpTransformRect; 5857 bounds.set(0, 0, getWidth(), getHeight()); 5858 List<RectF> intersections = mAttachInfo.mTmpRectList; 5859 intersections.clear(); 5860 5861 if (mParent instanceof ViewGroup) { 5862 ViewGroup parentGroup = (ViewGroup) mParent; 5863 if (!parentGroup.translateBoundsAndIntersectionsInWindowCoordinates( 5864 this, bounds, intersections)) { 5865 intersections.clear(); 5866 return false; 5867 } 5868 } 5869 5870 // Take into account the window location. 5871 final int dx = mAttachInfo.mWindowLeft; 5872 final int dy = mAttachInfo.mWindowTop; 5873 bounds.offset(dx, dy); 5874 offsetRects(intersections, dx, dy); 5875 5876 if (intersections.isEmpty() && interactiveRegion == null) { 5877 outPoint.set((int) bounds.centerX(), (int) bounds.centerY()); 5878 } else { 5879 // This view is partially covered by other views, then compute 5880 // the not covered region and pick a point on its boundary. 5881 Region region = new Region(); 5882 region.set((int) bounds.left, (int) bounds.top, 5883 (int) bounds.right, (int) bounds.bottom); 5884 5885 final int intersectionCount = intersections.size(); 5886 for (int i = intersectionCount - 1; i >= 0; i--) { 5887 RectF intersection = intersections.remove(i); 5888 region.op((int) intersection.left, (int) intersection.top, 5889 (int) intersection.right, (int) intersection.bottom, 5890 Region.Op.DIFFERENCE); 5891 } 5892 5893 // If the view is completely covered, done. 5894 if (region.isEmpty()) { 5895 return false; 5896 } 5897 5898 // Take into account the interactive portion of the window 5899 // as the rest is covered by other windows. If no such a region 5900 // then the whole window is interactive. 5901 if (interactiveRegion != null) { 5902 region.op(interactiveRegion, Region.Op.INTERSECT); 5903 } 5904 5905 // If the view is completely covered, done. 5906 if (region.isEmpty()) { 5907 return false; 5908 } 5909 5910 // Try a shortcut here. 5911 if (region.isRect()) { 5912 Rect regionBounds = mAttachInfo.mTmpInvalRect; 5913 region.getBounds(regionBounds); 5914 outPoint.set(regionBounds.centerX(), regionBounds.centerY()); 5915 return true; 5916 } 5917 5918 // Get the a point on the region boundary path. 5919 Path path = region.getBoundaryPath(); 5920 PathMeasure pathMeasure = new PathMeasure(path, false); 5921 final float[] coordinates = mAttachInfo.mTmpTransformLocation; 5922 5923 // Without loss of generality pick a point. 5924 final float point = pathMeasure.getLength() * 0.01f; 5925 if (!pathMeasure.getPosTan(point, coordinates, null)) { 5926 return false; 5927 } 5928 5929 outPoint.set(Math.round(coordinates[0]), Math.round(coordinates[1])); 5930 } 5931 5932 return true; 5933 } 5934 5935 /** 5936 * Adds the clickable rectangles withing the bounds of this view. They 5937 * may overlap. This method is intended for use only by the accessibility 5938 * layer. 5939 * 5940 * @param outRects List to which to add clickable areas. 5941 */ 5942 void addClickableRectsForAccessibility(List<RectF> outRects) { 5943 if (isClickable() || isLongClickable()) { 5944 RectF bounds = new RectF(); 5945 bounds.set(0, 0, getWidth(), getHeight()); 5946 outRects.add(bounds); 5947 } 5948 } 5949 5950 static void offsetRects(List<RectF> rects, float offsetX, float offsetY) { 5951 final int rectCount = rects.size(); 5952 for (int i = 0; i < rectCount; i++) { 5953 RectF intersection = rects.get(i); 5954 intersection.offset(offsetX, offsetY); 5955 } 5956 } 5957 5958 /** 5959 * Returns the delegate for implementing accessibility support via 5960 * composition. For more details see {@link AccessibilityDelegate}. 5961 * 5962 * @return The delegate, or null if none set. 5963 * 5964 * @hide 5965 */ 5966 public AccessibilityDelegate getAccessibilityDelegate() { 5967 return mAccessibilityDelegate; 5968 } 5969 5970 /** 5971 * Sets a delegate for implementing accessibility support via composition as 5972 * opposed to inheritance. The delegate's primary use is for implementing 5973 * backwards compatible widgets. For more details see {@link AccessibilityDelegate}. 5974 * 5975 * @param delegate The delegate instance. 5976 * 5977 * @see AccessibilityDelegate 5978 */ 5979 public void setAccessibilityDelegate(AccessibilityDelegate delegate) { 5980 mAccessibilityDelegate = delegate; 5981 } 5982 5983 /** 5984 * Gets the provider for managing a virtual view hierarchy rooted at this View 5985 * and reported to {@link android.accessibilityservice.AccessibilityService}s 5986 * that explore the window content. 5987 * <p> 5988 * If this method returns an instance, this instance is responsible for managing 5989 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this 5990 * View including the one representing the View itself. Similarly the returned 5991 * instance is responsible for performing accessibility actions on any virtual 5992 * view or the root view itself. 5993 * </p> 5994 * <p> 5995 * If an {@link AccessibilityDelegate} has been specified via calling 5996 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5997 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)} 5998 * is responsible for handling this call. 5999 * </p> 6000 * 6001 * @return The provider. 6002 * 6003 * @see AccessibilityNodeProvider 6004 */ 6005 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 6006 if (mAccessibilityDelegate != null) { 6007 return mAccessibilityDelegate.getAccessibilityNodeProvider(this); 6008 } else { 6009 return null; 6010 } 6011 } 6012 6013 /** 6014 * Gets the unique identifier of this view on the screen for accessibility purposes. 6015 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 6016 * 6017 * @return The view accessibility id. 6018 * 6019 * @hide 6020 */ 6021 public int getAccessibilityViewId() { 6022 if (mAccessibilityViewId == NO_ID) { 6023 mAccessibilityViewId = sNextAccessibilityViewId++; 6024 } 6025 return mAccessibilityViewId; 6026 } 6027 6028 /** 6029 * Gets the unique identifier of the window in which this View reseides. 6030 * 6031 * @return The window accessibility id. 6032 * 6033 * @hide 6034 */ 6035 public int getAccessibilityWindowId() { 6036 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId 6037 : AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 6038 } 6039 6040 /** 6041 * Gets the {@link View} description. It briefly describes the view and is 6042 * primarily used for accessibility support. Set this property to enable 6043 * better accessibility support for your application. This is especially 6044 * true for views that do not have textual representation (For example, 6045 * ImageButton). 6046 * 6047 * @return The content description. 6048 * 6049 * @attr ref android.R.styleable#View_contentDescription 6050 */ 6051 @ViewDebug.ExportedProperty(category = "accessibility") 6052 public CharSequence getContentDescription() { 6053 return mContentDescription; 6054 } 6055 6056 /** 6057 * Sets the {@link View} description. It briefly describes the view and is 6058 * primarily used for accessibility support. Set this property to enable 6059 * better accessibility support for your application. This is especially 6060 * true for views that do not have textual representation (For example, 6061 * ImageButton). 6062 * 6063 * @param contentDescription The content description. 6064 * 6065 * @attr ref android.R.styleable#View_contentDescription 6066 */ 6067 @RemotableViewMethod 6068 public void setContentDescription(CharSequence contentDescription) { 6069 if (mContentDescription == null) { 6070 if (contentDescription == null) { 6071 return; 6072 } 6073 } else if (mContentDescription.equals(contentDescription)) { 6074 return; 6075 } 6076 mContentDescription = contentDescription; 6077 final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0; 6078 if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 6079 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); 6080 notifySubtreeAccessibilityStateChangedIfNeeded(); 6081 } else { 6082 notifyViewAccessibilityStateChangedIfNeeded( 6083 AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION); 6084 } 6085 } 6086 6087 /** 6088 * Sets the id of a view before which this one is visited in accessibility traversal. 6089 * A screen-reader must visit the content of this view before the content of the one 6090 * it precedes. For example, if view B is set to be before view A, then a screen-reader 6091 * will traverse the entire content of B before traversing the entire content of A, 6092 * regardles of what traversal strategy it is using. 6093 * <p> 6094 * Views that do not have specified before/after relationships are traversed in order 6095 * determined by the screen-reader. 6096 * </p> 6097 * <p> 6098 * Setting that this view is before a view that is not important for accessibility 6099 * or if this view is not important for accessibility will have no effect as the 6100 * screen-reader is not aware of unimportant views. 6101 * </p> 6102 * 6103 * @param beforeId The id of a view this one precedes in accessibility traversal. 6104 * 6105 * @attr ref android.R.styleable#View_accessibilityTraversalBefore 6106 * 6107 * @see #setImportantForAccessibility(int) 6108 */ 6109 @RemotableViewMethod 6110 public void setAccessibilityTraversalBefore(int beforeId) { 6111 if (mAccessibilityTraversalBeforeId == beforeId) { 6112 return; 6113 } 6114 mAccessibilityTraversalBeforeId = beforeId; 6115 notifyViewAccessibilityStateChangedIfNeeded( 6116 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 6117 } 6118 6119 /** 6120 * Gets the id of a view before which this one is visited in accessibility traversal. 6121 * 6122 * @return The id of a view this one precedes in accessibility traversal if 6123 * specified, otherwise {@link #NO_ID}. 6124 * 6125 * @see #setAccessibilityTraversalBefore(int) 6126 */ 6127 public int getAccessibilityTraversalBefore() { 6128 return mAccessibilityTraversalBeforeId; 6129 } 6130 6131 /** 6132 * Sets the id of a view after which this one is visited in accessibility traversal. 6133 * A screen-reader must visit the content of the other view before the content of this 6134 * one. For example, if view B is set to be after view A, then a screen-reader 6135 * will traverse the entire content of A before traversing the entire content of B, 6136 * regardles of what traversal strategy it is using. 6137 * <p> 6138 * Views that do not have specified before/after relationships are traversed in order 6139 * determined by the screen-reader. 6140 * </p> 6141 * <p> 6142 * Setting that this view is after a view that is not important for accessibility 6143 * or if this view is not important for accessibility will have no effect as the 6144 * screen-reader is not aware of unimportant views. 6145 * </p> 6146 * 6147 * @param afterId The id of a view this one succedees in accessibility traversal. 6148 * 6149 * @attr ref android.R.styleable#View_accessibilityTraversalAfter 6150 * 6151 * @see #setImportantForAccessibility(int) 6152 */ 6153 @RemotableViewMethod 6154 public void setAccessibilityTraversalAfter(int afterId) { 6155 if (mAccessibilityTraversalAfterId == afterId) { 6156 return; 6157 } 6158 mAccessibilityTraversalAfterId = afterId; 6159 notifyViewAccessibilityStateChangedIfNeeded( 6160 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 6161 } 6162 6163 /** 6164 * Gets the id of a view after which this one is visited in accessibility traversal. 6165 * 6166 * @return The id of a view this one succeedes in accessibility traversal if 6167 * specified, otherwise {@link #NO_ID}. 6168 * 6169 * @see #setAccessibilityTraversalAfter(int) 6170 */ 6171 public int getAccessibilityTraversalAfter() { 6172 return mAccessibilityTraversalAfterId; 6173 } 6174 6175 /** 6176 * Gets the id of a view for which this view serves as a label for 6177 * accessibility purposes. 6178 * 6179 * @return The labeled view id. 6180 */ 6181 @ViewDebug.ExportedProperty(category = "accessibility") 6182 public int getLabelFor() { 6183 return mLabelForId; 6184 } 6185 6186 /** 6187 * Sets the id of a view for which this view serves as a label for 6188 * accessibility purposes. 6189 * 6190 * @param id The labeled view id. 6191 */ 6192 @RemotableViewMethod 6193 public void setLabelFor(int id) { 6194 if (mLabelForId == id) { 6195 return; 6196 } 6197 mLabelForId = id; 6198 if (mLabelForId != View.NO_ID 6199 && mID == View.NO_ID) { 6200 mID = generateViewId(); 6201 } 6202 notifyViewAccessibilityStateChangedIfNeeded( 6203 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 6204 } 6205 6206 /** 6207 * Invoked whenever this view loses focus, either by losing window focus or by losing 6208 * focus within its window. This method can be used to clear any state tied to the 6209 * focus. For instance, if a button is held pressed with the trackball and the window 6210 * loses focus, this method can be used to cancel the press. 6211 * 6212 * Subclasses of View overriding this method should always call super.onFocusLost(). 6213 * 6214 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 6215 * @see #onWindowFocusChanged(boolean) 6216 * 6217 * @hide pending API council approval 6218 */ 6219 protected void onFocusLost() { 6220 resetPressedState(); 6221 } 6222 6223 private void resetPressedState() { 6224 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 6225 return; 6226 } 6227 6228 if (isPressed()) { 6229 setPressed(false); 6230 6231 if (!mHasPerformedLongPress) { 6232 removeLongPressCallback(); 6233 } 6234 } 6235 } 6236 6237 /** 6238 * Returns true if this view has focus 6239 * 6240 * @return True if this view has focus, false otherwise. 6241 */ 6242 @ViewDebug.ExportedProperty(category = "focus") 6243 public boolean isFocused() { 6244 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 6245 } 6246 6247 /** 6248 * Find the view in the hierarchy rooted at this view that currently has 6249 * focus. 6250 * 6251 * @return The view that currently has focus, or null if no focused view can 6252 * be found. 6253 */ 6254 public View findFocus() { 6255 return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null; 6256 } 6257 6258 /** 6259 * Indicates whether this view is one of the set of scrollable containers in 6260 * its window. 6261 * 6262 * @return whether this view is one of the set of scrollable containers in 6263 * its window 6264 * 6265 * @attr ref android.R.styleable#View_isScrollContainer 6266 */ 6267 public boolean isScrollContainer() { 6268 return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0; 6269 } 6270 6271 /** 6272 * Change whether this view is one of the set of scrollable containers in 6273 * its window. This will be used to determine whether the window can 6274 * resize or must pan when a soft input area is open -- scrollable 6275 * containers allow the window to use resize mode since the container 6276 * will appropriately shrink. 6277 * 6278 * @attr ref android.R.styleable#View_isScrollContainer 6279 */ 6280 public void setScrollContainer(boolean isScrollContainer) { 6281 if (isScrollContainer) { 6282 if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) { 6283 mAttachInfo.mScrollContainers.add(this); 6284 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 6285 } 6286 mPrivateFlags |= PFLAG_SCROLL_CONTAINER; 6287 } else { 6288 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 6289 mAttachInfo.mScrollContainers.remove(this); 6290 } 6291 mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED); 6292 } 6293 } 6294 6295 /** 6296 * Returns the quality of the drawing cache. 6297 * 6298 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 6299 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 6300 * 6301 * @see #setDrawingCacheQuality(int) 6302 * @see #setDrawingCacheEnabled(boolean) 6303 * @see #isDrawingCacheEnabled() 6304 * 6305 * @attr ref android.R.styleable#View_drawingCacheQuality 6306 */ 6307 @DrawingCacheQuality 6308 public int getDrawingCacheQuality() { 6309 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 6310 } 6311 6312 /** 6313 * Set the drawing cache quality of this view. This value is used only when the 6314 * drawing cache is enabled 6315 * 6316 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 6317 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 6318 * 6319 * @see #getDrawingCacheQuality() 6320 * @see #setDrawingCacheEnabled(boolean) 6321 * @see #isDrawingCacheEnabled() 6322 * 6323 * @attr ref android.R.styleable#View_drawingCacheQuality 6324 */ 6325 public void setDrawingCacheQuality(@DrawingCacheQuality int quality) { 6326 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 6327 } 6328 6329 /** 6330 * Returns whether the screen should remain on, corresponding to the current 6331 * value of {@link #KEEP_SCREEN_ON}. 6332 * 6333 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 6334 * 6335 * @see #setKeepScreenOn(boolean) 6336 * 6337 * @attr ref android.R.styleable#View_keepScreenOn 6338 */ 6339 public boolean getKeepScreenOn() { 6340 return (mViewFlags & KEEP_SCREEN_ON) != 0; 6341 } 6342 6343 /** 6344 * Controls whether the screen should remain on, modifying the 6345 * value of {@link #KEEP_SCREEN_ON}. 6346 * 6347 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 6348 * 6349 * @see #getKeepScreenOn() 6350 * 6351 * @attr ref android.R.styleable#View_keepScreenOn 6352 */ 6353 public void setKeepScreenOn(boolean keepScreenOn) { 6354 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 6355 } 6356 6357 /** 6358 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 6359 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6360 * 6361 * @attr ref android.R.styleable#View_nextFocusLeft 6362 */ 6363 public int getNextFocusLeftId() { 6364 return mNextFocusLeftId; 6365 } 6366 6367 /** 6368 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 6369 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 6370 * decide automatically. 6371 * 6372 * @attr ref android.R.styleable#View_nextFocusLeft 6373 */ 6374 public void setNextFocusLeftId(int nextFocusLeftId) { 6375 mNextFocusLeftId = nextFocusLeftId; 6376 } 6377 6378 /** 6379 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 6380 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6381 * 6382 * @attr ref android.R.styleable#View_nextFocusRight 6383 */ 6384 public int getNextFocusRightId() { 6385 return mNextFocusRightId; 6386 } 6387 6388 /** 6389 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 6390 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 6391 * decide automatically. 6392 * 6393 * @attr ref android.R.styleable#View_nextFocusRight 6394 */ 6395 public void setNextFocusRightId(int nextFocusRightId) { 6396 mNextFocusRightId = nextFocusRightId; 6397 } 6398 6399 /** 6400 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 6401 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6402 * 6403 * @attr ref android.R.styleable#View_nextFocusUp 6404 */ 6405 public int getNextFocusUpId() { 6406 return mNextFocusUpId; 6407 } 6408 6409 /** 6410 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 6411 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 6412 * decide automatically. 6413 * 6414 * @attr ref android.R.styleable#View_nextFocusUp 6415 */ 6416 public void setNextFocusUpId(int nextFocusUpId) { 6417 mNextFocusUpId = nextFocusUpId; 6418 } 6419 6420 /** 6421 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 6422 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6423 * 6424 * @attr ref android.R.styleable#View_nextFocusDown 6425 */ 6426 public int getNextFocusDownId() { 6427 return mNextFocusDownId; 6428 } 6429 6430 /** 6431 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 6432 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 6433 * decide automatically. 6434 * 6435 * @attr ref android.R.styleable#View_nextFocusDown 6436 */ 6437 public void setNextFocusDownId(int nextFocusDownId) { 6438 mNextFocusDownId = nextFocusDownId; 6439 } 6440 6441 /** 6442 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 6443 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6444 * 6445 * @attr ref android.R.styleable#View_nextFocusForward 6446 */ 6447 public int getNextFocusForwardId() { 6448 return mNextFocusForwardId; 6449 } 6450 6451 /** 6452 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 6453 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 6454 * decide automatically. 6455 * 6456 * @attr ref android.R.styleable#View_nextFocusForward 6457 */ 6458 public void setNextFocusForwardId(int nextFocusForwardId) { 6459 mNextFocusForwardId = nextFocusForwardId; 6460 } 6461 6462 /** 6463 * Returns the visibility of this view and all of its ancestors 6464 * 6465 * @return True if this view and all of its ancestors are {@link #VISIBLE} 6466 */ 6467 public boolean isShown() { 6468 View current = this; 6469 //noinspection ConstantConditions 6470 do { 6471 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 6472 return false; 6473 } 6474 ViewParent parent = current.mParent; 6475 if (parent == null) { 6476 return false; // We are not attached to the view root 6477 } 6478 if (!(parent instanceof View)) { 6479 return true; 6480 } 6481 current = (View) parent; 6482 } while (current != null); 6483 6484 return false; 6485 } 6486 6487 /** 6488 * Called by the view hierarchy when the content insets for a window have 6489 * changed, to allow it to adjust its content to fit within those windows. 6490 * The content insets tell you the space that the status bar, input method, 6491 * and other system windows infringe on the application's window. 6492 * 6493 * <p>You do not normally need to deal with this function, since the default 6494 * window decoration given to applications takes care of applying it to the 6495 * content of the window. If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 6496 * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case, 6497 * and your content can be placed under those system elements. You can then 6498 * use this method within your view hierarchy if you have parts of your UI 6499 * which you would like to ensure are not being covered. 6500 * 6501 * <p>The default implementation of this method simply applies the content 6502 * insets to the view's padding, consuming that content (modifying the 6503 * insets to be 0), and returning true. This behavior is off by default, but can 6504 * be enabled through {@link #setFitsSystemWindows(boolean)}. 6505 * 6506 * <p>This function's traversal down the hierarchy is depth-first. The same content 6507 * insets object is propagated down the hierarchy, so any changes made to it will 6508 * be seen by all following views (including potentially ones above in 6509 * the hierarchy since this is a depth-first traversal). The first view 6510 * that returns true will abort the entire traversal. 6511 * 6512 * <p>The default implementation works well for a situation where it is 6513 * used with a container that covers the entire window, allowing it to 6514 * apply the appropriate insets to its content on all edges. If you need 6515 * a more complicated layout (such as two different views fitting system 6516 * windows, one on the top of the window, and one on the bottom), 6517 * you can override the method and handle the insets however you would like. 6518 * Note that the insets provided by the framework are always relative to the 6519 * far edges of the window, not accounting for the location of the called view 6520 * within that window. (In fact when this method is called you do not yet know 6521 * where the layout will place the view, as it is done before layout happens.) 6522 * 6523 * <p>Note: unlike many View methods, there is no dispatch phase to this 6524 * call. If you are overriding it in a ViewGroup and want to allow the 6525 * call to continue to your children, you must be sure to call the super 6526 * implementation. 6527 * 6528 * <p>Here is a sample layout that makes use of fitting system windows 6529 * to have controls for a video view placed inside of the window decorations 6530 * that it hides and shows. This can be used with code like the second 6531 * sample (video player) shown in {@link #setSystemUiVisibility(int)}. 6532 * 6533 * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete} 6534 * 6535 * @param insets Current content insets of the window. Prior to 6536 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify 6537 * the insets or else you and Android will be unhappy. 6538 * 6539 * @return {@code true} if this view applied the insets and it should not 6540 * continue propagating further down the hierarchy, {@code false} otherwise. 6541 * @see #getFitsSystemWindows() 6542 * @see #setFitsSystemWindows(boolean) 6543 * @see #setSystemUiVisibility(int) 6544 * 6545 * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply 6546 * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use 6547 * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)} 6548 * to implement handling their own insets. 6549 */ 6550 protected boolean fitSystemWindows(Rect insets) { 6551 if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) { 6552 if (insets == null) { 6553 // Null insets by definition have already been consumed. 6554 // This call cannot apply insets since there are none to apply, 6555 // so return false. 6556 return false; 6557 } 6558 // If we're not in the process of dispatching the newer apply insets call, 6559 // that means we're not in the compatibility path. Dispatch into the newer 6560 // apply insets path and take things from there. 6561 try { 6562 mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS; 6563 return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed(); 6564 } finally { 6565 mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS; 6566 } 6567 } else { 6568 // We're being called from the newer apply insets path. 6569 // Perform the standard fallback behavior. 6570 return fitSystemWindowsInt(insets); 6571 } 6572 } 6573 6574 private boolean fitSystemWindowsInt(Rect insets) { 6575 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 6576 mUserPaddingStart = UNDEFINED_PADDING; 6577 mUserPaddingEnd = UNDEFINED_PADDING; 6578 Rect localInsets = sThreadLocal.get(); 6579 if (localInsets == null) { 6580 localInsets = new Rect(); 6581 sThreadLocal.set(localInsets); 6582 } 6583 boolean res = computeFitSystemWindows(insets, localInsets); 6584 mUserPaddingLeftInitial = localInsets.left; 6585 mUserPaddingRightInitial = localInsets.right; 6586 internalSetPadding(localInsets.left, localInsets.top, 6587 localInsets.right, localInsets.bottom); 6588 return res; 6589 } 6590 return false; 6591 } 6592 6593 /** 6594 * Called when the view should apply {@link WindowInsets} according to its internal policy. 6595 * 6596 * <p>This method should be overridden by views that wish to apply a policy different from or 6597 * in addition to the default behavior. Clients that wish to force a view subtree 6598 * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p> 6599 * 6600 * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set 6601 * it will be called during dispatch instead of this method. The listener may optionally 6602 * call this method from its own implementation if it wishes to apply the view's default 6603 * insets policy in addition to its own.</p> 6604 * 6605 * <p>Implementations of this method should either return the insets parameter unchanged 6606 * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed 6607 * that this view applied itself. This allows new inset types added in future platform 6608 * versions to pass through existing implementations unchanged without being erroneously 6609 * consumed.</p> 6610 * 6611 * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows} 6612 * property is set then the view will consume the system window insets and apply them 6613 * as padding for the view.</p> 6614 * 6615 * @param insets Insets to apply 6616 * @return The supplied insets with any applied insets consumed 6617 */ 6618 public WindowInsets onApplyWindowInsets(WindowInsets insets) { 6619 if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) { 6620 // We weren't called from within a direct call to fitSystemWindows, 6621 // call into it as a fallback in case we're in a class that overrides it 6622 // and has logic to perform. 6623 if (fitSystemWindows(insets.getSystemWindowInsets())) { 6624 return insets.consumeSystemWindowInsets(); 6625 } 6626 } else { 6627 // We were called from within a direct call to fitSystemWindows. 6628 if (fitSystemWindowsInt(insets.getSystemWindowInsets())) { 6629 return insets.consumeSystemWindowInsets(); 6630 } 6631 } 6632 return insets; 6633 } 6634 6635 /** 6636 * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying 6637 * window insets to this view. The listener's 6638 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 6639 * method will be called instead of the view's 6640 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 6641 * 6642 * @param listener Listener to set 6643 * 6644 * @see #onApplyWindowInsets(WindowInsets) 6645 */ 6646 public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) { 6647 getListenerInfo().mOnApplyWindowInsetsListener = listener; 6648 } 6649 6650 /** 6651 * Request to apply the given window insets to this view or another view in its subtree. 6652 * 6653 * <p>This method should be called by clients wishing to apply insets corresponding to areas 6654 * obscured by window decorations or overlays. This can include the status and navigation bars, 6655 * action bars, input methods and more. New inset categories may be added in the future. 6656 * The method returns the insets provided minus any that were applied by this view or its 6657 * children.</p> 6658 * 6659 * <p>Clients wishing to provide custom behavior should override the 6660 * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a 6661 * {@link OnApplyWindowInsetsListener} via the 6662 * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener} 6663 * method.</p> 6664 * 6665 * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method. 6666 * </p> 6667 * 6668 * @param insets Insets to apply 6669 * @return The provided insets minus the insets that were consumed 6670 */ 6671 public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) { 6672 try { 6673 mPrivateFlags3 |= PFLAG3_APPLYING_INSETS; 6674 if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) { 6675 return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets); 6676 } else { 6677 return onApplyWindowInsets(insets); 6678 } 6679 } finally { 6680 mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS; 6681 } 6682 } 6683 6684 /** 6685 * @hide Compute the insets that should be consumed by this view and the ones 6686 * that should propagate to those under it. 6687 */ 6688 protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) { 6689 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 6690 || mAttachInfo == null 6691 || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0 6692 && !mAttachInfo.mOverscanRequested)) { 6693 outLocalInsets.set(inoutInsets); 6694 inoutInsets.set(0, 0, 0, 0); 6695 return true; 6696 } else { 6697 // The application wants to take care of fitting system window for 6698 // the content... however we still need to take care of any overscan here. 6699 final Rect overscan = mAttachInfo.mOverscanInsets; 6700 outLocalInsets.set(overscan); 6701 inoutInsets.left -= overscan.left; 6702 inoutInsets.top -= overscan.top; 6703 inoutInsets.right -= overscan.right; 6704 inoutInsets.bottom -= overscan.bottom; 6705 return false; 6706 } 6707 } 6708 6709 /** 6710 * Compute insets that should be consumed by this view and the ones that should propagate 6711 * to those under it. 6712 * 6713 * @param in Insets currently being processed by this View, likely received as a parameter 6714 * to {@link #onApplyWindowInsets(WindowInsets)}. 6715 * @param outLocalInsets A Rect that will receive the insets that should be consumed 6716 * by this view 6717 * @return Insets that should be passed along to views under this one 6718 */ 6719 public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) { 6720 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 6721 || mAttachInfo == null 6722 || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) { 6723 outLocalInsets.set(in.getSystemWindowInsets()); 6724 return in.consumeSystemWindowInsets(); 6725 } else { 6726 outLocalInsets.set(0, 0, 0, 0); 6727 return in; 6728 } 6729 } 6730 6731 /** 6732 * Sets whether or not this view should account for system screen decorations 6733 * such as the status bar and inset its content; that is, controlling whether 6734 * the default implementation of {@link #fitSystemWindows(Rect)} will be 6735 * executed. See that method for more details. 6736 * 6737 * <p>Note that if you are providing your own implementation of 6738 * {@link #fitSystemWindows(Rect)}, then there is no need to set this 6739 * flag to true -- your implementation will be overriding the default 6740 * implementation that checks this flag. 6741 * 6742 * @param fitSystemWindows If true, then the default implementation of 6743 * {@link #fitSystemWindows(Rect)} will be executed. 6744 * 6745 * @attr ref android.R.styleable#View_fitsSystemWindows 6746 * @see #getFitsSystemWindows() 6747 * @see #fitSystemWindows(Rect) 6748 * @see #setSystemUiVisibility(int) 6749 */ 6750 public void setFitsSystemWindows(boolean fitSystemWindows) { 6751 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 6752 } 6753 6754 /** 6755 * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method 6756 * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)} 6757 * will be executed. 6758 * 6759 * @return {@code true} if the default implementation of 6760 * {@link #fitSystemWindows(Rect)} will be executed. 6761 * 6762 * @attr ref android.R.styleable#View_fitsSystemWindows 6763 * @see #setFitsSystemWindows(boolean) 6764 * @see #fitSystemWindows(Rect) 6765 * @see #setSystemUiVisibility(int) 6766 */ 6767 @ViewDebug.ExportedProperty 6768 public boolean getFitsSystemWindows() { 6769 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 6770 } 6771 6772 /** @hide */ 6773 public boolean fitsSystemWindows() { 6774 return getFitsSystemWindows(); 6775 } 6776 6777 /** 6778 * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed. 6779 * @deprecated Use {@link #requestApplyInsets()} for newer platform versions. 6780 */ 6781 public void requestFitSystemWindows() { 6782 if (mParent != null) { 6783 mParent.requestFitSystemWindows(); 6784 } 6785 } 6786 6787 /** 6788 * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed. 6789 */ 6790 public void requestApplyInsets() { 6791 requestFitSystemWindows(); 6792 } 6793 6794 /** 6795 * For use by PhoneWindow to make its own system window fitting optional. 6796 * @hide 6797 */ 6798 public void makeOptionalFitsSystemWindows() { 6799 setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS); 6800 } 6801 6802 /** 6803 * Returns the visibility status for this view. 6804 * 6805 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 6806 * @attr ref android.R.styleable#View_visibility 6807 */ 6808 @ViewDebug.ExportedProperty(mapping = { 6809 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 6810 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 6811 @ViewDebug.IntToString(from = GONE, to = "GONE") 6812 }) 6813 @Visibility 6814 public int getVisibility() { 6815 return mViewFlags & VISIBILITY_MASK; 6816 } 6817 6818 /** 6819 * Set the enabled state of this view. 6820 * 6821 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 6822 * @attr ref android.R.styleable#View_visibility 6823 */ 6824 @RemotableViewMethod 6825 public void setVisibility(@Visibility int visibility) { 6826 setFlags(visibility, VISIBILITY_MASK); 6827 if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false); 6828 } 6829 6830 /** 6831 * Returns the enabled status for this view. The interpretation of the 6832 * enabled state varies by subclass. 6833 * 6834 * @return True if this view is enabled, false otherwise. 6835 */ 6836 @ViewDebug.ExportedProperty 6837 public boolean isEnabled() { 6838 return (mViewFlags & ENABLED_MASK) == ENABLED; 6839 } 6840 6841 /** 6842 * Set the enabled state of this view. The interpretation of the enabled 6843 * state varies by subclass. 6844 * 6845 * @param enabled True if this view is enabled, false otherwise. 6846 */ 6847 @RemotableViewMethod 6848 public void setEnabled(boolean enabled) { 6849 if (enabled == isEnabled()) return; 6850 6851 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 6852 6853 /* 6854 * The View most likely has to change its appearance, so refresh 6855 * the drawable state. 6856 */ 6857 refreshDrawableState(); 6858 6859 // Invalidate too, since the default behavior for views is to be 6860 // be drawn at 50% alpha rather than to change the drawable. 6861 invalidate(true); 6862 6863 if (!enabled) { 6864 cancelPendingInputEvents(); 6865 } 6866 } 6867 6868 /** 6869 * Set whether this view can receive the focus. 6870 * 6871 * Setting this to false will also ensure that this view is not focusable 6872 * in touch mode. 6873 * 6874 * @param focusable If true, this view can receive the focus. 6875 * 6876 * @see #setFocusableInTouchMode(boolean) 6877 * @attr ref android.R.styleable#View_focusable 6878 */ 6879 public void setFocusable(boolean focusable) { 6880 if (!focusable) { 6881 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 6882 } 6883 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 6884 } 6885 6886 /** 6887 * Set whether this view can receive focus while in touch mode. 6888 * 6889 * Setting this to true will also ensure that this view is focusable. 6890 * 6891 * @param focusableInTouchMode If true, this view can receive the focus while 6892 * in touch mode. 6893 * 6894 * @see #setFocusable(boolean) 6895 * @attr ref android.R.styleable#View_focusableInTouchMode 6896 */ 6897 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 6898 // Focusable in touch mode should always be set before the focusable flag 6899 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 6900 // which, in touch mode, will not successfully request focus on this view 6901 // because the focusable in touch mode flag is not set 6902 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 6903 if (focusableInTouchMode) { 6904 setFlags(FOCUSABLE, FOCUSABLE_MASK); 6905 } 6906 } 6907 6908 /** 6909 * Set whether this view should have sound effects enabled for events such as 6910 * clicking and touching. 6911 * 6912 * <p>You may wish to disable sound effects for a view if you already play sounds, 6913 * for instance, a dial key that plays dtmf tones. 6914 * 6915 * @param soundEffectsEnabled whether sound effects are enabled for this view. 6916 * @see #isSoundEffectsEnabled() 6917 * @see #playSoundEffect(int) 6918 * @attr ref android.R.styleable#View_soundEffectsEnabled 6919 */ 6920 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 6921 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 6922 } 6923 6924 /** 6925 * @return whether this view should have sound effects enabled for events such as 6926 * clicking and touching. 6927 * 6928 * @see #setSoundEffectsEnabled(boolean) 6929 * @see #playSoundEffect(int) 6930 * @attr ref android.R.styleable#View_soundEffectsEnabled 6931 */ 6932 @ViewDebug.ExportedProperty 6933 public boolean isSoundEffectsEnabled() { 6934 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 6935 } 6936 6937 /** 6938 * Set whether this view should have haptic feedback for events such as 6939 * long presses. 6940 * 6941 * <p>You may wish to disable haptic feedback if your view already controls 6942 * its own haptic feedback. 6943 * 6944 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 6945 * @see #isHapticFeedbackEnabled() 6946 * @see #performHapticFeedback(int) 6947 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6948 */ 6949 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 6950 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 6951 } 6952 6953 /** 6954 * @return whether this view should have haptic feedback enabled for events 6955 * long presses. 6956 * 6957 * @see #setHapticFeedbackEnabled(boolean) 6958 * @see #performHapticFeedback(int) 6959 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6960 */ 6961 @ViewDebug.ExportedProperty 6962 public boolean isHapticFeedbackEnabled() { 6963 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 6964 } 6965 6966 /** 6967 * Returns the layout direction for this view. 6968 * 6969 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 6970 * {@link #LAYOUT_DIRECTION_RTL}, 6971 * {@link #LAYOUT_DIRECTION_INHERIT} or 6972 * {@link #LAYOUT_DIRECTION_LOCALE}. 6973 * 6974 * @attr ref android.R.styleable#View_layoutDirection 6975 * 6976 * @hide 6977 */ 6978 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6979 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 6980 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 6981 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 6982 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 6983 }) 6984 @LayoutDir 6985 public int getRawLayoutDirection() { 6986 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 6987 } 6988 6989 /** 6990 * Set the layout direction for this view. This will propagate a reset of layout direction 6991 * resolution to the view's children and resolve layout direction for this view. 6992 * 6993 * @param layoutDirection the layout direction to set. Should be one of: 6994 * 6995 * {@link #LAYOUT_DIRECTION_LTR}, 6996 * {@link #LAYOUT_DIRECTION_RTL}, 6997 * {@link #LAYOUT_DIRECTION_INHERIT}, 6998 * {@link #LAYOUT_DIRECTION_LOCALE}. 6999 * 7000 * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution 7001 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 7002 * will return the default {@link #LAYOUT_DIRECTION_LTR}. 7003 * 7004 * @attr ref android.R.styleable#View_layoutDirection 7005 */ 7006 @RemotableViewMethod 7007 public void setLayoutDirection(@LayoutDir int layoutDirection) { 7008 if (getRawLayoutDirection() != layoutDirection) { 7009 // Reset the current layout direction and the resolved one 7010 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK; 7011 resetRtlProperties(); 7012 // Set the new layout direction (filtered) 7013 mPrivateFlags2 |= 7014 ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK); 7015 // We need to resolve all RTL properties as they all depend on layout direction 7016 resolveRtlPropertiesIfNeeded(); 7017 requestLayout(); 7018 invalidate(true); 7019 } 7020 } 7021 7022 /** 7023 * Returns the resolved layout direction for this view. 7024 * 7025 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 7026 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL. 7027 * 7028 * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version 7029 * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}. 7030 * 7031 * @attr ref android.R.styleable#View_layoutDirection 7032 */ 7033 @ViewDebug.ExportedProperty(category = "layout", mapping = { 7034 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 7035 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 7036 }) 7037 @ResolvedLayoutDir 7038 public int getLayoutDirection() { 7039 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 7040 if (targetSdkVersion < JELLY_BEAN_MR1) { 7041 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 7042 return LAYOUT_DIRECTION_RESOLVED_DEFAULT; 7043 } 7044 return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) == 7045 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 7046 } 7047 7048 /** 7049 * Indicates whether or not this view's layout is right-to-left. This is resolved from 7050 * layout attribute and/or the inherited value from the parent 7051 * 7052 * @return true if the layout is right-to-left. 7053 * 7054 * @hide 7055 */ 7056 @ViewDebug.ExportedProperty(category = "layout") 7057 public boolean isLayoutRtl() { 7058 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL); 7059 } 7060 7061 /** 7062 * Indicates whether the view is currently tracking transient state that the 7063 * app should not need to concern itself with saving and restoring, but that 7064 * the framework should take special note to preserve when possible. 7065 * 7066 * <p>A view with transient state cannot be trivially rebound from an external 7067 * data source, such as an adapter binding item views in a list. This may be 7068 * because the view is performing an animation, tracking user selection 7069 * of content, or similar.</p> 7070 * 7071 * @return true if the view has transient state 7072 */ 7073 @ViewDebug.ExportedProperty(category = "layout") 7074 public boolean hasTransientState() { 7075 return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE; 7076 } 7077 7078 /** 7079 * Set whether this view is currently tracking transient state that the 7080 * framework should attempt to preserve when possible. This flag is reference counted, 7081 * so every call to setHasTransientState(true) should be paired with a later call 7082 * to setHasTransientState(false). 7083 * 7084 * <p>A view with transient state cannot be trivially rebound from an external 7085 * data source, such as an adapter binding item views in a list. This may be 7086 * because the view is performing an animation, tracking user selection 7087 * of content, or similar.</p> 7088 * 7089 * @param hasTransientState true if this view has transient state 7090 */ 7091 public void setHasTransientState(boolean hasTransientState) { 7092 mTransientStateCount = hasTransientState ? mTransientStateCount + 1 : 7093 mTransientStateCount - 1; 7094 if (mTransientStateCount < 0) { 7095 mTransientStateCount = 0; 7096 Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " + 7097 "unmatched pair of setHasTransientState calls"); 7098 } else if ((hasTransientState && mTransientStateCount == 1) || 7099 (!hasTransientState && mTransientStateCount == 0)) { 7100 // update flag if we've just incremented up from 0 or decremented down to 0 7101 mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) | 7102 (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0); 7103 if (mParent != null) { 7104 try { 7105 mParent.childHasTransientStateChanged(this, hasTransientState); 7106 } catch (AbstractMethodError e) { 7107 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 7108 " does not fully implement ViewParent", e); 7109 } 7110 } 7111 } 7112 } 7113 7114 /** 7115 * Returns true if this view is currently attached to a window. 7116 */ 7117 public boolean isAttachedToWindow() { 7118 return mAttachInfo != null; 7119 } 7120 7121 /** 7122 * Returns true if this view has been through at least one layout since it 7123 * was last attached to or detached from a window. 7124 */ 7125 public boolean isLaidOut() { 7126 return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT; 7127 } 7128 7129 /** 7130 * If this view doesn't do any drawing on its own, set this flag to 7131 * allow further optimizations. By default, this flag is not set on 7132 * View, but could be set on some View subclasses such as ViewGroup. 7133 * 7134 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 7135 * you should clear this flag. 7136 * 7137 * @param willNotDraw whether or not this View draw on its own 7138 */ 7139 public void setWillNotDraw(boolean willNotDraw) { 7140 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 7141 } 7142 7143 /** 7144 * Returns whether or not this View draws on its own. 7145 * 7146 * @return true if this view has nothing to draw, false otherwise 7147 */ 7148 @ViewDebug.ExportedProperty(category = "drawing") 7149 public boolean willNotDraw() { 7150 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 7151 } 7152 7153 /** 7154 * When a View's drawing cache is enabled, drawing is redirected to an 7155 * offscreen bitmap. Some views, like an ImageView, must be able to 7156 * bypass this mechanism if they already draw a single bitmap, to avoid 7157 * unnecessary usage of the memory. 7158 * 7159 * @param willNotCacheDrawing true if this view does not cache its 7160 * drawing, false otherwise 7161 */ 7162 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 7163 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 7164 } 7165 7166 /** 7167 * Returns whether or not this View can cache its drawing or not. 7168 * 7169 * @return true if this view does not cache its drawing, false otherwise 7170 */ 7171 @ViewDebug.ExportedProperty(category = "drawing") 7172 public boolean willNotCacheDrawing() { 7173 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 7174 } 7175 7176 /** 7177 * Indicates whether this view reacts to click events or not. 7178 * 7179 * @return true if the view is clickable, false otherwise 7180 * 7181 * @see #setClickable(boolean) 7182 * @attr ref android.R.styleable#View_clickable 7183 */ 7184 @ViewDebug.ExportedProperty 7185 public boolean isClickable() { 7186 return (mViewFlags & CLICKABLE) == CLICKABLE; 7187 } 7188 7189 /** 7190 * Enables or disables click events for this view. When a view 7191 * is clickable it will change its state to "pressed" on every click. 7192 * Subclasses should set the view clickable to visually react to 7193 * user's clicks. 7194 * 7195 * @param clickable true to make the view clickable, false otherwise 7196 * 7197 * @see #isClickable() 7198 * @attr ref android.R.styleable#View_clickable 7199 */ 7200 public void setClickable(boolean clickable) { 7201 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 7202 } 7203 7204 /** 7205 * Indicates whether this view reacts to long click events or not. 7206 * 7207 * @return true if the view is long clickable, false otherwise 7208 * 7209 * @see #setLongClickable(boolean) 7210 * @attr ref android.R.styleable#View_longClickable 7211 */ 7212 public boolean isLongClickable() { 7213 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 7214 } 7215 7216 /** 7217 * Enables or disables long click events for this view. When a view is long 7218 * clickable it reacts to the user holding down the button for a longer 7219 * duration than a tap. This event can either launch the listener or a 7220 * context menu. 7221 * 7222 * @param longClickable true to make the view long clickable, false otherwise 7223 * @see #isLongClickable() 7224 * @attr ref android.R.styleable#View_longClickable 7225 */ 7226 public void setLongClickable(boolean longClickable) { 7227 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 7228 } 7229 7230 /** 7231 * Sets the pressed state for this view and provides a touch coordinate for 7232 * animation hinting. 7233 * 7234 * @param pressed Pass true to set the View's internal state to "pressed", 7235 * or false to reverts the View's internal state from a 7236 * previously set "pressed" state. 7237 * @param x The x coordinate of the touch that caused the press 7238 * @param y The y coordinate of the touch that caused the press 7239 */ 7240 private void setPressed(boolean pressed, float x, float y) { 7241 if (pressed) { 7242 drawableHotspotChanged(x, y); 7243 } 7244 7245 setPressed(pressed); 7246 } 7247 7248 /** 7249 * Sets the pressed state for this view. 7250 * 7251 * @see #isClickable() 7252 * @see #setClickable(boolean) 7253 * 7254 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 7255 * the View's internal state from a previously set "pressed" state. 7256 */ 7257 public void setPressed(boolean pressed) { 7258 final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED); 7259 7260 if (pressed) { 7261 mPrivateFlags |= PFLAG_PRESSED; 7262 } else { 7263 mPrivateFlags &= ~PFLAG_PRESSED; 7264 } 7265 7266 if (needsRefresh) { 7267 refreshDrawableState(); 7268 } 7269 dispatchSetPressed(pressed); 7270 } 7271 7272 /** 7273 * Dispatch setPressed to all of this View's children. 7274 * 7275 * @see #setPressed(boolean) 7276 * 7277 * @param pressed The new pressed state 7278 */ 7279 protected void dispatchSetPressed(boolean pressed) { 7280 } 7281 7282 /** 7283 * Indicates whether the view is currently in pressed state. Unless 7284 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 7285 * the pressed state. 7286 * 7287 * @see #setPressed(boolean) 7288 * @see #isClickable() 7289 * @see #setClickable(boolean) 7290 * 7291 * @return true if the view is currently pressed, false otherwise 7292 */ 7293 @ViewDebug.ExportedProperty 7294 public boolean isPressed() { 7295 return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED; 7296 } 7297 7298 /** 7299 * Indicates whether this view will save its state (that is, 7300 * whether its {@link #onSaveInstanceState} method will be called). 7301 * 7302 * @return Returns true if the view state saving is enabled, else false. 7303 * 7304 * @see #setSaveEnabled(boolean) 7305 * @attr ref android.R.styleable#View_saveEnabled 7306 */ 7307 public boolean isSaveEnabled() { 7308 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 7309 } 7310 7311 /** 7312 * Controls whether the saving of this view's state is 7313 * enabled (that is, whether its {@link #onSaveInstanceState} method 7314 * will be called). Note that even if freezing is enabled, the 7315 * view still must have an id assigned to it (via {@link #setId(int)}) 7316 * for its state to be saved. This flag can only disable the 7317 * saving of this view; any child views may still have their state saved. 7318 * 7319 * @param enabled Set to false to <em>disable</em> state saving, or true 7320 * (the default) to allow it. 7321 * 7322 * @see #isSaveEnabled() 7323 * @see #setId(int) 7324 * @see #onSaveInstanceState() 7325 * @attr ref android.R.styleable#View_saveEnabled 7326 */ 7327 public void setSaveEnabled(boolean enabled) { 7328 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 7329 } 7330 7331 /** 7332 * Gets whether the framework should discard touches when the view's 7333 * window is obscured by another visible window. 7334 * Refer to the {@link View} security documentation for more details. 7335 * 7336 * @return True if touch filtering is enabled. 7337 * 7338 * @see #setFilterTouchesWhenObscured(boolean) 7339 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 7340 */ 7341 @ViewDebug.ExportedProperty 7342 public boolean getFilterTouchesWhenObscured() { 7343 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 7344 } 7345 7346 /** 7347 * Sets whether the framework should discard touches when the view's 7348 * window is obscured by another visible window. 7349 * Refer to the {@link View} security documentation for more details. 7350 * 7351 * @param enabled True if touch filtering should be enabled. 7352 * 7353 * @see #getFilterTouchesWhenObscured 7354 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 7355 */ 7356 public void setFilterTouchesWhenObscured(boolean enabled) { 7357 setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0, 7358 FILTER_TOUCHES_WHEN_OBSCURED); 7359 } 7360 7361 /** 7362 * Indicates whether the entire hierarchy under this view will save its 7363 * state when a state saving traversal occurs from its parent. The default 7364 * is true; if false, these views will not be saved unless 7365 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 7366 * 7367 * @return Returns true if the view state saving from parent is enabled, else false. 7368 * 7369 * @see #setSaveFromParentEnabled(boolean) 7370 */ 7371 public boolean isSaveFromParentEnabled() { 7372 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 7373 } 7374 7375 /** 7376 * Controls whether the entire hierarchy under this view will save its 7377 * state when a state saving traversal occurs from its parent. The default 7378 * is true; if false, these views will not be saved unless 7379 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 7380 * 7381 * @param enabled Set to false to <em>disable</em> state saving, or true 7382 * (the default) to allow it. 7383 * 7384 * @see #isSaveFromParentEnabled() 7385 * @see #setId(int) 7386 * @see #onSaveInstanceState() 7387 */ 7388 public void setSaveFromParentEnabled(boolean enabled) { 7389 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 7390 } 7391 7392 7393 /** 7394 * Returns whether this View is able to take focus. 7395 * 7396 * @return True if this view can take focus, or false otherwise. 7397 * @attr ref android.R.styleable#View_focusable 7398 */ 7399 @ViewDebug.ExportedProperty(category = "focus") 7400 public final boolean isFocusable() { 7401 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 7402 } 7403 7404 /** 7405 * When a view is focusable, it may not want to take focus when in touch mode. 7406 * For example, a button would like focus when the user is navigating via a D-pad 7407 * so that the user can click on it, but once the user starts touching the screen, 7408 * the button shouldn't take focus 7409 * @return Whether the view is focusable in touch mode. 7410 * @attr ref android.R.styleable#View_focusableInTouchMode 7411 */ 7412 @ViewDebug.ExportedProperty 7413 public final boolean isFocusableInTouchMode() { 7414 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 7415 } 7416 7417 /** 7418 * Find the nearest view in the specified direction that can take focus. 7419 * This does not actually give focus to that view. 7420 * 7421 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7422 * 7423 * @return The nearest focusable in the specified direction, or null if none 7424 * can be found. 7425 */ 7426 public View focusSearch(@FocusRealDirection int direction) { 7427 if (mParent != null) { 7428 return mParent.focusSearch(this, direction); 7429 } else { 7430 return null; 7431 } 7432 } 7433 7434 /** 7435 * This method is the last chance for the focused view and its ancestors to 7436 * respond to an arrow key. This is called when the focused view did not 7437 * consume the key internally, nor could the view system find a new view in 7438 * the requested direction to give focus to. 7439 * 7440 * @param focused The currently focused view. 7441 * @param direction The direction focus wants to move. One of FOCUS_UP, 7442 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 7443 * @return True if the this view consumed this unhandled move. 7444 */ 7445 public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) { 7446 return false; 7447 } 7448 7449 /** 7450 * If a user manually specified the next view id for a particular direction, 7451 * use the root to look up the view. 7452 * @param root The root view of the hierarchy containing this view. 7453 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 7454 * or FOCUS_BACKWARD. 7455 * @return The user specified next view, or null if there is none. 7456 */ 7457 View findUserSetNextFocus(View root, @FocusDirection int direction) { 7458 switch (direction) { 7459 case FOCUS_LEFT: 7460 if (mNextFocusLeftId == View.NO_ID) return null; 7461 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 7462 case FOCUS_RIGHT: 7463 if (mNextFocusRightId == View.NO_ID) return null; 7464 return findViewInsideOutShouldExist(root, mNextFocusRightId); 7465 case FOCUS_UP: 7466 if (mNextFocusUpId == View.NO_ID) return null; 7467 return findViewInsideOutShouldExist(root, mNextFocusUpId); 7468 case FOCUS_DOWN: 7469 if (mNextFocusDownId == View.NO_ID) return null; 7470 return findViewInsideOutShouldExist(root, mNextFocusDownId); 7471 case FOCUS_FORWARD: 7472 if (mNextFocusForwardId == View.NO_ID) return null; 7473 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 7474 case FOCUS_BACKWARD: { 7475 if (mID == View.NO_ID) return null; 7476 final int id = mID; 7477 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 7478 @Override 7479 public boolean apply(View t) { 7480 return t.mNextFocusForwardId == id; 7481 } 7482 }); 7483 } 7484 } 7485 return null; 7486 } 7487 7488 private View findViewInsideOutShouldExist(View root, int id) { 7489 if (mMatchIdPredicate == null) { 7490 mMatchIdPredicate = new MatchIdPredicate(); 7491 } 7492 mMatchIdPredicate.mId = id; 7493 View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate); 7494 if (result == null) { 7495 Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id); 7496 } 7497 return result; 7498 } 7499 7500 /** 7501 * Find and return all focusable views that are descendants of this view, 7502 * possibly including this view if it is focusable itself. 7503 * 7504 * @param direction The direction of the focus 7505 * @return A list of focusable views 7506 */ 7507 public ArrayList<View> getFocusables(@FocusDirection int direction) { 7508 ArrayList<View> result = new ArrayList<View>(24); 7509 addFocusables(result, direction); 7510 return result; 7511 } 7512 7513 /** 7514 * Add any focusable views that are descendants of this view (possibly 7515 * including this view if it is focusable itself) to views. If we are in touch mode, 7516 * only add views that are also focusable in touch mode. 7517 * 7518 * @param views Focusable views found so far 7519 * @param direction The direction of the focus 7520 */ 7521 public void addFocusables(ArrayList<View> views, @FocusDirection int direction) { 7522 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 7523 } 7524 7525 /** 7526 * Adds any focusable views that are descendants of this view (possibly 7527 * including this view if it is focusable itself) to views. This method 7528 * adds all focusable views regardless if we are in touch mode or 7529 * only views focusable in touch mode if we are in touch mode or 7530 * only views that can take accessibility focus if accessibility is enabeld 7531 * depending on the focusable mode paramater. 7532 * 7533 * @param views Focusable views found so far or null if all we are interested is 7534 * the number of focusables. 7535 * @param direction The direction of the focus. 7536 * @param focusableMode The type of focusables to be added. 7537 * 7538 * @see #FOCUSABLES_ALL 7539 * @see #FOCUSABLES_TOUCH_MODE 7540 */ 7541 public void addFocusables(ArrayList<View> views, @FocusDirection int direction, 7542 @FocusableMode int focusableMode) { 7543 if (views == null) { 7544 return; 7545 } 7546 if (!isFocusable()) { 7547 return; 7548 } 7549 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE 7550 && isInTouchMode() && !isFocusableInTouchMode()) { 7551 return; 7552 } 7553 views.add(this); 7554 } 7555 7556 /** 7557 * Finds the Views that contain given text. The containment is case insensitive. 7558 * The search is performed by either the text that the View renders or the content 7559 * description that describes the view for accessibility purposes and the view does 7560 * not render or both. Clients can specify how the search is to be performed via 7561 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 7562 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 7563 * 7564 * @param outViews The output list of matching Views. 7565 * @param searched The text to match against. 7566 * 7567 * @see #FIND_VIEWS_WITH_TEXT 7568 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 7569 * @see #setContentDescription(CharSequence) 7570 */ 7571 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, 7572 @FindViewFlags int flags) { 7573 if (getAccessibilityNodeProvider() != null) { 7574 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 7575 outViews.add(this); 7576 } 7577 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 7578 && (searched != null && searched.length() > 0) 7579 && (mContentDescription != null && mContentDescription.length() > 0)) { 7580 String searchedLowerCase = searched.toString().toLowerCase(); 7581 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 7582 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 7583 outViews.add(this); 7584 } 7585 } 7586 } 7587 7588 /** 7589 * Find and return all touchable views that are descendants of this view, 7590 * possibly including this view if it is touchable itself. 7591 * 7592 * @return A list of touchable views 7593 */ 7594 public ArrayList<View> getTouchables() { 7595 ArrayList<View> result = new ArrayList<View>(); 7596 addTouchables(result); 7597 return result; 7598 } 7599 7600 /** 7601 * Add any touchable views that are descendants of this view (possibly 7602 * including this view if it is touchable itself) to views. 7603 * 7604 * @param views Touchable views found so far 7605 */ 7606 public void addTouchables(ArrayList<View> views) { 7607 final int viewFlags = mViewFlags; 7608 7609 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 7610 && (viewFlags & ENABLED_MASK) == ENABLED) { 7611 views.add(this); 7612 } 7613 } 7614 7615 /** 7616 * Returns whether this View is accessibility focused. 7617 * 7618 * @return True if this View is accessibility focused. 7619 */ 7620 public boolean isAccessibilityFocused() { 7621 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0; 7622 } 7623 7624 /** 7625 * Call this to try to give accessibility focus to this view. 7626 * 7627 * A view will not actually take focus if {@link AccessibilityManager#isEnabled()} 7628 * returns false or the view is no visible or the view already has accessibility 7629 * focus. 7630 * 7631 * See also {@link #focusSearch(int)}, which is what you call to say that you 7632 * have focus, and you want your parent to look for the next one. 7633 * 7634 * @return Whether this view actually took accessibility focus. 7635 * 7636 * @hide 7637 */ 7638 public boolean requestAccessibilityFocus() { 7639 AccessibilityManager manager = AccessibilityManager.getInstance(mContext); 7640 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 7641 return false; 7642 } 7643 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7644 return false; 7645 } 7646 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) { 7647 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED; 7648 ViewRootImpl viewRootImpl = getViewRootImpl(); 7649 if (viewRootImpl != null) { 7650 viewRootImpl.setAccessibilityFocus(this, null); 7651 } 7652 invalidate(); 7653 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); 7654 return true; 7655 } 7656 return false; 7657 } 7658 7659 /** 7660 * Call this to try to clear accessibility focus of this view. 7661 * 7662 * See also {@link #focusSearch(int)}, which is what you call to say that you 7663 * have focus, and you want your parent to look for the next one. 7664 * 7665 * @hide 7666 */ 7667 public void clearAccessibilityFocus() { 7668 clearAccessibilityFocusNoCallbacks(); 7669 // Clear the global reference of accessibility focus if this 7670 // view or any of its descendants had accessibility focus. 7671 ViewRootImpl viewRootImpl = getViewRootImpl(); 7672 if (viewRootImpl != null) { 7673 View focusHost = viewRootImpl.getAccessibilityFocusedHost(); 7674 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 7675 viewRootImpl.setAccessibilityFocus(null, null); 7676 } 7677 } 7678 } 7679 7680 private void sendAccessibilityHoverEvent(int eventType) { 7681 // Since we are not delivering to a client accessibility events from not 7682 // important views (unless the clinet request that) we need to fire the 7683 // event from the deepest view exposed to the client. As a consequence if 7684 // the user crosses a not exposed view the client will see enter and exit 7685 // of the exposed predecessor followed by and enter and exit of that same 7686 // predecessor when entering and exiting the not exposed descendant. This 7687 // is fine since the client has a clear idea which view is hovered at the 7688 // price of a couple more events being sent. This is a simple and 7689 // working solution. 7690 View source = this; 7691 while (true) { 7692 if (source.includeForAccessibility()) { 7693 source.sendAccessibilityEvent(eventType); 7694 return; 7695 } 7696 ViewParent parent = source.getParent(); 7697 if (parent instanceof View) { 7698 source = (View) parent; 7699 } else { 7700 return; 7701 } 7702 } 7703 } 7704 7705 /** 7706 * Clears accessibility focus without calling any callback methods 7707 * normally invoked in {@link #clearAccessibilityFocus()}. This method 7708 * is used for clearing accessibility focus when giving this focus to 7709 * another view. 7710 */ 7711 void clearAccessibilityFocusNoCallbacks() { 7712 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 7713 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 7714 invalidate(); 7715 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); 7716 } 7717 } 7718 7719 /** 7720 * Call this to try to give focus to a specific view or to one of its 7721 * descendants. 7722 * 7723 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7724 * false), or if it is focusable and it is not focusable in touch mode 7725 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7726 * 7727 * See also {@link #focusSearch(int)}, which is what you call to say that you 7728 * have focus, and you want your parent to look for the next one. 7729 * 7730 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 7731 * {@link #FOCUS_DOWN} and <code>null</code>. 7732 * 7733 * @return Whether this view or one of its descendants actually took focus. 7734 */ 7735 public final boolean requestFocus() { 7736 return requestFocus(View.FOCUS_DOWN); 7737 } 7738 7739 /** 7740 * Call this to try to give focus to a specific view or to one of its 7741 * descendants and give it a hint about what direction focus is heading. 7742 * 7743 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7744 * false), or if it is focusable and it is not focusable in touch mode 7745 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7746 * 7747 * See also {@link #focusSearch(int)}, which is what you call to say that you 7748 * have focus, and you want your parent to look for the next one. 7749 * 7750 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 7751 * <code>null</code> set for the previously focused rectangle. 7752 * 7753 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7754 * @return Whether this view or one of its descendants actually took focus. 7755 */ 7756 public final boolean requestFocus(int direction) { 7757 return requestFocus(direction, null); 7758 } 7759 7760 /** 7761 * Call this to try to give focus to a specific view or to one of its descendants 7762 * and give it hints about the direction and a specific rectangle that the focus 7763 * is coming from. The rectangle can help give larger views a finer grained hint 7764 * about where focus is coming from, and therefore, where to show selection, or 7765 * forward focus change internally. 7766 * 7767 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7768 * false), or if it is focusable and it is not focusable in touch mode 7769 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7770 * 7771 * A View will not take focus if it is not visible. 7772 * 7773 * A View will not take focus if one of its parents has 7774 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 7775 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 7776 * 7777 * See also {@link #focusSearch(int)}, which is what you call to say that you 7778 * have focus, and you want your parent to look for the next one. 7779 * 7780 * You may wish to override this method if your custom {@link View} has an internal 7781 * {@link View} that it wishes to forward the request to. 7782 * 7783 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7784 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 7785 * to give a finer grained hint about where focus is coming from. May be null 7786 * if there is no hint. 7787 * @return Whether this view or one of its descendants actually took focus. 7788 */ 7789 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 7790 return requestFocusNoSearch(direction, previouslyFocusedRect); 7791 } 7792 7793 private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) { 7794 // need to be focusable 7795 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 7796 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7797 return false; 7798 } 7799 7800 // need to be focusable in touch mode if in touch mode 7801 if (isInTouchMode() && 7802 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 7803 return false; 7804 } 7805 7806 // need to not have any parents blocking us 7807 if (hasAncestorThatBlocksDescendantFocus()) { 7808 return false; 7809 } 7810 7811 handleFocusGainInternal(direction, previouslyFocusedRect); 7812 return true; 7813 } 7814 7815 /** 7816 * Call this to try to give focus to a specific view or to one of its descendants. This is a 7817 * special variant of {@link #requestFocus() } that will allow views that are not focuable in 7818 * touch mode to request focus when they are touched. 7819 * 7820 * @return Whether this view or one of its descendants actually took focus. 7821 * 7822 * @see #isInTouchMode() 7823 * 7824 */ 7825 public final boolean requestFocusFromTouch() { 7826 // Leave touch mode if we need to 7827 if (isInTouchMode()) { 7828 ViewRootImpl viewRoot = getViewRootImpl(); 7829 if (viewRoot != null) { 7830 viewRoot.ensureTouchMode(false); 7831 } 7832 } 7833 return requestFocus(View.FOCUS_DOWN); 7834 } 7835 7836 /** 7837 * @return Whether any ancestor of this view blocks descendant focus. 7838 */ 7839 private boolean hasAncestorThatBlocksDescendantFocus() { 7840 final boolean focusableInTouchMode = isFocusableInTouchMode(); 7841 ViewParent ancestor = mParent; 7842 while (ancestor instanceof ViewGroup) { 7843 final ViewGroup vgAncestor = (ViewGroup) ancestor; 7844 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS 7845 || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) { 7846 return true; 7847 } else { 7848 ancestor = vgAncestor.getParent(); 7849 } 7850 } 7851 return false; 7852 } 7853 7854 /** 7855 * Gets the mode for determining whether this View is important for accessibility 7856 * which is if it fires accessibility events and if it is reported to 7857 * accessibility services that query the screen. 7858 * 7859 * @return The mode for determining whether a View is important for accessibility. 7860 * 7861 * @attr ref android.R.styleable#View_importantForAccessibility 7862 * 7863 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 7864 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 7865 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 7866 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 7867 */ 7868 @ViewDebug.ExportedProperty(category = "accessibility", mapping = { 7869 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"), 7870 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"), 7871 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"), 7872 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS, 7873 to = "noHideDescendants") 7874 }) 7875 public int getImportantForAccessibility() { 7876 return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 7877 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 7878 } 7879 7880 /** 7881 * Sets the live region mode for this view. This indicates to accessibility 7882 * services whether they should automatically notify the user about changes 7883 * to the view's content description or text, or to the content descriptions 7884 * or text of the view's children (where applicable). 7885 * <p> 7886 * For example, in a login screen with a TextView that displays an "incorrect 7887 * password" notification, that view should be marked as a live region with 7888 * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 7889 * <p> 7890 * To disable change notifications for this view, use 7891 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region 7892 * mode for most views. 7893 * <p> 7894 * To indicate that the user should be notified of changes, use 7895 * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 7896 * <p> 7897 * If the view's changes should interrupt ongoing speech and notify the user 7898 * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}. 7899 * 7900 * @param mode The live region mode for this view, one of: 7901 * <ul> 7902 * <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE} 7903 * <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE} 7904 * <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE} 7905 * </ul> 7906 * @attr ref android.R.styleable#View_accessibilityLiveRegion 7907 */ 7908 public void setAccessibilityLiveRegion(int mode) { 7909 if (mode != getAccessibilityLiveRegion()) { 7910 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 7911 mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT) 7912 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 7913 notifyViewAccessibilityStateChangedIfNeeded( 7914 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7915 } 7916 } 7917 7918 /** 7919 * Gets the live region mode for this View. 7920 * 7921 * @return The live region mode for the view. 7922 * 7923 * @attr ref android.R.styleable#View_accessibilityLiveRegion 7924 * 7925 * @see #setAccessibilityLiveRegion(int) 7926 */ 7927 public int getAccessibilityLiveRegion() { 7928 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK) 7929 >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 7930 } 7931 7932 /** 7933 * Sets how to determine whether this view is important for accessibility 7934 * which is if it fires accessibility events and if it is reported to 7935 * accessibility services that query the screen. 7936 * 7937 * @param mode How to determine whether this view is important for accessibility. 7938 * 7939 * @attr ref android.R.styleable#View_importantForAccessibility 7940 * 7941 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 7942 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 7943 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 7944 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 7945 */ 7946 public void setImportantForAccessibility(int mode) { 7947 final int oldMode = getImportantForAccessibility(); 7948 if (mode != oldMode) { 7949 // If we're moving between AUTO and another state, we might not need 7950 // to send a subtree changed notification. We'll store the computed 7951 // importance, since we'll need to check it later to make sure. 7952 final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO 7953 || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO; 7954 final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility(); 7955 mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 7956 mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT) 7957 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 7958 if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) { 7959 notifySubtreeAccessibilityStateChangedIfNeeded(); 7960 } else { 7961 notifyViewAccessibilityStateChangedIfNeeded( 7962 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7963 } 7964 } 7965 } 7966 7967 /** 7968 * Computes whether this view should be exposed for accessibility. In 7969 * general, views that are interactive or provide information are exposed 7970 * while views that serve only as containers are hidden. 7971 * <p> 7972 * If an ancestor of this view has importance 7973 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method 7974 * returns <code>false</code>. 7975 * <p> 7976 * Otherwise, the value is computed according to the view's 7977 * {@link #getImportantForAccessibility()} value: 7978 * <ol> 7979 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or 7980 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false 7981 * </code> 7982 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code> 7983 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if 7984 * view satisfies any of the following: 7985 * <ul> 7986 * <li>Is actionable, e.g. {@link #isClickable()}, 7987 * {@link #isLongClickable()}, or {@link #isFocusable()} 7988 * <li>Has an {@link AccessibilityDelegate} 7989 * <li>Has an interaction listener, e.g. {@link OnTouchListener}, 7990 * {@link OnKeyListener}, etc. 7991 * <li>Is an accessibility live region, e.g. 7992 * {@link #getAccessibilityLiveRegion()} is not 7993 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. 7994 * </ul> 7995 * </ol> 7996 * 7997 * @return Whether the view is exposed for accessibility. 7998 * @see #setImportantForAccessibility(int) 7999 * @see #getImportantForAccessibility() 8000 */ 8001 public boolean isImportantForAccessibility() { 8002 final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 8003 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 8004 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO 8005 || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 8006 return false; 8007 } 8008 8009 // Check parent mode to ensure we're not hidden. 8010 ViewParent parent = mParent; 8011 while (parent instanceof View) { 8012 if (((View) parent).getImportantForAccessibility() 8013 == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 8014 return false; 8015 } 8016 parent = parent.getParent(); 8017 } 8018 8019 return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility() 8020 || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null 8021 || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE; 8022 } 8023 8024 /** 8025 * Gets the parent for accessibility purposes. Note that the parent for 8026 * accessibility is not necessary the immediate parent. It is the first 8027 * predecessor that is important for accessibility. 8028 * 8029 * @return The parent for accessibility purposes. 8030 */ 8031 public ViewParent getParentForAccessibility() { 8032 if (mParent instanceof View) { 8033 View parentView = (View) mParent; 8034 if (parentView.includeForAccessibility()) { 8035 return mParent; 8036 } else { 8037 return mParent.getParentForAccessibility(); 8038 } 8039 } 8040 return null; 8041 } 8042 8043 /** 8044 * Adds the children of a given View for accessibility. Since some Views are 8045 * not important for accessibility the children for accessibility are not 8046 * necessarily direct children of the view, rather they are the first level of 8047 * descendants important for accessibility. 8048 * 8049 * @param children The list of children for accessibility. 8050 */ 8051 public void addChildrenForAccessibility(ArrayList<View> children) { 8052 8053 } 8054 8055 /** 8056 * Whether to regard this view for accessibility. A view is regarded for 8057 * accessibility if it is important for accessibility or the querying 8058 * accessibility service has explicitly requested that view not 8059 * important for accessibility are regarded. 8060 * 8061 * @return Whether to regard the view for accessibility. 8062 * 8063 * @hide 8064 */ 8065 public boolean includeForAccessibility() { 8066 if (mAttachInfo != null) { 8067 return (mAttachInfo.mAccessibilityFetchFlags 8068 & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0 8069 || isImportantForAccessibility(); 8070 } 8071 return false; 8072 } 8073 8074 /** 8075 * Returns whether the View is considered actionable from 8076 * accessibility perspective. Such view are important for 8077 * accessibility. 8078 * 8079 * @return True if the view is actionable for accessibility. 8080 * 8081 * @hide 8082 */ 8083 public boolean isActionableForAccessibility() { 8084 return (isClickable() || isLongClickable() || isFocusable()); 8085 } 8086 8087 /** 8088 * Returns whether the View has registered callbacks which makes it 8089 * important for accessibility. 8090 * 8091 * @return True if the view is actionable for accessibility. 8092 */ 8093 private boolean hasListenersForAccessibility() { 8094 ListenerInfo info = getListenerInfo(); 8095 return mTouchDelegate != null || info.mOnKeyListener != null 8096 || info.mOnTouchListener != null || info.mOnGenericMotionListener != null 8097 || info.mOnHoverListener != null || info.mOnDragListener != null; 8098 } 8099 8100 /** 8101 * Notifies that the accessibility state of this view changed. The change 8102 * is local to this view and does not represent structural changes such 8103 * as children and parent. For example, the view became focusable. The 8104 * notification is at at most once every 8105 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 8106 * to avoid unnecessary load to the system. Also once a view has a pending 8107 * notification this method is a NOP until the notification has been sent. 8108 * 8109 * @hide 8110 */ 8111 public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) { 8112 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 8113 return; 8114 } 8115 if (mSendViewStateChangedAccessibilityEvent == null) { 8116 mSendViewStateChangedAccessibilityEvent = 8117 new SendViewStateChangedAccessibilityEvent(); 8118 } 8119 mSendViewStateChangedAccessibilityEvent.runOrPost(changeType); 8120 } 8121 8122 /** 8123 * Notifies that the accessibility state of this view changed. The change 8124 * is *not* local to this view and does represent structural changes such 8125 * as children and parent. For example, the view size changed. The 8126 * notification is at at most once every 8127 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 8128 * to avoid unnecessary load to the system. Also once a view has a pending 8129 * notification this method is a NOP until the notification has been sent. 8130 * 8131 * @hide 8132 */ 8133 public void notifySubtreeAccessibilityStateChangedIfNeeded() { 8134 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 8135 return; 8136 } 8137 if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) { 8138 mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 8139 if (mParent != null) { 8140 try { 8141 mParent.notifySubtreeAccessibilityStateChanged( 8142 this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE); 8143 } catch (AbstractMethodError e) { 8144 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 8145 " does not fully implement ViewParent", e); 8146 } 8147 } 8148 } 8149 } 8150 8151 /** 8152 * Reset the flag indicating the accessibility state of the subtree rooted 8153 * at this view changed. 8154 */ 8155 void resetSubtreeAccessibilityStateChanged() { 8156 mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 8157 } 8158 8159 /** 8160 * Performs the specified accessibility action on the view. For 8161 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 8162 * <p> 8163 * If an {@link AccessibilityDelegate} has been specified via calling 8164 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 8165 * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)} 8166 * is responsible for handling this call. 8167 * </p> 8168 * 8169 * @param action The action to perform. 8170 * @param arguments Optional action arguments. 8171 * @return Whether the action was performed. 8172 */ 8173 public boolean performAccessibilityAction(int action, Bundle arguments) { 8174 if (mAccessibilityDelegate != null) { 8175 return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments); 8176 } else { 8177 return performAccessibilityActionInternal(action, arguments); 8178 } 8179 } 8180 8181 /** 8182 * @see #performAccessibilityAction(int, Bundle) 8183 * 8184 * Note: Called from the default {@link AccessibilityDelegate}. 8185 */ 8186 boolean performAccessibilityActionInternal(int action, Bundle arguments) { 8187 switch (action) { 8188 case AccessibilityNodeInfo.ACTION_CLICK: { 8189 if (isClickable()) { 8190 performClick(); 8191 return true; 8192 } 8193 } break; 8194 case AccessibilityNodeInfo.ACTION_LONG_CLICK: { 8195 if (isLongClickable()) { 8196 performLongClick(); 8197 return true; 8198 } 8199 } break; 8200 case AccessibilityNodeInfo.ACTION_FOCUS: { 8201 if (!hasFocus()) { 8202 // Get out of touch mode since accessibility 8203 // wants to move focus around. 8204 getViewRootImpl().ensureTouchMode(false); 8205 return requestFocus(); 8206 } 8207 } break; 8208 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 8209 if (hasFocus()) { 8210 clearFocus(); 8211 return !isFocused(); 8212 } 8213 } break; 8214 case AccessibilityNodeInfo.ACTION_SELECT: { 8215 if (!isSelected()) { 8216 setSelected(true); 8217 return isSelected(); 8218 } 8219 } break; 8220 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: { 8221 if (isSelected()) { 8222 setSelected(false); 8223 return !isSelected(); 8224 } 8225 } break; 8226 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 8227 if (!isAccessibilityFocused()) { 8228 return requestAccessibilityFocus(); 8229 } 8230 } break; 8231 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 8232 if (isAccessibilityFocused()) { 8233 clearAccessibilityFocus(); 8234 return true; 8235 } 8236 } break; 8237 case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { 8238 if (arguments != null) { 8239 final int granularity = arguments.getInt( 8240 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 8241 final boolean extendSelection = arguments.getBoolean( 8242 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 8243 return traverseAtGranularity(granularity, true, extendSelection); 8244 } 8245 } break; 8246 case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { 8247 if (arguments != null) { 8248 final int granularity = arguments.getInt( 8249 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 8250 final boolean extendSelection = arguments.getBoolean( 8251 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 8252 return traverseAtGranularity(granularity, false, extendSelection); 8253 } 8254 } break; 8255 case AccessibilityNodeInfo.ACTION_SET_SELECTION: { 8256 CharSequence text = getIterableTextForAccessibility(); 8257 if (text == null) { 8258 return false; 8259 } 8260 final int start = (arguments != null) ? arguments.getInt( 8261 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1; 8262 final int end = (arguments != null) ? arguments.getInt( 8263 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1; 8264 // Only cursor position can be specified (selection length == 0) 8265 if ((getAccessibilitySelectionStart() != start 8266 || getAccessibilitySelectionEnd() != end) 8267 && (start == end)) { 8268 setAccessibilitySelection(start, end); 8269 notifyViewAccessibilityStateChangedIfNeeded( 8270 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 8271 return true; 8272 } 8273 } break; 8274 } 8275 return false; 8276 } 8277 8278 private boolean traverseAtGranularity(int granularity, boolean forward, 8279 boolean extendSelection) { 8280 CharSequence text = getIterableTextForAccessibility(); 8281 if (text == null || text.length() == 0) { 8282 return false; 8283 } 8284 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 8285 if (iterator == null) { 8286 return false; 8287 } 8288 int current = getAccessibilitySelectionEnd(); 8289 if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 8290 current = forward ? 0 : text.length(); 8291 } 8292 final int[] range = forward ? iterator.following(current) : iterator.preceding(current); 8293 if (range == null) { 8294 return false; 8295 } 8296 final int segmentStart = range[0]; 8297 final int segmentEnd = range[1]; 8298 int selectionStart; 8299 int selectionEnd; 8300 if (extendSelection && isAccessibilitySelectionExtendable()) { 8301 selectionStart = getAccessibilitySelectionStart(); 8302 if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 8303 selectionStart = forward ? segmentStart : segmentEnd; 8304 } 8305 selectionEnd = forward ? segmentEnd : segmentStart; 8306 } else { 8307 selectionStart = selectionEnd= forward ? segmentEnd : segmentStart; 8308 } 8309 setAccessibilitySelection(selectionStart, selectionEnd); 8310 final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY 8311 : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY; 8312 sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd); 8313 return true; 8314 } 8315 8316 /** 8317 * Gets the text reported for accessibility purposes. 8318 * 8319 * @return The accessibility text. 8320 * 8321 * @hide 8322 */ 8323 public CharSequence getIterableTextForAccessibility() { 8324 return getContentDescription(); 8325 } 8326 8327 /** 8328 * Gets whether accessibility selection can be extended. 8329 * 8330 * @return If selection is extensible. 8331 * 8332 * @hide 8333 */ 8334 public boolean isAccessibilitySelectionExtendable() { 8335 return false; 8336 } 8337 8338 /** 8339 * @hide 8340 */ 8341 public int getAccessibilitySelectionStart() { 8342 return mAccessibilityCursorPosition; 8343 } 8344 8345 /** 8346 * @hide 8347 */ 8348 public int getAccessibilitySelectionEnd() { 8349 return getAccessibilitySelectionStart(); 8350 } 8351 8352 /** 8353 * @hide 8354 */ 8355 public void setAccessibilitySelection(int start, int end) { 8356 if (start == end && end == mAccessibilityCursorPosition) { 8357 return; 8358 } 8359 if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) { 8360 mAccessibilityCursorPosition = start; 8361 } else { 8362 mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 8363 } 8364 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); 8365 } 8366 8367 private void sendViewTextTraversedAtGranularityEvent(int action, int granularity, 8368 int fromIndex, int toIndex) { 8369 if (mParent == null) { 8370 return; 8371 } 8372 AccessibilityEvent event = AccessibilityEvent.obtain( 8373 AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY); 8374 onInitializeAccessibilityEvent(event); 8375 onPopulateAccessibilityEvent(event); 8376 event.setFromIndex(fromIndex); 8377 event.setToIndex(toIndex); 8378 event.setAction(action); 8379 event.setMovementGranularity(granularity); 8380 mParent.requestSendAccessibilityEvent(this, event); 8381 } 8382 8383 /** 8384 * @hide 8385 */ 8386 public TextSegmentIterator getIteratorForGranularity(int granularity) { 8387 switch (granularity) { 8388 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { 8389 CharSequence text = getIterableTextForAccessibility(); 8390 if (text != null && text.length() > 0) { 8391 CharacterTextSegmentIterator iterator = 8392 CharacterTextSegmentIterator.getInstance( 8393 mContext.getResources().getConfiguration().locale); 8394 iterator.initialize(text.toString()); 8395 return iterator; 8396 } 8397 } break; 8398 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: { 8399 CharSequence text = getIterableTextForAccessibility(); 8400 if (text != null && text.length() > 0) { 8401 WordTextSegmentIterator iterator = 8402 WordTextSegmentIterator.getInstance( 8403 mContext.getResources().getConfiguration().locale); 8404 iterator.initialize(text.toString()); 8405 return iterator; 8406 } 8407 } break; 8408 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: { 8409 CharSequence text = getIterableTextForAccessibility(); 8410 if (text != null && text.length() > 0) { 8411 ParagraphTextSegmentIterator iterator = 8412 ParagraphTextSegmentIterator.getInstance(); 8413 iterator.initialize(text.toString()); 8414 return iterator; 8415 } 8416 } break; 8417 } 8418 return null; 8419 } 8420 8421 /** 8422 * @hide 8423 */ 8424 public void dispatchStartTemporaryDetach() { 8425 onStartTemporaryDetach(); 8426 } 8427 8428 /** 8429 * This is called when a container is going to temporarily detach a child, with 8430 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 8431 * It will either be followed by {@link #onFinishTemporaryDetach()} or 8432 * {@link #onDetachedFromWindow()} when the container is done. 8433 */ 8434 public void onStartTemporaryDetach() { 8435 removeUnsetPressCallback(); 8436 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 8437 } 8438 8439 /** 8440 * @hide 8441 */ 8442 public void dispatchFinishTemporaryDetach() { 8443 onFinishTemporaryDetach(); 8444 } 8445 8446 /** 8447 * Called after {@link #onStartTemporaryDetach} when the container is done 8448 * changing the view. 8449 */ 8450 public void onFinishTemporaryDetach() { 8451 } 8452 8453 /** 8454 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 8455 * for this view's window. Returns null if the view is not currently attached 8456 * to the window. Normally you will not need to use this directly, but 8457 * just use the standard high-level event callbacks like 8458 * {@link #onKeyDown(int, KeyEvent)}. 8459 */ 8460 public KeyEvent.DispatcherState getKeyDispatcherState() { 8461 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 8462 } 8463 8464 /** 8465 * Dispatch a key event before it is processed by any input method 8466 * associated with the view hierarchy. This can be used to intercept 8467 * key events in special situations before the IME consumes them; a 8468 * typical example would be handling the BACK key to update the application's 8469 * UI instead of allowing the IME to see it and close itself. 8470 * 8471 * @param event The key event to be dispatched. 8472 * @return True if the event was handled, false otherwise. 8473 */ 8474 public boolean dispatchKeyEventPreIme(KeyEvent event) { 8475 return onKeyPreIme(event.getKeyCode(), event); 8476 } 8477 8478 /** 8479 * Dispatch a key event to the next view on the focus path. This path runs 8480 * from the top of the view tree down to the currently focused view. If this 8481 * view has focus, it will dispatch to itself. Otherwise it will dispatch 8482 * the next node down the focus path. This method also fires any key 8483 * listeners. 8484 * 8485 * @param event The key event to be dispatched. 8486 * @return True if the event was handled, false otherwise. 8487 */ 8488 public boolean dispatchKeyEvent(KeyEvent event) { 8489 if (mInputEventConsistencyVerifier != null) { 8490 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 8491 } 8492 8493 // Give any attached key listener a first crack at the event. 8494 //noinspection SimplifiableIfStatement 8495 ListenerInfo li = mListenerInfo; 8496 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 8497 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 8498 return true; 8499 } 8500 8501 if (event.dispatch(this, mAttachInfo != null 8502 ? mAttachInfo.mKeyDispatchState : null, this)) { 8503 return true; 8504 } 8505 8506 if (mInputEventConsistencyVerifier != null) { 8507 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8508 } 8509 return false; 8510 } 8511 8512 /** 8513 * Dispatches a key shortcut event. 8514 * 8515 * @param event The key event to be dispatched. 8516 * @return True if the event was handled by the view, false otherwise. 8517 */ 8518 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 8519 return onKeyShortcut(event.getKeyCode(), event); 8520 } 8521 8522 /** 8523 * Pass the touch screen motion event down to the target view, or this 8524 * view if it is the target. 8525 * 8526 * @param event The motion event to be dispatched. 8527 * @return True if the event was handled by the view, false otherwise. 8528 */ 8529 public boolean dispatchTouchEvent(MotionEvent event) { 8530 boolean result = false; 8531 8532 if (mInputEventConsistencyVerifier != null) { 8533 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 8534 } 8535 8536 final int actionMasked = event.getActionMasked(); 8537 if (actionMasked == MotionEvent.ACTION_DOWN) { 8538 // Defensive cleanup for new gesture 8539 stopNestedScroll(); 8540 } 8541 8542 if (onFilterTouchEventForSecurity(event)) { 8543 //noinspection SimplifiableIfStatement 8544 ListenerInfo li = mListenerInfo; 8545 if (li != null && li.mOnTouchListener != null 8546 && (mViewFlags & ENABLED_MASK) == ENABLED 8547 && li.mOnTouchListener.onTouch(this, event)) { 8548 result = true; 8549 } 8550 8551 if (!result && onTouchEvent(event)) { 8552 result = true; 8553 } 8554 } 8555 8556 if (!result && mInputEventConsistencyVerifier != null) { 8557 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8558 } 8559 8560 // Clean up after nested scrolls if this is the end of a gesture; 8561 // also cancel it if we tried an ACTION_DOWN but we didn't want the rest 8562 // of the gesture. 8563 if (actionMasked == MotionEvent.ACTION_UP || 8564 actionMasked == MotionEvent.ACTION_CANCEL || 8565 (actionMasked == MotionEvent.ACTION_DOWN && !result)) { 8566 stopNestedScroll(); 8567 } 8568 8569 return result; 8570 } 8571 8572 /** 8573 * Filter the touch event to apply security policies. 8574 * 8575 * @param event The motion event to be filtered. 8576 * @return True if the event should be dispatched, false if the event should be dropped. 8577 * 8578 * @see #getFilterTouchesWhenObscured 8579 */ 8580 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 8581 //noinspection RedundantIfStatement 8582 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 8583 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 8584 // Window is obscured, drop this touch. 8585 return false; 8586 } 8587 return true; 8588 } 8589 8590 /** 8591 * Pass a trackball motion event down to the focused view. 8592 * 8593 * @param event The motion event to be dispatched. 8594 * @return True if the event was handled by the view, false otherwise. 8595 */ 8596 public boolean dispatchTrackballEvent(MotionEvent event) { 8597 if (mInputEventConsistencyVerifier != null) { 8598 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 8599 } 8600 8601 return onTrackballEvent(event); 8602 } 8603 8604 /** 8605 * Dispatch a generic motion event. 8606 * <p> 8607 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 8608 * are delivered to the view under the pointer. All other generic motion events are 8609 * delivered to the focused view. Hover events are handled specially and are delivered 8610 * to {@link #onHoverEvent(MotionEvent)}. 8611 * </p> 8612 * 8613 * @param event The motion event to be dispatched. 8614 * @return True if the event was handled by the view, false otherwise. 8615 */ 8616 public boolean dispatchGenericMotionEvent(MotionEvent event) { 8617 if (mInputEventConsistencyVerifier != null) { 8618 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 8619 } 8620 8621 final int source = event.getSource(); 8622 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 8623 final int action = event.getAction(); 8624 if (action == MotionEvent.ACTION_HOVER_ENTER 8625 || action == MotionEvent.ACTION_HOVER_MOVE 8626 || action == MotionEvent.ACTION_HOVER_EXIT) { 8627 if (dispatchHoverEvent(event)) { 8628 return true; 8629 } 8630 } else if (dispatchGenericPointerEvent(event)) { 8631 return true; 8632 } 8633 } else if (dispatchGenericFocusedEvent(event)) { 8634 return true; 8635 } 8636 8637 if (dispatchGenericMotionEventInternal(event)) { 8638 return true; 8639 } 8640 8641 if (mInputEventConsistencyVerifier != null) { 8642 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8643 } 8644 return false; 8645 } 8646 8647 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 8648 //noinspection SimplifiableIfStatement 8649 ListenerInfo li = mListenerInfo; 8650 if (li != null && li.mOnGenericMotionListener != null 8651 && (mViewFlags & ENABLED_MASK) == ENABLED 8652 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 8653 return true; 8654 } 8655 8656 if (onGenericMotionEvent(event)) { 8657 return true; 8658 } 8659 8660 if (mInputEventConsistencyVerifier != null) { 8661 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8662 } 8663 return false; 8664 } 8665 8666 /** 8667 * Dispatch a hover event. 8668 * <p> 8669 * Do not call this method directly. 8670 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8671 * </p> 8672 * 8673 * @param event The motion event to be dispatched. 8674 * @return True if the event was handled by the view, false otherwise. 8675 */ 8676 protected boolean dispatchHoverEvent(MotionEvent event) { 8677 ListenerInfo li = mListenerInfo; 8678 //noinspection SimplifiableIfStatement 8679 if (li != null && li.mOnHoverListener != null 8680 && (mViewFlags & ENABLED_MASK) == ENABLED 8681 && li.mOnHoverListener.onHover(this, event)) { 8682 return true; 8683 } 8684 8685 return onHoverEvent(event); 8686 } 8687 8688 /** 8689 * Returns true if the view has a child to which it has recently sent 8690 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 8691 * it does not have a hovered child, then it must be the innermost hovered view. 8692 * @hide 8693 */ 8694 protected boolean hasHoveredChild() { 8695 return false; 8696 } 8697 8698 /** 8699 * Dispatch a generic motion event to the view under the first pointer. 8700 * <p> 8701 * Do not call this method directly. 8702 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8703 * </p> 8704 * 8705 * @param event The motion event to be dispatched. 8706 * @return True if the event was handled by the view, false otherwise. 8707 */ 8708 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 8709 return false; 8710 } 8711 8712 /** 8713 * Dispatch a generic motion event to the currently focused view. 8714 * <p> 8715 * Do not call this method directly. 8716 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8717 * </p> 8718 * 8719 * @param event The motion event to be dispatched. 8720 * @return True if the event was handled by the view, false otherwise. 8721 */ 8722 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 8723 return false; 8724 } 8725 8726 /** 8727 * Dispatch a pointer event. 8728 * <p> 8729 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 8730 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 8731 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 8732 * and should not be expected to handle other pointing device features. 8733 * </p> 8734 * 8735 * @param event The motion event to be dispatched. 8736 * @return True if the event was handled by the view, false otherwise. 8737 * @hide 8738 */ 8739 public final boolean dispatchPointerEvent(MotionEvent event) { 8740 if (event.isTouchEvent()) { 8741 return dispatchTouchEvent(event); 8742 } else { 8743 return dispatchGenericMotionEvent(event); 8744 } 8745 } 8746 8747 /** 8748 * Called when the window containing this view gains or loses window focus. 8749 * ViewGroups should override to route to their children. 8750 * 8751 * @param hasFocus True if the window containing this view now has focus, 8752 * false otherwise. 8753 */ 8754 public void dispatchWindowFocusChanged(boolean hasFocus) { 8755 onWindowFocusChanged(hasFocus); 8756 } 8757 8758 /** 8759 * Called when the window containing this view gains or loses focus. Note 8760 * that this is separate from view focus: to receive key events, both 8761 * your view and its window must have focus. If a window is displayed 8762 * on top of yours that takes input focus, then your own window will lose 8763 * focus but the view focus will remain unchanged. 8764 * 8765 * @param hasWindowFocus True if the window containing this view now has 8766 * focus, false otherwise. 8767 */ 8768 public void onWindowFocusChanged(boolean hasWindowFocus) { 8769 InputMethodManager imm = InputMethodManager.peekInstance(); 8770 if (!hasWindowFocus) { 8771 if (isPressed()) { 8772 setPressed(false); 8773 } 8774 if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 8775 imm.focusOut(this); 8776 } 8777 removeLongPressCallback(); 8778 removeTapCallback(); 8779 onFocusLost(); 8780 } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 8781 imm.focusIn(this); 8782 } 8783 refreshDrawableState(); 8784 } 8785 8786 /** 8787 * Returns true if this view is in a window that currently has window focus. 8788 * Note that this is not the same as the view itself having focus. 8789 * 8790 * @return True if this view is in a window that currently has window focus. 8791 */ 8792 public boolean hasWindowFocus() { 8793 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 8794 } 8795 8796 /** 8797 * Dispatch a view visibility change down the view hierarchy. 8798 * ViewGroups should override to route to their children. 8799 * @param changedView The view whose visibility changed. Could be 'this' or 8800 * an ancestor view. 8801 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 8802 * {@link #INVISIBLE} or {@link #GONE}. 8803 */ 8804 protected void dispatchVisibilityChanged(@NonNull View changedView, 8805 @Visibility int visibility) { 8806 onVisibilityChanged(changedView, visibility); 8807 } 8808 8809 /** 8810 * Called when the visibility of the view or an ancestor of the view is changed. 8811 * @param changedView The view whose visibility changed. Could be 'this' or 8812 * an ancestor view. 8813 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 8814 * {@link #INVISIBLE} or {@link #GONE}. 8815 */ 8816 protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) { 8817 if (visibility == VISIBLE) { 8818 if (mAttachInfo != null) { 8819 initialAwakenScrollBars(); 8820 } else { 8821 mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 8822 } 8823 } 8824 } 8825 8826 /** 8827 * Dispatch a hint about whether this view is displayed. For instance, when 8828 * a View moves out of the screen, it might receives a display hint indicating 8829 * the view is not displayed. Applications should not <em>rely</em> on this hint 8830 * as there is no guarantee that they will receive one. 8831 * 8832 * @param hint A hint about whether or not this view is displayed: 8833 * {@link #VISIBLE} or {@link #INVISIBLE}. 8834 */ 8835 public void dispatchDisplayHint(@Visibility int hint) { 8836 onDisplayHint(hint); 8837 } 8838 8839 /** 8840 * Gives this view a hint about whether is displayed or not. For instance, when 8841 * a View moves out of the screen, it might receives a display hint indicating 8842 * the view is not displayed. Applications should not <em>rely</em> on this hint 8843 * as there is no guarantee that they will receive one. 8844 * 8845 * @param hint A hint about whether or not this view is displayed: 8846 * {@link #VISIBLE} or {@link #INVISIBLE}. 8847 */ 8848 protected void onDisplayHint(@Visibility int hint) { 8849 } 8850 8851 /** 8852 * Dispatch a window visibility change down the view hierarchy. 8853 * ViewGroups should override to route to their children. 8854 * 8855 * @param visibility The new visibility of the window. 8856 * 8857 * @see #onWindowVisibilityChanged(int) 8858 */ 8859 public void dispatchWindowVisibilityChanged(@Visibility int visibility) { 8860 onWindowVisibilityChanged(visibility); 8861 } 8862 8863 /** 8864 * Called when the window containing has change its visibility 8865 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 8866 * that this tells you whether or not your window is being made visible 8867 * to the window manager; this does <em>not</em> tell you whether or not 8868 * your window is obscured by other windows on the screen, even if it 8869 * is itself visible. 8870 * 8871 * @param visibility The new visibility of the window. 8872 */ 8873 protected void onWindowVisibilityChanged(@Visibility int visibility) { 8874 if (visibility == VISIBLE) { 8875 initialAwakenScrollBars(); 8876 } 8877 } 8878 8879 /** 8880 * Returns the current visibility of the window this view is attached to 8881 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 8882 * 8883 * @return Returns the current visibility of the view's window. 8884 */ 8885 @Visibility 8886 public int getWindowVisibility() { 8887 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 8888 } 8889 8890 /** 8891 * Retrieve the overall visible display size in which the window this view is 8892 * attached to has been positioned in. This takes into account screen 8893 * decorations above the window, for both cases where the window itself 8894 * is being position inside of them or the window is being placed under 8895 * then and covered insets are used for the window to position its content 8896 * inside. In effect, this tells you the available area where content can 8897 * be placed and remain visible to users. 8898 * 8899 * <p>This function requires an IPC back to the window manager to retrieve 8900 * the requested information, so should not be used in performance critical 8901 * code like drawing. 8902 * 8903 * @param outRect Filled in with the visible display frame. If the view 8904 * is not attached to a window, this is simply the raw display size. 8905 */ 8906 public void getWindowVisibleDisplayFrame(Rect outRect) { 8907 if (mAttachInfo != null) { 8908 try { 8909 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 8910 } catch (RemoteException e) { 8911 return; 8912 } 8913 // XXX This is really broken, and probably all needs to be done 8914 // in the window manager, and we need to know more about whether 8915 // we want the area behind or in front of the IME. 8916 final Rect insets = mAttachInfo.mVisibleInsets; 8917 outRect.left += insets.left; 8918 outRect.top += insets.top; 8919 outRect.right -= insets.right; 8920 outRect.bottom -= insets.bottom; 8921 return; 8922 } 8923 // The view is not attached to a display so we don't have a context. 8924 // Make a best guess about the display size. 8925 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 8926 d.getRectSize(outRect); 8927 } 8928 8929 /** 8930 * Dispatch a notification about a resource configuration change down 8931 * the view hierarchy. 8932 * ViewGroups should override to route to their children. 8933 * 8934 * @param newConfig The new resource configuration. 8935 * 8936 * @see #onConfigurationChanged(android.content.res.Configuration) 8937 */ 8938 public void dispatchConfigurationChanged(Configuration newConfig) { 8939 onConfigurationChanged(newConfig); 8940 } 8941 8942 /** 8943 * Called when the current configuration of the resources being used 8944 * by the application have changed. You can use this to decide when 8945 * to reload resources that can changed based on orientation and other 8946 * configuration characterstics. You only need to use this if you are 8947 * not relying on the normal {@link android.app.Activity} mechanism of 8948 * recreating the activity instance upon a configuration change. 8949 * 8950 * @param newConfig The new resource configuration. 8951 */ 8952 protected void onConfigurationChanged(Configuration newConfig) { 8953 } 8954 8955 /** 8956 * Private function to aggregate all per-view attributes in to the view 8957 * root. 8958 */ 8959 void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) { 8960 performCollectViewAttributes(attachInfo, visibility); 8961 } 8962 8963 void performCollectViewAttributes(AttachInfo attachInfo, int visibility) { 8964 if ((visibility & VISIBILITY_MASK) == VISIBLE) { 8965 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 8966 attachInfo.mKeepScreenOn = true; 8967 } 8968 attachInfo.mSystemUiVisibility |= mSystemUiVisibility; 8969 ListenerInfo li = mListenerInfo; 8970 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 8971 attachInfo.mHasSystemUiListeners = true; 8972 } 8973 } 8974 } 8975 8976 void needGlobalAttributesUpdate(boolean force) { 8977 final AttachInfo ai = mAttachInfo; 8978 if (ai != null && !ai.mRecomputeGlobalAttributes) { 8979 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 8980 || ai.mHasSystemUiListeners) { 8981 ai.mRecomputeGlobalAttributes = true; 8982 } 8983 } 8984 } 8985 8986 /** 8987 * Returns whether the device is currently in touch mode. Touch mode is entered 8988 * once the user begins interacting with the device by touch, and affects various 8989 * things like whether focus is always visible to the user. 8990 * 8991 * @return Whether the device is in touch mode. 8992 */ 8993 @ViewDebug.ExportedProperty 8994 public boolean isInTouchMode() { 8995 if (mAttachInfo != null) { 8996 return mAttachInfo.mInTouchMode; 8997 } else { 8998 return ViewRootImpl.isInTouchMode(); 8999 } 9000 } 9001 9002 /** 9003 * Returns the context the view is running in, through which it can 9004 * access the current theme, resources, etc. 9005 * 9006 * @return The view's Context. 9007 */ 9008 @ViewDebug.CapturedViewProperty 9009 public final Context getContext() { 9010 return mContext; 9011 } 9012 9013 /** 9014 * Handle a key event before it is processed by any input method 9015 * associated with the view hierarchy. This can be used to intercept 9016 * key events in special situations before the IME consumes them; a 9017 * typical example would be handling the BACK key to update the application's 9018 * UI instead of allowing the IME to see it and close itself. 9019 * 9020 * @param keyCode The value in event.getKeyCode(). 9021 * @param event Description of the key event. 9022 * @return If you handled the event, return true. If you want to allow the 9023 * event to be handled by the next receiver, return false. 9024 */ 9025 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 9026 return false; 9027 } 9028 9029 /** 9030 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 9031 * KeyEvent.Callback.onKeyDown()}: perform press of the view 9032 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 9033 * is released, if the view is enabled and clickable. 9034 * 9035 * <p>Key presses in software keyboards will generally NOT trigger this listener, 9036 * although some may elect to do so in some situations. Do not rely on this to 9037 * catch software key presses. 9038 * 9039 * @param keyCode A key code that represents the button pressed, from 9040 * {@link android.view.KeyEvent}. 9041 * @param event The KeyEvent object that defines the button action. 9042 */ 9043 public boolean onKeyDown(int keyCode, KeyEvent event) { 9044 boolean result = false; 9045 9046 if (KeyEvent.isConfirmKey(keyCode)) { 9047 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 9048 return true; 9049 } 9050 // Long clickable items don't necessarily have to be clickable 9051 if (((mViewFlags & CLICKABLE) == CLICKABLE || 9052 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 9053 (event.getRepeatCount() == 0)) { 9054 setPressed(true); 9055 checkForLongClick(0); 9056 return true; 9057 } 9058 } 9059 return result; 9060 } 9061 9062 /** 9063 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 9064 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 9065 * the event). 9066 * <p>Key presses in software keyboards will generally NOT trigger this listener, 9067 * although some may elect to do so in some situations. Do not rely on this to 9068 * catch software key presses. 9069 */ 9070 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 9071 return false; 9072 } 9073 9074 /** 9075 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 9076 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 9077 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 9078 * {@link KeyEvent#KEYCODE_ENTER} is released. 9079 * <p>Key presses in software keyboards will generally NOT trigger this listener, 9080 * although some may elect to do so in some situations. Do not rely on this to 9081 * catch software key presses. 9082 * 9083 * @param keyCode A key code that represents the button pressed, from 9084 * {@link android.view.KeyEvent}. 9085 * @param event The KeyEvent object that defines the button action. 9086 */ 9087 public boolean onKeyUp(int keyCode, KeyEvent event) { 9088 if (KeyEvent.isConfirmKey(keyCode)) { 9089 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 9090 return true; 9091 } 9092 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 9093 setPressed(false); 9094 9095 if (!mHasPerformedLongPress) { 9096 // This is a tap, so remove the longpress check 9097 removeLongPressCallback(); 9098 return performClick(); 9099 } 9100 } 9101 } 9102 return false; 9103 } 9104 9105 /** 9106 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 9107 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 9108 * the event). 9109 * <p>Key presses in software keyboards will generally NOT trigger this listener, 9110 * although some may elect to do so in some situations. Do not rely on this to 9111 * catch software key presses. 9112 * 9113 * @param keyCode A key code that represents the button pressed, from 9114 * {@link android.view.KeyEvent}. 9115 * @param repeatCount The number of times the action was made. 9116 * @param event The KeyEvent object that defines the button action. 9117 */ 9118 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 9119 return false; 9120 } 9121 9122 /** 9123 * Called on the focused view when a key shortcut event is not handled. 9124 * Override this method to implement local key shortcuts for the View. 9125 * Key shortcuts can also be implemented by setting the 9126 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 9127 * 9128 * @param keyCode The value in event.getKeyCode(). 9129 * @param event Description of the key event. 9130 * @return If you handled the event, return true. If you want to allow the 9131 * event to be handled by the next receiver, return false. 9132 */ 9133 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 9134 return false; 9135 } 9136 9137 /** 9138 * Check whether the called view is a text editor, in which case it 9139 * would make sense to automatically display a soft input window for 9140 * it. Subclasses should override this if they implement 9141 * {@link #onCreateInputConnection(EditorInfo)} to return true if 9142 * a call on that method would return a non-null InputConnection, and 9143 * they are really a first-class editor that the user would normally 9144 * start typing on when the go into a window containing your view. 9145 * 9146 * <p>The default implementation always returns false. This does 9147 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 9148 * will not be called or the user can not otherwise perform edits on your 9149 * view; it is just a hint to the system that this is not the primary 9150 * purpose of this view. 9151 * 9152 * @return Returns true if this view is a text editor, else false. 9153 */ 9154 public boolean onCheckIsTextEditor() { 9155 return false; 9156 } 9157 9158 /** 9159 * Create a new InputConnection for an InputMethod to interact 9160 * with the view. The default implementation returns null, since it doesn't 9161 * support input methods. You can override this to implement such support. 9162 * This is only needed for views that take focus and text input. 9163 * 9164 * <p>When implementing this, you probably also want to implement 9165 * {@link #onCheckIsTextEditor()} to indicate you will return a 9166 * non-null InputConnection.</p> 9167 * 9168 * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo} 9169 * object correctly and in its entirety, so that the connected IME can rely 9170 * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart} 9171 * and {@link android.view.inputmethod.EditorInfo#initialSelEnd} members 9172 * must be filled in with the correct cursor position for IMEs to work correctly 9173 * with your application.</p> 9174 * 9175 * @param outAttrs Fill in with attribute information about the connection. 9176 */ 9177 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 9178 return null; 9179 } 9180 9181 /** 9182 * Called by the {@link android.view.inputmethod.InputMethodManager} 9183 * when a view who is not the current 9184 * input connection target is trying to make a call on the manager. The 9185 * default implementation returns false; you can override this to return 9186 * true for certain views if you are performing InputConnection proxying 9187 * to them. 9188 * @param view The View that is making the InputMethodManager call. 9189 * @return Return true to allow the call, false to reject. 9190 */ 9191 public boolean checkInputConnectionProxy(View view) { 9192 return false; 9193 } 9194 9195 /** 9196 * Show the context menu for this view. It is not safe to hold on to the 9197 * menu after returning from this method. 9198 * 9199 * You should normally not overload this method. Overload 9200 * {@link #onCreateContextMenu(ContextMenu)} or define an 9201 * {@link OnCreateContextMenuListener} to add items to the context menu. 9202 * 9203 * @param menu The context menu to populate 9204 */ 9205 public void createContextMenu(ContextMenu menu) { 9206 ContextMenuInfo menuInfo = getContextMenuInfo(); 9207 9208 // Sets the current menu info so all items added to menu will have 9209 // my extra info set. 9210 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 9211 9212 onCreateContextMenu(menu); 9213 ListenerInfo li = mListenerInfo; 9214 if (li != null && li.mOnCreateContextMenuListener != null) { 9215 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 9216 } 9217 9218 // Clear the extra information so subsequent items that aren't mine don't 9219 // have my extra info. 9220 ((MenuBuilder)menu).setCurrentMenuInfo(null); 9221 9222 if (mParent != null) { 9223 mParent.createContextMenu(menu); 9224 } 9225 } 9226 9227 /** 9228 * Views should implement this if they have extra information to associate 9229 * with the context menu. The return result is supplied as a parameter to 9230 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 9231 * callback. 9232 * 9233 * @return Extra information about the item for which the context menu 9234 * should be shown. This information will vary across different 9235 * subclasses of View. 9236 */ 9237 protected ContextMenuInfo getContextMenuInfo() { 9238 return null; 9239 } 9240 9241 /** 9242 * Views should implement this if the view itself is going to add items to 9243 * the context menu. 9244 * 9245 * @param menu the context menu to populate 9246 */ 9247 protected void onCreateContextMenu(ContextMenu menu) { 9248 } 9249 9250 /** 9251 * Implement this method to handle trackball motion events. The 9252 * <em>relative</em> movement of the trackball since the last event 9253 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 9254 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 9255 * that a movement of 1 corresponds to the user pressing one DPAD key (so 9256 * they will often be fractional values, representing the more fine-grained 9257 * movement information available from a trackball). 9258 * 9259 * @param event The motion event. 9260 * @return True if the event was handled, false otherwise. 9261 */ 9262 public boolean onTrackballEvent(MotionEvent event) { 9263 return false; 9264 } 9265 9266 /** 9267 * Implement this method to handle generic motion events. 9268 * <p> 9269 * Generic motion events describe joystick movements, mouse hovers, track pad 9270 * touches, scroll wheel movements and other input events. The 9271 * {@link MotionEvent#getSource() source} of the motion event specifies 9272 * the class of input that was received. Implementations of this method 9273 * must examine the bits in the source before processing the event. 9274 * The following code example shows how this is done. 9275 * </p><p> 9276 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 9277 * are delivered to the view under the pointer. All other generic motion events are 9278 * delivered to the focused view. 9279 * </p> 9280 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 9281 * if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) { 9282 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 9283 * // process the joystick movement... 9284 * return true; 9285 * } 9286 * } 9287 * if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) { 9288 * switch (event.getAction()) { 9289 * case MotionEvent.ACTION_HOVER_MOVE: 9290 * // process the mouse hover movement... 9291 * return true; 9292 * case MotionEvent.ACTION_SCROLL: 9293 * // process the scroll wheel movement... 9294 * return true; 9295 * } 9296 * } 9297 * return super.onGenericMotionEvent(event); 9298 * }</pre> 9299 * 9300 * @param event The generic motion event being processed. 9301 * @return True if the event was handled, false otherwise. 9302 */ 9303 public boolean onGenericMotionEvent(MotionEvent event) { 9304 return false; 9305 } 9306 9307 /** 9308 * Implement this method to handle hover events. 9309 * <p> 9310 * This method is called whenever a pointer is hovering into, over, or out of the 9311 * bounds of a view and the view is not currently being touched. 9312 * Hover events are represented as pointer events with action 9313 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 9314 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 9315 * </p> 9316 * <ul> 9317 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 9318 * when the pointer enters the bounds of the view.</li> 9319 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 9320 * when the pointer has already entered the bounds of the view and has moved.</li> 9321 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 9322 * when the pointer has exited the bounds of the view or when the pointer is 9323 * about to go down due to a button click, tap, or similar user action that 9324 * causes the view to be touched.</li> 9325 * </ul> 9326 * <p> 9327 * The view should implement this method to return true to indicate that it is 9328 * handling the hover event, such as by changing its drawable state. 9329 * </p><p> 9330 * The default implementation calls {@link #setHovered} to update the hovered state 9331 * of the view when a hover enter or hover exit event is received, if the view 9332 * is enabled and is clickable. The default implementation also sends hover 9333 * accessibility events. 9334 * </p> 9335 * 9336 * @param event The motion event that describes the hover. 9337 * @return True if the view handled the hover event. 9338 * 9339 * @see #isHovered 9340 * @see #setHovered 9341 * @see #onHoverChanged 9342 */ 9343 public boolean onHoverEvent(MotionEvent event) { 9344 // The root view may receive hover (or touch) events that are outside the bounds of 9345 // the window. This code ensures that we only send accessibility events for 9346 // hovers that are actually within the bounds of the root view. 9347 final int action = event.getActionMasked(); 9348 if (!mSendingHoverAccessibilityEvents) { 9349 if ((action == MotionEvent.ACTION_HOVER_ENTER 9350 || action == MotionEvent.ACTION_HOVER_MOVE) 9351 && !hasHoveredChild() 9352 && pointInView(event.getX(), event.getY())) { 9353 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 9354 mSendingHoverAccessibilityEvents = true; 9355 } 9356 } else { 9357 if (action == MotionEvent.ACTION_HOVER_EXIT 9358 || (action == MotionEvent.ACTION_MOVE 9359 && !pointInView(event.getX(), event.getY()))) { 9360 mSendingHoverAccessibilityEvents = false; 9361 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 9362 } 9363 } 9364 9365 if (isHoverable()) { 9366 switch (action) { 9367 case MotionEvent.ACTION_HOVER_ENTER: 9368 setHovered(true); 9369 break; 9370 case MotionEvent.ACTION_HOVER_EXIT: 9371 setHovered(false); 9372 break; 9373 } 9374 9375 // Dispatch the event to onGenericMotionEvent before returning true. 9376 // This is to provide compatibility with existing applications that 9377 // handled HOVER_MOVE events in onGenericMotionEvent and that would 9378 // break because of the new default handling for hoverable views 9379 // in onHoverEvent. 9380 // Note that onGenericMotionEvent will be called by default when 9381 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 9382 dispatchGenericMotionEventInternal(event); 9383 // The event was already handled by calling setHovered(), so always 9384 // return true. 9385 return true; 9386 } 9387 9388 return false; 9389 } 9390 9391 /** 9392 * Returns true if the view should handle {@link #onHoverEvent} 9393 * by calling {@link #setHovered} to change its hovered state. 9394 * 9395 * @return True if the view is hoverable. 9396 */ 9397 private boolean isHoverable() { 9398 final int viewFlags = mViewFlags; 9399 if ((viewFlags & ENABLED_MASK) == DISABLED) { 9400 return false; 9401 } 9402 9403 return (viewFlags & CLICKABLE) == CLICKABLE 9404 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 9405 } 9406 9407 /** 9408 * Returns true if the view is currently hovered. 9409 * 9410 * @return True if the view is currently hovered. 9411 * 9412 * @see #setHovered 9413 * @see #onHoverChanged 9414 */ 9415 @ViewDebug.ExportedProperty 9416 public boolean isHovered() { 9417 return (mPrivateFlags & PFLAG_HOVERED) != 0; 9418 } 9419 9420 /** 9421 * Sets whether the view is currently hovered. 9422 * <p> 9423 * Calling this method also changes the drawable state of the view. This 9424 * enables the view to react to hover by using different drawable resources 9425 * to change its appearance. 9426 * </p><p> 9427 * The {@link #onHoverChanged} method is called when the hovered state changes. 9428 * </p> 9429 * 9430 * @param hovered True if the view is hovered. 9431 * 9432 * @see #isHovered 9433 * @see #onHoverChanged 9434 */ 9435 public void setHovered(boolean hovered) { 9436 if (hovered) { 9437 if ((mPrivateFlags & PFLAG_HOVERED) == 0) { 9438 mPrivateFlags |= PFLAG_HOVERED; 9439 refreshDrawableState(); 9440 onHoverChanged(true); 9441 } 9442 } else { 9443 if ((mPrivateFlags & PFLAG_HOVERED) != 0) { 9444 mPrivateFlags &= ~PFLAG_HOVERED; 9445 refreshDrawableState(); 9446 onHoverChanged(false); 9447 } 9448 } 9449 } 9450 9451 /** 9452 * Implement this method to handle hover state changes. 9453 * <p> 9454 * This method is called whenever the hover state changes as a result of a 9455 * call to {@link #setHovered}. 9456 * </p> 9457 * 9458 * @param hovered The current hover state, as returned by {@link #isHovered}. 9459 * 9460 * @see #isHovered 9461 * @see #setHovered 9462 */ 9463 public void onHoverChanged(boolean hovered) { 9464 } 9465 9466 /** 9467 * Implement this method to handle touch screen motion events. 9468 * <p> 9469 * If this method is used to detect click actions, it is recommended that 9470 * the actions be performed by implementing and calling 9471 * {@link #performClick()}. This will ensure consistent system behavior, 9472 * including: 9473 * <ul> 9474 * <li>obeying click sound preferences 9475 * <li>dispatching OnClickListener calls 9476 * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when 9477 * accessibility features are enabled 9478 * </ul> 9479 * 9480 * @param event The motion event. 9481 * @return True if the event was handled, false otherwise. 9482 */ 9483 public boolean onTouchEvent(MotionEvent event) { 9484 final float x = event.getX(); 9485 final float y = event.getY(); 9486 final int viewFlags = mViewFlags; 9487 9488 if ((viewFlags & ENABLED_MASK) == DISABLED) { 9489 if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { 9490 setPressed(false); 9491 } 9492 // A disabled view that is clickable still consumes the touch 9493 // events, it just doesn't respond to them. 9494 return (((viewFlags & CLICKABLE) == CLICKABLE || 9495 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); 9496 } 9497 9498 if (mTouchDelegate != null) { 9499 if (mTouchDelegate.onTouchEvent(event)) { 9500 return true; 9501 } 9502 } 9503 9504 if (((viewFlags & CLICKABLE) == CLICKABLE || 9505 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { 9506 switch (event.getAction()) { 9507 case MotionEvent.ACTION_UP: 9508 boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; 9509 if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { 9510 // take focus if we don't have it already and we should in 9511 // touch mode. 9512 boolean focusTaken = false; 9513 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 9514 focusTaken = requestFocus(); 9515 } 9516 9517 if (prepressed) { 9518 // The button is being released before we actually 9519 // showed it as pressed. Make it show the pressed 9520 // state now (before scheduling the click) to ensure 9521 // the user sees it. 9522 setPressed(true, x, y); 9523 } 9524 9525 if (!mHasPerformedLongPress) { 9526 // This is a tap, so remove the longpress check 9527 removeLongPressCallback(); 9528 9529 // Only perform take click actions if we were in the pressed state 9530 if (!focusTaken) { 9531 // Use a Runnable and post this rather than calling 9532 // performClick directly. This lets other visual state 9533 // of the view update before click actions start. 9534 if (mPerformClick == null) { 9535 mPerformClick = new PerformClick(); 9536 } 9537 if (!post(mPerformClick)) { 9538 performClick(); 9539 } 9540 } 9541 } 9542 9543 if (mUnsetPressedState == null) { 9544 mUnsetPressedState = new UnsetPressedState(); 9545 } 9546 9547 if (prepressed) { 9548 postDelayed(mUnsetPressedState, 9549 ViewConfiguration.getPressedStateDuration()); 9550 } else if (!post(mUnsetPressedState)) { 9551 // If the post failed, unpress right now 9552 mUnsetPressedState.run(); 9553 } 9554 9555 removeTapCallback(); 9556 } 9557 break; 9558 9559 case MotionEvent.ACTION_DOWN: 9560 mHasPerformedLongPress = false; 9561 9562 if (performButtonActionOnTouchDown(event)) { 9563 break; 9564 } 9565 9566 // Walk up the hierarchy to determine if we're inside a scrolling container. 9567 boolean isInScrollingContainer = isInScrollingContainer(); 9568 9569 // For views inside a scrolling container, delay the pressed feedback for 9570 // a short period in case this is a scroll. 9571 if (isInScrollingContainer) { 9572 mPrivateFlags |= PFLAG_PREPRESSED; 9573 if (mPendingCheckForTap == null) { 9574 mPendingCheckForTap = new CheckForTap(); 9575 } 9576 mPendingCheckForTap.x = event.getX(); 9577 mPendingCheckForTap.y = event.getY(); 9578 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 9579 } else { 9580 // Not inside a scrolling container, so show the feedback right away 9581 setPressed(true, x, y); 9582 checkForLongClick(0); 9583 } 9584 break; 9585 9586 case MotionEvent.ACTION_CANCEL: 9587 setPressed(false); 9588 removeTapCallback(); 9589 removeLongPressCallback(); 9590 break; 9591 9592 case MotionEvent.ACTION_MOVE: 9593 drawableHotspotChanged(x, y); 9594 9595 // Be lenient about moving outside of buttons 9596 if (!pointInView(x, y, mTouchSlop)) { 9597 // Outside button 9598 removeTapCallback(); 9599 if ((mPrivateFlags & PFLAG_PRESSED) != 0) { 9600 // Remove any future long press/tap checks 9601 removeLongPressCallback(); 9602 9603 setPressed(false); 9604 } 9605 } 9606 break; 9607 } 9608 9609 return true; 9610 } 9611 9612 return false; 9613 } 9614 9615 /** 9616 * @hide 9617 */ 9618 public boolean isInScrollingContainer() { 9619 ViewParent p = getParent(); 9620 while (p != null && p instanceof ViewGroup) { 9621 if (((ViewGroup) p).shouldDelayChildPressedState()) { 9622 return true; 9623 } 9624 p = p.getParent(); 9625 } 9626 return false; 9627 } 9628 9629 /** 9630 * Remove the longpress detection timer. 9631 */ 9632 private void removeLongPressCallback() { 9633 if (mPendingCheckForLongPress != null) { 9634 removeCallbacks(mPendingCheckForLongPress); 9635 } 9636 } 9637 9638 /** 9639 * Remove the pending click action 9640 */ 9641 private void removePerformClickCallback() { 9642 if (mPerformClick != null) { 9643 removeCallbacks(mPerformClick); 9644 } 9645 } 9646 9647 /** 9648 * Remove the prepress detection timer. 9649 */ 9650 private void removeUnsetPressCallback() { 9651 if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) { 9652 setPressed(false); 9653 removeCallbacks(mUnsetPressedState); 9654 } 9655 } 9656 9657 /** 9658 * Remove the tap detection timer. 9659 */ 9660 private void removeTapCallback() { 9661 if (mPendingCheckForTap != null) { 9662 mPrivateFlags &= ~PFLAG_PREPRESSED; 9663 removeCallbacks(mPendingCheckForTap); 9664 } 9665 } 9666 9667 /** 9668 * Cancels a pending long press. Your subclass can use this if you 9669 * want the context menu to come up if the user presses and holds 9670 * at the same place, but you don't want it to come up if they press 9671 * and then move around enough to cause scrolling. 9672 */ 9673 public void cancelLongPress() { 9674 removeLongPressCallback(); 9675 9676 /* 9677 * The prepressed state handled by the tap callback is a display 9678 * construct, but the tap callback will post a long press callback 9679 * less its own timeout. Remove it here. 9680 */ 9681 removeTapCallback(); 9682 } 9683 9684 /** 9685 * Remove the pending callback for sending a 9686 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 9687 */ 9688 private void removeSendViewScrolledAccessibilityEventCallback() { 9689 if (mSendViewScrolledAccessibilityEvent != null) { 9690 removeCallbacks(mSendViewScrolledAccessibilityEvent); 9691 mSendViewScrolledAccessibilityEvent.mIsPending = false; 9692 } 9693 } 9694 9695 /** 9696 * Sets the TouchDelegate for this View. 9697 */ 9698 public void setTouchDelegate(TouchDelegate delegate) { 9699 mTouchDelegate = delegate; 9700 } 9701 9702 /** 9703 * Gets the TouchDelegate for this View. 9704 */ 9705 public TouchDelegate getTouchDelegate() { 9706 return mTouchDelegate; 9707 } 9708 9709 /** 9710 * Request unbuffered dispatch of the given stream of MotionEvents to this View. 9711 * 9712 * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input 9713 * system not batch {@link MotionEvent}s but instead deliver them as soon as they're 9714 * available. This method should only be called for touch events. 9715 * 9716 * <p class="note">This api is not intended for most applications. Buffered dispatch 9717 * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent 9718 * streams will not improve your input latency. Side effects include: increased latency, 9719 * jittery scrolls and inability to take advantage of system resampling. Talk to your input 9720 * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for 9721 * you.</p> 9722 */ 9723 public final void requestUnbufferedDispatch(MotionEvent event) { 9724 final int action = event.getAction(); 9725 if (mAttachInfo == null 9726 || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE 9727 || !event.isTouchEvent()) { 9728 return; 9729 } 9730 mAttachInfo.mUnbufferedDispatchRequested = true; 9731 } 9732 9733 /** 9734 * Set flags controlling behavior of this view. 9735 * 9736 * @param flags Constant indicating the value which should be set 9737 * @param mask Constant indicating the bit range that should be changed 9738 */ 9739 void setFlags(int flags, int mask) { 9740 final boolean accessibilityEnabled = 9741 AccessibilityManager.getInstance(mContext).isEnabled(); 9742 final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility(); 9743 9744 int old = mViewFlags; 9745 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 9746 9747 int changed = mViewFlags ^ old; 9748 if (changed == 0) { 9749 return; 9750 } 9751 int privateFlags = mPrivateFlags; 9752 9753 /* Check if the FOCUSABLE bit has changed */ 9754 if (((changed & FOCUSABLE_MASK) != 0) && 9755 ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) { 9756 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 9757 && ((privateFlags & PFLAG_FOCUSED) != 0)) { 9758 /* Give up focus if we are no longer focusable */ 9759 clearFocus(); 9760 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 9761 && ((privateFlags & PFLAG_FOCUSED) == 0)) { 9762 /* 9763 * Tell the view system that we are now available to take focus 9764 * if no one else already has it. 9765 */ 9766 if (mParent != null) mParent.focusableViewAvailable(this); 9767 } 9768 } 9769 9770 final int newVisibility = flags & VISIBILITY_MASK; 9771 if (newVisibility == VISIBLE) { 9772 if ((changed & VISIBILITY_MASK) != 0) { 9773 /* 9774 * If this view is becoming visible, invalidate it in case it changed while 9775 * it was not visible. Marking it drawn ensures that the invalidation will 9776 * go through. 9777 */ 9778 mPrivateFlags |= PFLAG_DRAWN; 9779 invalidate(true); 9780 9781 needGlobalAttributesUpdate(true); 9782 9783 // a view becoming visible is worth notifying the parent 9784 // about in case nothing has focus. even if this specific view 9785 // isn't focusable, it may contain something that is, so let 9786 // the root view try to give this focus if nothing else does. 9787 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 9788 mParent.focusableViewAvailable(this); 9789 } 9790 } 9791 } 9792 9793 /* Check if the GONE bit has changed */ 9794 if ((changed & GONE) != 0) { 9795 needGlobalAttributesUpdate(false); 9796 requestLayout(); 9797 9798 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 9799 if (hasFocus()) clearFocus(); 9800 clearAccessibilityFocus(); 9801 destroyDrawingCache(); 9802 if (mParent instanceof View) { 9803 // GONE views noop invalidation, so invalidate the parent 9804 ((View) mParent).invalidate(true); 9805 } 9806 // Mark the view drawn to ensure that it gets invalidated properly the next 9807 // time it is visible and gets invalidated 9808 mPrivateFlags |= PFLAG_DRAWN; 9809 } 9810 if (mAttachInfo != null) { 9811 mAttachInfo.mViewVisibilityChanged = true; 9812 } 9813 } 9814 9815 /* Check if the VISIBLE bit has changed */ 9816 if ((changed & INVISIBLE) != 0) { 9817 needGlobalAttributesUpdate(false); 9818 /* 9819 * If this view is becoming invisible, set the DRAWN flag so that 9820 * the next invalidate() will not be skipped. 9821 */ 9822 mPrivateFlags |= PFLAG_DRAWN; 9823 9824 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) { 9825 // root view becoming invisible shouldn't clear focus and accessibility focus 9826 if (getRootView() != this) { 9827 if (hasFocus()) clearFocus(); 9828 clearAccessibilityFocus(); 9829 } 9830 } 9831 if (mAttachInfo != null) { 9832 mAttachInfo.mViewVisibilityChanged = true; 9833 } 9834 } 9835 9836 if ((changed & VISIBILITY_MASK) != 0) { 9837 // If the view is invisible, cleanup its display list to free up resources 9838 if (newVisibility != VISIBLE && mAttachInfo != null) { 9839 cleanupDraw(); 9840 } 9841 9842 if (mParent instanceof ViewGroup) { 9843 ((ViewGroup) mParent).onChildVisibilityChanged(this, 9844 (changed & VISIBILITY_MASK), newVisibility); 9845 ((View) mParent).invalidate(true); 9846 } else if (mParent != null) { 9847 mParent.invalidateChild(this, null); 9848 } 9849 dispatchVisibilityChanged(this, newVisibility); 9850 9851 notifySubtreeAccessibilityStateChangedIfNeeded(); 9852 } 9853 9854 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 9855 destroyDrawingCache(); 9856 } 9857 9858 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 9859 destroyDrawingCache(); 9860 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 9861 invalidateParentCaches(); 9862 } 9863 9864 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 9865 destroyDrawingCache(); 9866 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 9867 } 9868 9869 if ((changed & DRAW_MASK) != 0) { 9870 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 9871 if (mBackground != null) { 9872 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 9873 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 9874 } else { 9875 mPrivateFlags |= PFLAG_SKIP_DRAW; 9876 } 9877 } else { 9878 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 9879 } 9880 requestLayout(); 9881 invalidate(true); 9882 } 9883 9884 if ((changed & KEEP_SCREEN_ON) != 0) { 9885 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 9886 mParent.recomputeViewAttributes(this); 9887 } 9888 } 9889 9890 if (accessibilityEnabled) { 9891 if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0 9892 || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) { 9893 if (oldIncludeForAccessibility != includeForAccessibility()) { 9894 notifySubtreeAccessibilityStateChangedIfNeeded(); 9895 } else { 9896 notifyViewAccessibilityStateChangedIfNeeded( 9897 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9898 } 9899 } else if ((changed & ENABLED_MASK) != 0) { 9900 notifyViewAccessibilityStateChangedIfNeeded( 9901 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9902 } 9903 } 9904 } 9905 9906 /** 9907 * Change the view's z order in the tree, so it's on top of other sibling 9908 * views. This ordering change may affect layout, if the parent container 9909 * uses an order-dependent layout scheme (e.g., LinearLayout). Prior 9910 * to {@link android.os.Build.VERSION_CODES#KITKAT} this 9911 * method should be followed by calls to {@link #requestLayout()} and 9912 * {@link View#invalidate()} on the view's parent to force the parent to redraw 9913 * with the new child ordering. 9914 * 9915 * @see ViewGroup#bringChildToFront(View) 9916 */ 9917 public void bringToFront() { 9918 if (mParent != null) { 9919 mParent.bringChildToFront(this); 9920 } 9921 } 9922 9923 /** 9924 * This is called in response to an internal scroll in this view (i.e., the 9925 * view scrolled its own contents). This is typically as a result of 9926 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 9927 * called. 9928 * 9929 * @param l Current horizontal scroll origin. 9930 * @param t Current vertical scroll origin. 9931 * @param oldl Previous horizontal scroll origin. 9932 * @param oldt Previous vertical scroll origin. 9933 */ 9934 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 9935 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 9936 postSendViewScrolledAccessibilityEventCallback(); 9937 } 9938 9939 mBackgroundSizeChanged = true; 9940 9941 final AttachInfo ai = mAttachInfo; 9942 if (ai != null) { 9943 ai.mViewScrollChanged = true; 9944 } 9945 9946 if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) { 9947 mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt); 9948 } 9949 } 9950 9951 /** 9952 * Interface definition for a callback to be invoked when the scroll 9953 * position of a view changes. 9954 * 9955 * @hide Only used internally. 9956 */ 9957 public interface OnScrollChangeListener { 9958 /** 9959 * Called when the scroll position of a view changes. 9960 * 9961 * @param v The view whose scroll position has changed. 9962 * @param scrollX Current horizontal scroll origin. 9963 * @param scrollY Current vertical scroll origin. 9964 * @param oldScrollX Previous horizontal scroll origin. 9965 * @param oldScrollY Previous vertical scroll origin. 9966 */ 9967 void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY); 9968 } 9969 9970 /** 9971 * Interface definition for a callback to be invoked when the layout bounds of a view 9972 * changes due to layout processing. 9973 */ 9974 public interface OnLayoutChangeListener { 9975 /** 9976 * Called when the layout bounds of a view changes due to layout processing. 9977 * 9978 * @param v The view whose bounds have changed. 9979 * @param left The new value of the view's left property. 9980 * @param top The new value of the view's top property. 9981 * @param right The new value of the view's right property. 9982 * @param bottom The new value of the view's bottom property. 9983 * @param oldLeft The previous value of the view's left property. 9984 * @param oldTop The previous value of the view's top property. 9985 * @param oldRight The previous value of the view's right property. 9986 * @param oldBottom The previous value of the view's bottom property. 9987 */ 9988 void onLayoutChange(View v, int left, int top, int right, int bottom, 9989 int oldLeft, int oldTop, int oldRight, int oldBottom); 9990 } 9991 9992 /** 9993 * This is called during layout when the size of this view has changed. If 9994 * you were just added to the view hierarchy, you're called with the old 9995 * values of 0. 9996 * 9997 * @param w Current width of this view. 9998 * @param h Current height of this view. 9999 * @param oldw Old width of this view. 10000 * @param oldh Old height of this view. 10001 */ 10002 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 10003 } 10004 10005 /** 10006 * Called by draw to draw the child views. This may be overridden 10007 * by derived classes to gain control just before its children are drawn 10008 * (but after its own view has been drawn). 10009 * @param canvas the canvas on which to draw the view 10010 */ 10011 protected void dispatchDraw(Canvas canvas) { 10012 10013 } 10014 10015 /** 10016 * Gets the parent of this view. Note that the parent is a 10017 * ViewParent and not necessarily a View. 10018 * 10019 * @return Parent of this view. 10020 */ 10021 public final ViewParent getParent() { 10022 return mParent; 10023 } 10024 10025 /** 10026 * Set the horizontal scrolled position of your view. This will cause a call to 10027 * {@link #onScrollChanged(int, int, int, int)} and the view will be 10028 * invalidated. 10029 * @param value the x position to scroll to 10030 */ 10031 public void setScrollX(int value) { 10032 scrollTo(value, mScrollY); 10033 } 10034 10035 /** 10036 * Set the vertical scrolled position of your view. This will cause a call to 10037 * {@link #onScrollChanged(int, int, int, int)} and the view will be 10038 * invalidated. 10039 * @param value the y position to scroll to 10040 */ 10041 public void setScrollY(int value) { 10042 scrollTo(mScrollX, value); 10043 } 10044 10045 /** 10046 * Return the scrolled left position of this view. This is the left edge of 10047 * the displayed part of your view. You do not need to draw any pixels 10048 * farther left, since those are outside of the frame of your view on 10049 * screen. 10050 * 10051 * @return The left edge of the displayed part of your view, in pixels. 10052 */ 10053 public final int getScrollX() { 10054 return mScrollX; 10055 } 10056 10057 /** 10058 * Return the scrolled top position of this view. This is the top edge of 10059 * the displayed part of your view. You do not need to draw any pixels above 10060 * it, since those are outside of the frame of your view on screen. 10061 * 10062 * @return The top edge of the displayed part of your view, in pixels. 10063 */ 10064 public final int getScrollY() { 10065 return mScrollY; 10066 } 10067 10068 /** 10069 * Return the width of the your view. 10070 * 10071 * @return The width of your view, in pixels. 10072 */ 10073 @ViewDebug.ExportedProperty(category = "layout") 10074 public final int getWidth() { 10075 return mRight - mLeft; 10076 } 10077 10078 /** 10079 * Return the height of your view. 10080 * 10081 * @return The height of your view, in pixels. 10082 */ 10083 @ViewDebug.ExportedProperty(category = "layout") 10084 public final int getHeight() { 10085 return mBottom - mTop; 10086 } 10087 10088 /** 10089 * Return the visible drawing bounds of your view. Fills in the output 10090 * rectangle with the values from getScrollX(), getScrollY(), 10091 * getWidth(), and getHeight(). These bounds do not account for any 10092 * transformation properties currently set on the view, such as 10093 * {@link #setScaleX(float)} or {@link #setRotation(float)}. 10094 * 10095 * @param outRect The (scrolled) drawing bounds of the view. 10096 */ 10097 public void getDrawingRect(Rect outRect) { 10098 outRect.left = mScrollX; 10099 outRect.top = mScrollY; 10100 outRect.right = mScrollX + (mRight - mLeft); 10101 outRect.bottom = mScrollY + (mBottom - mTop); 10102 } 10103 10104 /** 10105 * Like {@link #getMeasuredWidthAndState()}, but only returns the 10106 * raw width component (that is the result is masked by 10107 * {@link #MEASURED_SIZE_MASK}). 10108 * 10109 * @return The raw measured width of this view. 10110 */ 10111 public final int getMeasuredWidth() { 10112 return mMeasuredWidth & MEASURED_SIZE_MASK; 10113 } 10114 10115 /** 10116 * Return the full width measurement information for this view as computed 10117 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 10118 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 10119 * This should be used during measurement and layout calculations only. Use 10120 * {@link #getWidth()} to see how wide a view is after layout. 10121 * 10122 * @return The measured width of this view as a bit mask. 10123 */ 10124 public final int getMeasuredWidthAndState() { 10125 return mMeasuredWidth; 10126 } 10127 10128 /** 10129 * Like {@link #getMeasuredHeightAndState()}, but only returns the 10130 * raw width component (that is the result is masked by 10131 * {@link #MEASURED_SIZE_MASK}). 10132 * 10133 * @return The raw measured height of this view. 10134 */ 10135 public final int getMeasuredHeight() { 10136 return mMeasuredHeight & MEASURED_SIZE_MASK; 10137 } 10138 10139 /** 10140 * Return the full height measurement information for this view as computed 10141 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 10142 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 10143 * This should be used during measurement and layout calculations only. Use 10144 * {@link #getHeight()} to see how wide a view is after layout. 10145 * 10146 * @return The measured width of this view as a bit mask. 10147 */ 10148 public final int getMeasuredHeightAndState() { 10149 return mMeasuredHeight; 10150 } 10151 10152 /** 10153 * Return only the state bits of {@link #getMeasuredWidthAndState()} 10154 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 10155 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 10156 * and the height component is at the shifted bits 10157 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 10158 */ 10159 public final int getMeasuredState() { 10160 return (mMeasuredWidth&MEASURED_STATE_MASK) 10161 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 10162 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 10163 } 10164 10165 /** 10166 * The transform matrix of this view, which is calculated based on the current 10167 * rotation, scale, and pivot properties. 10168 * 10169 * @see #getRotation() 10170 * @see #getScaleX() 10171 * @see #getScaleY() 10172 * @see #getPivotX() 10173 * @see #getPivotY() 10174 * @return The current transform matrix for the view 10175 */ 10176 public Matrix getMatrix() { 10177 ensureTransformationInfo(); 10178 final Matrix matrix = mTransformationInfo.mMatrix; 10179 mRenderNode.getMatrix(matrix); 10180 return matrix; 10181 } 10182 10183 /** 10184 * Returns true if the transform matrix is the identity matrix. 10185 * Recomputes the matrix if necessary. 10186 * 10187 * @return True if the transform matrix is the identity matrix, false otherwise. 10188 */ 10189 final boolean hasIdentityMatrix() { 10190 return mRenderNode.hasIdentityMatrix(); 10191 } 10192 10193 void ensureTransformationInfo() { 10194 if (mTransformationInfo == null) { 10195 mTransformationInfo = new TransformationInfo(); 10196 } 10197 } 10198 10199 /** 10200 * Utility method to retrieve the inverse of the current mMatrix property. 10201 * We cache the matrix to avoid recalculating it when transform properties 10202 * have not changed. 10203 * 10204 * @return The inverse of the current matrix of this view. 10205 * @hide 10206 */ 10207 public final Matrix getInverseMatrix() { 10208 ensureTransformationInfo(); 10209 if (mTransformationInfo.mInverseMatrix == null) { 10210 mTransformationInfo.mInverseMatrix = new Matrix(); 10211 } 10212 final Matrix matrix = mTransformationInfo.mInverseMatrix; 10213 mRenderNode.getInverseMatrix(matrix); 10214 return matrix; 10215 } 10216 10217 /** 10218 * Gets the distance along the Z axis from the camera to this view. 10219 * 10220 * @see #setCameraDistance(float) 10221 * 10222 * @return The distance along the Z axis. 10223 */ 10224 public float getCameraDistance() { 10225 final float dpi = mResources.getDisplayMetrics().densityDpi; 10226 return -(mRenderNode.getCameraDistance() * dpi); 10227 } 10228 10229 /** 10230 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 10231 * views are drawn) from the camera to this view. The camera's distance 10232 * affects 3D transformations, for instance rotations around the X and Y 10233 * axis. If the rotationX or rotationY properties are changed and this view is 10234 * large (more than half the size of the screen), it is recommended to always 10235 * use a camera distance that's greater than the height (X axis rotation) or 10236 * the width (Y axis rotation) of this view.</p> 10237 * 10238 * <p>The distance of the camera from the view plane can have an affect on the 10239 * perspective distortion of the view when it is rotated around the x or y axis. 10240 * For example, a large distance will result in a large viewing angle, and there 10241 * will not be much perspective distortion of the view as it rotates. A short 10242 * distance may cause much more perspective distortion upon rotation, and can 10243 * also result in some drawing artifacts if the rotated view ends up partially 10244 * behind the camera (which is why the recommendation is to use a distance at 10245 * least as far as the size of the view, if the view is to be rotated.)</p> 10246 * 10247 * <p>The distance is expressed in "depth pixels." The default distance depends 10248 * on the screen density. For instance, on a medium density display, the 10249 * default distance is 1280. On a high density display, the default distance 10250 * is 1920.</p> 10251 * 10252 * <p>If you want to specify a distance that leads to visually consistent 10253 * results across various densities, use the following formula:</p> 10254 * <pre> 10255 * float scale = context.getResources().getDisplayMetrics().density; 10256 * view.setCameraDistance(distance * scale); 10257 * </pre> 10258 * 10259 * <p>The density scale factor of a high density display is 1.5, 10260 * and 1920 = 1280 * 1.5.</p> 10261 * 10262 * @param distance The distance in "depth pixels", if negative the opposite 10263 * value is used 10264 * 10265 * @see #setRotationX(float) 10266 * @see #setRotationY(float) 10267 */ 10268 public void setCameraDistance(float distance) { 10269 final float dpi = mResources.getDisplayMetrics().densityDpi; 10270 10271 invalidateViewProperty(true, false); 10272 mRenderNode.setCameraDistance(-Math.abs(distance) / dpi); 10273 invalidateViewProperty(false, false); 10274 10275 invalidateParentIfNeededAndWasQuickRejected(); 10276 } 10277 10278 /** 10279 * The degrees that the view is rotated around the pivot point. 10280 * 10281 * @see #setRotation(float) 10282 * @see #getPivotX() 10283 * @see #getPivotY() 10284 * 10285 * @return The degrees of rotation. 10286 */ 10287 @ViewDebug.ExportedProperty(category = "drawing") 10288 public float getRotation() { 10289 return mRenderNode.getRotation(); 10290 } 10291 10292 /** 10293 * Sets the degrees that the view is rotated around the pivot point. Increasing values 10294 * result in clockwise rotation. 10295 * 10296 * @param rotation The degrees of rotation. 10297 * 10298 * @see #getRotation() 10299 * @see #getPivotX() 10300 * @see #getPivotY() 10301 * @see #setRotationX(float) 10302 * @see #setRotationY(float) 10303 * 10304 * @attr ref android.R.styleable#View_rotation 10305 */ 10306 public void setRotation(float rotation) { 10307 if (rotation != getRotation()) { 10308 // Double-invalidation is necessary to capture view's old and new areas 10309 invalidateViewProperty(true, false); 10310 mRenderNode.setRotation(rotation); 10311 invalidateViewProperty(false, true); 10312 10313 invalidateParentIfNeededAndWasQuickRejected(); 10314 notifySubtreeAccessibilityStateChangedIfNeeded(); 10315 } 10316 } 10317 10318 /** 10319 * The degrees that the view is rotated around the vertical axis through the pivot point. 10320 * 10321 * @see #getPivotX() 10322 * @see #getPivotY() 10323 * @see #setRotationY(float) 10324 * 10325 * @return The degrees of Y rotation. 10326 */ 10327 @ViewDebug.ExportedProperty(category = "drawing") 10328 public float getRotationY() { 10329 return mRenderNode.getRotationY(); 10330 } 10331 10332 /** 10333 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 10334 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 10335 * down the y axis. 10336 * 10337 * When rotating large views, it is recommended to adjust the camera distance 10338 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 10339 * 10340 * @param rotationY The degrees of Y rotation. 10341 * 10342 * @see #getRotationY() 10343 * @see #getPivotX() 10344 * @see #getPivotY() 10345 * @see #setRotation(float) 10346 * @see #setRotationX(float) 10347 * @see #setCameraDistance(float) 10348 * 10349 * @attr ref android.R.styleable#View_rotationY 10350 */ 10351 public void setRotationY(float rotationY) { 10352 if (rotationY != getRotationY()) { 10353 invalidateViewProperty(true, false); 10354 mRenderNode.setRotationY(rotationY); 10355 invalidateViewProperty(false, true); 10356 10357 invalidateParentIfNeededAndWasQuickRejected(); 10358 notifySubtreeAccessibilityStateChangedIfNeeded(); 10359 } 10360 } 10361 10362 /** 10363 * The degrees that the view is rotated around the horizontal axis through the pivot point. 10364 * 10365 * @see #getPivotX() 10366 * @see #getPivotY() 10367 * @see #setRotationX(float) 10368 * 10369 * @return The degrees of X rotation. 10370 */ 10371 @ViewDebug.ExportedProperty(category = "drawing") 10372 public float getRotationX() { 10373 return mRenderNode.getRotationX(); 10374 } 10375 10376 /** 10377 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 10378 * Increasing values result in clockwise rotation from the viewpoint of looking down the 10379 * x axis. 10380 * 10381 * When rotating large views, it is recommended to adjust the camera distance 10382 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 10383 * 10384 * @param rotationX The degrees of X rotation. 10385 * 10386 * @see #getRotationX() 10387 * @see #getPivotX() 10388 * @see #getPivotY() 10389 * @see #setRotation(float) 10390 * @see #setRotationY(float) 10391 * @see #setCameraDistance(float) 10392 * 10393 * @attr ref android.R.styleable#View_rotationX 10394 */ 10395 public void setRotationX(float rotationX) { 10396 if (rotationX != getRotationX()) { 10397 invalidateViewProperty(true, false); 10398 mRenderNode.setRotationX(rotationX); 10399 invalidateViewProperty(false, true); 10400 10401 invalidateParentIfNeededAndWasQuickRejected(); 10402 notifySubtreeAccessibilityStateChangedIfNeeded(); 10403 } 10404 } 10405 10406 /** 10407 * The amount that the view is scaled in x around the pivot point, as a proportion of 10408 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 10409 * 10410 * <p>By default, this is 1.0f. 10411 * 10412 * @see #getPivotX() 10413 * @see #getPivotY() 10414 * @return The scaling factor. 10415 */ 10416 @ViewDebug.ExportedProperty(category = "drawing") 10417 public float getScaleX() { 10418 return mRenderNode.getScaleX(); 10419 } 10420 10421 /** 10422 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 10423 * the view's unscaled width. A value of 1 means that no scaling is applied. 10424 * 10425 * @param scaleX The scaling factor. 10426 * @see #getPivotX() 10427 * @see #getPivotY() 10428 * 10429 * @attr ref android.R.styleable#View_scaleX 10430 */ 10431 public void setScaleX(float scaleX) { 10432 if (scaleX != getScaleX()) { 10433 invalidateViewProperty(true, false); 10434 mRenderNode.setScaleX(scaleX); 10435 invalidateViewProperty(false, true); 10436 10437 invalidateParentIfNeededAndWasQuickRejected(); 10438 notifySubtreeAccessibilityStateChangedIfNeeded(); 10439 } 10440 } 10441 10442 /** 10443 * The amount that the view is scaled in y around the pivot point, as a proportion of 10444 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 10445 * 10446 * <p>By default, this is 1.0f. 10447 * 10448 * @see #getPivotX() 10449 * @see #getPivotY() 10450 * @return The scaling factor. 10451 */ 10452 @ViewDebug.ExportedProperty(category = "drawing") 10453 public float getScaleY() { 10454 return mRenderNode.getScaleY(); 10455 } 10456 10457 /** 10458 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 10459 * the view's unscaled width. A value of 1 means that no scaling is applied. 10460 * 10461 * @param scaleY The scaling factor. 10462 * @see #getPivotX() 10463 * @see #getPivotY() 10464 * 10465 * @attr ref android.R.styleable#View_scaleY 10466 */ 10467 public void setScaleY(float scaleY) { 10468 if (scaleY != getScaleY()) { 10469 invalidateViewProperty(true, false); 10470 mRenderNode.setScaleY(scaleY); 10471 invalidateViewProperty(false, true); 10472 10473 invalidateParentIfNeededAndWasQuickRejected(); 10474 notifySubtreeAccessibilityStateChangedIfNeeded(); 10475 } 10476 } 10477 10478 /** 10479 * The x location of the point around which the view is {@link #setRotation(float) rotated} 10480 * and {@link #setScaleX(float) scaled}. 10481 * 10482 * @see #getRotation() 10483 * @see #getScaleX() 10484 * @see #getScaleY() 10485 * @see #getPivotY() 10486 * @return The x location of the pivot point. 10487 * 10488 * @attr ref android.R.styleable#View_transformPivotX 10489 */ 10490 @ViewDebug.ExportedProperty(category = "drawing") 10491 public float getPivotX() { 10492 return mRenderNode.getPivotX(); 10493 } 10494 10495 /** 10496 * Sets the x location of the point around which the view is 10497 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 10498 * By default, the pivot point is centered on the object. 10499 * Setting this property disables this behavior and causes the view to use only the 10500 * explicitly set pivotX and pivotY values. 10501 * 10502 * @param pivotX The x location of the pivot point. 10503 * @see #getRotation() 10504 * @see #getScaleX() 10505 * @see #getScaleY() 10506 * @see #getPivotY() 10507 * 10508 * @attr ref android.R.styleable#View_transformPivotX 10509 */ 10510 public void setPivotX(float pivotX) { 10511 if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) { 10512 invalidateViewProperty(true, false); 10513 mRenderNode.setPivotX(pivotX); 10514 invalidateViewProperty(false, true); 10515 10516 invalidateParentIfNeededAndWasQuickRejected(); 10517 } 10518 } 10519 10520 /** 10521 * The y location of the point around which the view is {@link #setRotation(float) rotated} 10522 * and {@link #setScaleY(float) scaled}. 10523 * 10524 * @see #getRotation() 10525 * @see #getScaleX() 10526 * @see #getScaleY() 10527 * @see #getPivotY() 10528 * @return The y location of the pivot point. 10529 * 10530 * @attr ref android.R.styleable#View_transformPivotY 10531 */ 10532 @ViewDebug.ExportedProperty(category = "drawing") 10533 public float getPivotY() { 10534 return mRenderNode.getPivotY(); 10535 } 10536 10537 /** 10538 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 10539 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 10540 * Setting this property disables this behavior and causes the view to use only the 10541 * explicitly set pivotX and pivotY values. 10542 * 10543 * @param pivotY The y location of the pivot point. 10544 * @see #getRotation() 10545 * @see #getScaleX() 10546 * @see #getScaleY() 10547 * @see #getPivotY() 10548 * 10549 * @attr ref android.R.styleable#View_transformPivotY 10550 */ 10551 public void setPivotY(float pivotY) { 10552 if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) { 10553 invalidateViewProperty(true, false); 10554 mRenderNode.setPivotY(pivotY); 10555 invalidateViewProperty(false, true); 10556 10557 invalidateParentIfNeededAndWasQuickRejected(); 10558 } 10559 } 10560 10561 /** 10562 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 10563 * completely transparent and 1 means the view is completely opaque. 10564 * 10565 * <p>By default this is 1.0f. 10566 * @return The opacity of the view. 10567 */ 10568 @ViewDebug.ExportedProperty(category = "drawing") 10569 public float getAlpha() { 10570 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 10571 } 10572 10573 /** 10574 * Returns whether this View has content which overlaps. 10575 * 10576 * <p>This function, intended to be overridden by specific View types, is an optimization when 10577 * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to 10578 * an offscreen buffer and then composited into place, which can be expensive. If the view has 10579 * no overlapping rendering, the view can draw each primitive with the appropriate alpha value 10580 * directly. An example of overlapping rendering is a TextView with a background image, such as 10581 * a Button. An example of non-overlapping rendering is a TextView with no background, or an 10582 * ImageView with only the foreground image. The default implementation returns true; subclasses 10583 * should override if they have cases which can be optimized.</p> 10584 * 10585 * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas} 10586 * necessitates that a View return true if it uses the methods internally without passing the 10587 * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p> 10588 * 10589 * @return true if the content in this view might overlap, false otherwise. 10590 */ 10591 @ViewDebug.ExportedProperty(category = "drawing") 10592 public boolean hasOverlappingRendering() { 10593 return true; 10594 } 10595 10596 /** 10597 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is 10598 * completely transparent and 1 means the view is completely opaque.</p> 10599 * 10600 * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant 10601 * performance implications, especially for large views. It is best to use the alpha property 10602 * sparingly and transiently, as in the case of fading animations.</p> 10603 * 10604 * <p>For a view with a frequently changing alpha, such as during a fading animation, it is 10605 * strongly recommended for performance reasons to either override 10606 * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a 10607 * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p> 10608 * 10609 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 10610 * responsible for applying the opacity itself.</p> 10611 * 10612 * <p>Note that if the view is backed by a 10613 * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a 10614 * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than 10615 * 1.0 will supercede the alpha of the layer paint.</p> 10616 * 10617 * @param alpha The opacity of the view. 10618 * 10619 * @see #hasOverlappingRendering() 10620 * @see #setLayerType(int, android.graphics.Paint) 10621 * 10622 * @attr ref android.R.styleable#View_alpha 10623 */ 10624 public void setAlpha(float alpha) { 10625 ensureTransformationInfo(); 10626 if (mTransformationInfo.mAlpha != alpha) { 10627 mTransformationInfo.mAlpha = alpha; 10628 if (onSetAlpha((int) (alpha * 255))) { 10629 mPrivateFlags |= PFLAG_ALPHA_SET; 10630 // subclass is handling alpha - don't optimize rendering cache invalidation 10631 invalidateParentCaches(); 10632 invalidate(true); 10633 } else { 10634 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10635 invalidateViewProperty(true, false); 10636 mRenderNode.setAlpha(getFinalAlpha()); 10637 notifyViewAccessibilityStateChangedIfNeeded( 10638 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 10639 } 10640 } 10641 } 10642 10643 /** 10644 * Faster version of setAlpha() which performs the same steps except there are 10645 * no calls to invalidate(). The caller of this function should perform proper invalidation 10646 * on the parent and this object. The return value indicates whether the subclass handles 10647 * alpha (the return value for onSetAlpha()). 10648 * 10649 * @param alpha The new value for the alpha property 10650 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 10651 * the new value for the alpha property is different from the old value 10652 */ 10653 boolean setAlphaNoInvalidation(float alpha) { 10654 ensureTransformationInfo(); 10655 if (mTransformationInfo.mAlpha != alpha) { 10656 mTransformationInfo.mAlpha = alpha; 10657 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 10658 if (subclassHandlesAlpha) { 10659 mPrivateFlags |= PFLAG_ALPHA_SET; 10660 return true; 10661 } else { 10662 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10663 mRenderNode.setAlpha(getFinalAlpha()); 10664 } 10665 } 10666 return false; 10667 } 10668 10669 /** 10670 * This property is hidden and intended only for use by the Fade transition, which 10671 * animates it to produce a visual translucency that does not side-effect (or get 10672 * affected by) the real alpha property. This value is composited with the other 10673 * alpha value (and the AlphaAnimation value, when that is present) to produce 10674 * a final visual translucency result, which is what is passed into the DisplayList. 10675 * 10676 * @hide 10677 */ 10678 public void setTransitionAlpha(float alpha) { 10679 ensureTransformationInfo(); 10680 if (mTransformationInfo.mTransitionAlpha != alpha) { 10681 mTransformationInfo.mTransitionAlpha = alpha; 10682 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10683 invalidateViewProperty(true, false); 10684 mRenderNode.setAlpha(getFinalAlpha()); 10685 } 10686 } 10687 10688 /** 10689 * Calculates the visual alpha of this view, which is a combination of the actual 10690 * alpha value and the transitionAlpha value (if set). 10691 */ 10692 private float getFinalAlpha() { 10693 if (mTransformationInfo != null) { 10694 return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha; 10695 } 10696 return 1; 10697 } 10698 10699 /** 10700 * This property is hidden and intended only for use by the Fade transition, which 10701 * animates it to produce a visual translucency that does not side-effect (or get 10702 * affected by) the real alpha property. This value is composited with the other 10703 * alpha value (and the AlphaAnimation value, when that is present) to produce 10704 * a final visual translucency result, which is what is passed into the DisplayList. 10705 * 10706 * @hide 10707 */ 10708 @ViewDebug.ExportedProperty(category = "drawing") 10709 public float getTransitionAlpha() { 10710 return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1; 10711 } 10712 10713 /** 10714 * Top position of this view relative to its parent. 10715 * 10716 * @return The top of this view, in pixels. 10717 */ 10718 @ViewDebug.CapturedViewProperty 10719 public final int getTop() { 10720 return mTop; 10721 } 10722 10723 /** 10724 * Sets the top position of this view relative to its parent. This method is meant to be called 10725 * by the layout system and should not generally be called otherwise, because the property 10726 * may be changed at any time by the layout. 10727 * 10728 * @param top The top of this view, in pixels. 10729 */ 10730 public final void setTop(int top) { 10731 if (top != mTop) { 10732 final boolean matrixIsIdentity = hasIdentityMatrix(); 10733 if (matrixIsIdentity) { 10734 if (mAttachInfo != null) { 10735 int minTop; 10736 int yLoc; 10737 if (top < mTop) { 10738 minTop = top; 10739 yLoc = top - mTop; 10740 } else { 10741 minTop = mTop; 10742 yLoc = 0; 10743 } 10744 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 10745 } 10746 } else { 10747 // Double-invalidation is necessary to capture view's old and new areas 10748 invalidate(true); 10749 } 10750 10751 int width = mRight - mLeft; 10752 int oldHeight = mBottom - mTop; 10753 10754 mTop = top; 10755 mRenderNode.setTop(mTop); 10756 10757 sizeChange(width, mBottom - mTop, width, oldHeight); 10758 10759 if (!matrixIsIdentity) { 10760 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10761 invalidate(true); 10762 } 10763 mBackgroundSizeChanged = true; 10764 invalidateParentIfNeeded(); 10765 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10766 // View was rejected last time it was drawn by its parent; this may have changed 10767 invalidateParentIfNeeded(); 10768 } 10769 } 10770 } 10771 10772 /** 10773 * Bottom position of this view relative to its parent. 10774 * 10775 * @return The bottom of this view, in pixels. 10776 */ 10777 @ViewDebug.CapturedViewProperty 10778 public final int getBottom() { 10779 return mBottom; 10780 } 10781 10782 /** 10783 * True if this view has changed since the last time being drawn. 10784 * 10785 * @return The dirty state of this view. 10786 */ 10787 public boolean isDirty() { 10788 return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0; 10789 } 10790 10791 /** 10792 * Sets the bottom position of this view relative to its parent. This method is meant to be 10793 * called by the layout system and should not generally be called otherwise, because the 10794 * property may be changed at any time by the layout. 10795 * 10796 * @param bottom The bottom of this view, in pixels. 10797 */ 10798 public final void setBottom(int bottom) { 10799 if (bottom != mBottom) { 10800 final boolean matrixIsIdentity = hasIdentityMatrix(); 10801 if (matrixIsIdentity) { 10802 if (mAttachInfo != null) { 10803 int maxBottom; 10804 if (bottom < mBottom) { 10805 maxBottom = mBottom; 10806 } else { 10807 maxBottom = bottom; 10808 } 10809 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 10810 } 10811 } else { 10812 // Double-invalidation is necessary to capture view's old and new areas 10813 invalidate(true); 10814 } 10815 10816 int width = mRight - mLeft; 10817 int oldHeight = mBottom - mTop; 10818 10819 mBottom = bottom; 10820 mRenderNode.setBottom(mBottom); 10821 10822 sizeChange(width, mBottom - mTop, width, oldHeight); 10823 10824 if (!matrixIsIdentity) { 10825 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10826 invalidate(true); 10827 } 10828 mBackgroundSizeChanged = true; 10829 invalidateParentIfNeeded(); 10830 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10831 // View was rejected last time it was drawn by its parent; this may have changed 10832 invalidateParentIfNeeded(); 10833 } 10834 } 10835 } 10836 10837 /** 10838 * Left position of this view relative to its parent. 10839 * 10840 * @return The left edge of this view, in pixels. 10841 */ 10842 @ViewDebug.CapturedViewProperty 10843 public final int getLeft() { 10844 return mLeft; 10845 } 10846 10847 /** 10848 * Sets the left position of this view relative to its parent. This method is meant to be called 10849 * by the layout system and should not generally be called otherwise, because the property 10850 * may be changed at any time by the layout. 10851 * 10852 * @param left The left of this view, in pixels. 10853 */ 10854 public final void setLeft(int left) { 10855 if (left != mLeft) { 10856 final boolean matrixIsIdentity = hasIdentityMatrix(); 10857 if (matrixIsIdentity) { 10858 if (mAttachInfo != null) { 10859 int minLeft; 10860 int xLoc; 10861 if (left < mLeft) { 10862 minLeft = left; 10863 xLoc = left - mLeft; 10864 } else { 10865 minLeft = mLeft; 10866 xLoc = 0; 10867 } 10868 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 10869 } 10870 } else { 10871 // Double-invalidation is necessary to capture view's old and new areas 10872 invalidate(true); 10873 } 10874 10875 int oldWidth = mRight - mLeft; 10876 int height = mBottom - mTop; 10877 10878 mLeft = left; 10879 mRenderNode.setLeft(left); 10880 10881 sizeChange(mRight - mLeft, height, oldWidth, height); 10882 10883 if (!matrixIsIdentity) { 10884 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10885 invalidate(true); 10886 } 10887 mBackgroundSizeChanged = true; 10888 invalidateParentIfNeeded(); 10889 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10890 // View was rejected last time it was drawn by its parent; this may have changed 10891 invalidateParentIfNeeded(); 10892 } 10893 } 10894 } 10895 10896 /** 10897 * Right position of this view relative to its parent. 10898 * 10899 * @return The right edge of this view, in pixels. 10900 */ 10901 @ViewDebug.CapturedViewProperty 10902 public final int getRight() { 10903 return mRight; 10904 } 10905 10906 /** 10907 * Sets the right position of this view relative to its parent. This method is meant to be called 10908 * by the layout system and should not generally be called otherwise, because the property 10909 * may be changed at any time by the layout. 10910 * 10911 * @param right The right of this view, in pixels. 10912 */ 10913 public final void setRight(int right) { 10914 if (right != mRight) { 10915 final boolean matrixIsIdentity = hasIdentityMatrix(); 10916 if (matrixIsIdentity) { 10917 if (mAttachInfo != null) { 10918 int maxRight; 10919 if (right < mRight) { 10920 maxRight = mRight; 10921 } else { 10922 maxRight = right; 10923 } 10924 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 10925 } 10926 } else { 10927 // Double-invalidation is necessary to capture view's old and new areas 10928 invalidate(true); 10929 } 10930 10931 int oldWidth = mRight - mLeft; 10932 int height = mBottom - mTop; 10933 10934 mRight = right; 10935 mRenderNode.setRight(mRight); 10936 10937 sizeChange(mRight - mLeft, height, oldWidth, height); 10938 10939 if (!matrixIsIdentity) { 10940 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10941 invalidate(true); 10942 } 10943 mBackgroundSizeChanged = true; 10944 invalidateParentIfNeeded(); 10945 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10946 // View was rejected last time it was drawn by its parent; this may have changed 10947 invalidateParentIfNeeded(); 10948 } 10949 } 10950 } 10951 10952 /** 10953 * The visual x position of this view, in pixels. This is equivalent to the 10954 * {@link #setTranslationX(float) translationX} property plus the current 10955 * {@link #getLeft() left} property. 10956 * 10957 * @return The visual x position of this view, in pixels. 10958 */ 10959 @ViewDebug.ExportedProperty(category = "drawing") 10960 public float getX() { 10961 return mLeft + getTranslationX(); 10962 } 10963 10964 /** 10965 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 10966 * {@link #setTranslationX(float) translationX} property to be the difference between 10967 * the x value passed in and the current {@link #getLeft() left} property. 10968 * 10969 * @param x The visual x position of this view, in pixels. 10970 */ 10971 public void setX(float x) { 10972 setTranslationX(x - mLeft); 10973 } 10974 10975 /** 10976 * The visual y position of this view, in pixels. This is equivalent to the 10977 * {@link #setTranslationY(float) translationY} property plus the current 10978 * {@link #getTop() top} property. 10979 * 10980 * @return The visual y position of this view, in pixels. 10981 */ 10982 @ViewDebug.ExportedProperty(category = "drawing") 10983 public float getY() { 10984 return mTop + getTranslationY(); 10985 } 10986 10987 /** 10988 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 10989 * {@link #setTranslationY(float) translationY} property to be the difference between 10990 * the y value passed in and the current {@link #getTop() top} property. 10991 * 10992 * @param y The visual y position of this view, in pixels. 10993 */ 10994 public void setY(float y) { 10995 setTranslationY(y - mTop); 10996 } 10997 10998 /** 10999 * The visual z position of this view, in pixels. This is equivalent to the 11000 * {@link #setTranslationZ(float) translationZ} property plus the current 11001 * {@link #getElevation() elevation} property. 11002 * 11003 * @return The visual z position of this view, in pixels. 11004 */ 11005 @ViewDebug.ExportedProperty(category = "drawing") 11006 public float getZ() { 11007 return getElevation() + getTranslationZ(); 11008 } 11009 11010 /** 11011 * Sets the visual z position of this view, in pixels. This is equivalent to setting the 11012 * {@link #setTranslationZ(float) translationZ} property to be the difference between 11013 * the x value passed in and the current {@link #getElevation() elevation} property. 11014 * 11015 * @param z The visual z position of this view, in pixels. 11016 */ 11017 public void setZ(float z) { 11018 setTranslationZ(z - getElevation()); 11019 } 11020 11021 /** 11022 * The base elevation of this view relative to its parent, in pixels. 11023 * 11024 * @return The base depth position of the view, in pixels. 11025 */ 11026 @ViewDebug.ExportedProperty(category = "drawing") 11027 public float getElevation() { 11028 return mRenderNode.getElevation(); 11029 } 11030 11031 /** 11032 * Sets the base elevation of this view, in pixels. 11033 * 11034 * @attr ref android.R.styleable#View_elevation 11035 */ 11036 public void setElevation(float elevation) { 11037 if (elevation != getElevation()) { 11038 invalidateViewProperty(true, false); 11039 mRenderNode.setElevation(elevation); 11040 invalidateViewProperty(false, true); 11041 11042 invalidateParentIfNeededAndWasQuickRejected(); 11043 } 11044 } 11045 11046 /** 11047 * The horizontal location of this view relative to its {@link #getLeft() left} position. 11048 * This position is post-layout, in addition to wherever the object's 11049 * layout placed it. 11050 * 11051 * @return The horizontal position of this view relative to its left position, in pixels. 11052 */ 11053 @ViewDebug.ExportedProperty(category = "drawing") 11054 public float getTranslationX() { 11055 return mRenderNode.getTranslationX(); 11056 } 11057 11058 /** 11059 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 11060 * This effectively positions the object post-layout, in addition to wherever the object's 11061 * layout placed it. 11062 * 11063 * @param translationX The horizontal position of this view relative to its left position, 11064 * in pixels. 11065 * 11066 * @attr ref android.R.styleable#View_translationX 11067 */ 11068 public void setTranslationX(float translationX) { 11069 if (translationX != getTranslationX()) { 11070 invalidateViewProperty(true, false); 11071 mRenderNode.setTranslationX(translationX); 11072 invalidateViewProperty(false, true); 11073 11074 invalidateParentIfNeededAndWasQuickRejected(); 11075 notifySubtreeAccessibilityStateChangedIfNeeded(); 11076 } 11077 } 11078 11079 /** 11080 * The vertical location of this view relative to its {@link #getTop() top} position. 11081 * This position is post-layout, in addition to wherever the object's 11082 * layout placed it. 11083 * 11084 * @return The vertical position of this view relative to its top position, 11085 * in pixels. 11086 */ 11087 @ViewDebug.ExportedProperty(category = "drawing") 11088 public float getTranslationY() { 11089 return mRenderNode.getTranslationY(); 11090 } 11091 11092 /** 11093 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 11094 * This effectively positions the object post-layout, in addition to wherever the object's 11095 * layout placed it. 11096 * 11097 * @param translationY The vertical position of this view relative to its top position, 11098 * in pixels. 11099 * 11100 * @attr ref android.R.styleable#View_translationY 11101 */ 11102 public void setTranslationY(float translationY) { 11103 if (translationY != getTranslationY()) { 11104 invalidateViewProperty(true, false); 11105 mRenderNode.setTranslationY(translationY); 11106 invalidateViewProperty(false, true); 11107 11108 invalidateParentIfNeededAndWasQuickRejected(); 11109 } 11110 } 11111 11112 /** 11113 * The depth location of this view relative to its {@link #getElevation() elevation}. 11114 * 11115 * @return The depth of this view relative to its elevation. 11116 */ 11117 @ViewDebug.ExportedProperty(category = "drawing") 11118 public float getTranslationZ() { 11119 return mRenderNode.getTranslationZ(); 11120 } 11121 11122 /** 11123 * Sets the depth location of this view relative to its {@link #getElevation() elevation}. 11124 * 11125 * @attr ref android.R.styleable#View_translationZ 11126 */ 11127 public void setTranslationZ(float translationZ) { 11128 if (translationZ != getTranslationZ()) { 11129 invalidateViewProperty(true, false); 11130 mRenderNode.setTranslationZ(translationZ); 11131 invalidateViewProperty(false, true); 11132 11133 invalidateParentIfNeededAndWasQuickRejected(); 11134 } 11135 } 11136 11137 /** @hide */ 11138 public void setAnimationMatrix(Matrix matrix) { 11139 invalidateViewProperty(true, false); 11140 mRenderNode.setAnimationMatrix(matrix); 11141 invalidateViewProperty(false, true); 11142 11143 invalidateParentIfNeededAndWasQuickRejected(); 11144 } 11145 11146 /** 11147 * Returns the current StateListAnimator if exists. 11148 * 11149 * @return StateListAnimator or null if it does not exists 11150 * @see #setStateListAnimator(android.animation.StateListAnimator) 11151 */ 11152 public StateListAnimator getStateListAnimator() { 11153 return mStateListAnimator; 11154 } 11155 11156 /** 11157 * Attaches the provided StateListAnimator to this View. 11158 * <p> 11159 * Any previously attached StateListAnimator will be detached. 11160 * 11161 * @param stateListAnimator The StateListAnimator to update the view 11162 * @see {@link android.animation.StateListAnimator} 11163 */ 11164 public void setStateListAnimator(StateListAnimator stateListAnimator) { 11165 if (mStateListAnimator == stateListAnimator) { 11166 return; 11167 } 11168 if (mStateListAnimator != null) { 11169 mStateListAnimator.setTarget(null); 11170 } 11171 mStateListAnimator = stateListAnimator; 11172 if (stateListAnimator != null) { 11173 stateListAnimator.setTarget(this); 11174 if (isAttachedToWindow()) { 11175 stateListAnimator.setState(getDrawableState()); 11176 } 11177 } 11178 } 11179 11180 /** 11181 * Returns whether the Outline should be used to clip the contents of the View. 11182 * <p> 11183 * Note that this flag will only be respected if the View's Outline returns true from 11184 * {@link Outline#canClip()}. 11185 * 11186 * @see #setOutlineProvider(ViewOutlineProvider) 11187 * @see #setClipToOutline(boolean) 11188 */ 11189 public final boolean getClipToOutline() { 11190 return mRenderNode.getClipToOutline(); 11191 } 11192 11193 /** 11194 * Sets whether the View's Outline should be used to clip the contents of the View. 11195 * <p> 11196 * Only a single non-rectangular clip can be applied on a View at any time. 11197 * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float) 11198 * circular reveal} animation take priority over Outline clipping, and 11199 * child Outline clipping takes priority over Outline clipping done by a 11200 * parent. 11201 * <p> 11202 * Note that this flag will only be respected if the View's Outline returns true from 11203 * {@link Outline#canClip()}. 11204 * 11205 * @see #setOutlineProvider(ViewOutlineProvider) 11206 * @see #getClipToOutline() 11207 */ 11208 public void setClipToOutline(boolean clipToOutline) { 11209 damageInParent(); 11210 if (getClipToOutline() != clipToOutline) { 11211 mRenderNode.setClipToOutline(clipToOutline); 11212 } 11213 } 11214 11215 // correspond to the enum values of View_outlineProvider 11216 private static final int PROVIDER_BACKGROUND = 0; 11217 private static final int PROVIDER_NONE = 1; 11218 private static final int PROVIDER_BOUNDS = 2; 11219 private static final int PROVIDER_PADDED_BOUNDS = 3; 11220 private void setOutlineProviderFromAttribute(int providerInt) { 11221 switch (providerInt) { 11222 case PROVIDER_BACKGROUND: 11223 setOutlineProvider(ViewOutlineProvider.BACKGROUND); 11224 break; 11225 case PROVIDER_NONE: 11226 setOutlineProvider(null); 11227 break; 11228 case PROVIDER_BOUNDS: 11229 setOutlineProvider(ViewOutlineProvider.BOUNDS); 11230 break; 11231 case PROVIDER_PADDED_BOUNDS: 11232 setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS); 11233 break; 11234 } 11235 } 11236 11237 /** 11238 * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines 11239 * the shape of the shadow it casts, and enables outline clipping. 11240 * <p> 11241 * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline 11242 * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the 11243 * outline provider with this method allows this behavior to be overridden. 11244 * <p> 11245 * If the ViewOutlineProvider is null, if querying it for an outline returns false, 11246 * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast. 11247 * <p> 11248 * Only outlines that return true from {@link Outline#canClip()} may be used for clipping. 11249 * 11250 * @see #setClipToOutline(boolean) 11251 * @see #getClipToOutline() 11252 * @see #getOutlineProvider() 11253 */ 11254 public void setOutlineProvider(ViewOutlineProvider provider) { 11255 mOutlineProvider = provider; 11256 invalidateOutline(); 11257 } 11258 11259 /** 11260 * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline 11261 * that defines the shape of the shadow it casts, and enables outline clipping. 11262 * 11263 * @see #setOutlineProvider(ViewOutlineProvider) 11264 */ 11265 public ViewOutlineProvider getOutlineProvider() { 11266 return mOutlineProvider; 11267 } 11268 11269 /** 11270 * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider} 11271 * 11272 * @see #setOutlineProvider(ViewOutlineProvider) 11273 */ 11274 public void invalidateOutline() { 11275 mPrivateFlags3 |= PFLAG3_OUTLINE_INVALID; 11276 11277 notifySubtreeAccessibilityStateChangedIfNeeded(); 11278 invalidateViewProperty(false, false); 11279 } 11280 11281 /** 11282 * Internal version of {@link #invalidateOutline()} which invalidates the 11283 * outline without invalidating the view itself. This is intended to be called from 11284 * within methods in the View class itself which are the result of the view being 11285 * invalidated already. For example, when we are drawing the background of a View, 11286 * we invalidate the outline in case it changed in the meantime, but we do not 11287 * need to invalidate the view because we're already drawing the background as part 11288 * of drawing the view in response to an earlier invalidation of the view. 11289 */ 11290 private void rebuildOutline() { 11291 // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow() 11292 if (mAttachInfo == null) return; 11293 11294 if (mOutlineProvider == null) { 11295 // no provider, remove outline 11296 mRenderNode.setOutline(null); 11297 } else { 11298 final Outline outline = mAttachInfo.mTmpOutline; 11299 outline.setEmpty(); 11300 outline.setAlpha(1.0f); 11301 11302 mOutlineProvider.getOutline(this, outline); 11303 mRenderNode.setOutline(outline); 11304 } 11305 } 11306 11307 /** 11308 * HierarchyViewer only 11309 * 11310 * @hide 11311 */ 11312 @ViewDebug.ExportedProperty(category = "drawing") 11313 public boolean hasShadow() { 11314 return mRenderNode.hasShadow(); 11315 } 11316 11317 11318 /** @hide */ 11319 public void setRevealClip(boolean shouldClip, float x, float y, float radius) { 11320 mRenderNode.setRevealClip(shouldClip, x, y, radius); 11321 invalidateViewProperty(false, false); 11322 } 11323 11324 /** 11325 * Hit rectangle in parent's coordinates 11326 * 11327 * @param outRect The hit rectangle of the view. 11328 */ 11329 public void getHitRect(Rect outRect) { 11330 if (hasIdentityMatrix() || mAttachInfo == null) { 11331 outRect.set(mLeft, mTop, mRight, mBottom); 11332 } else { 11333 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 11334 tmpRect.set(0, 0, getWidth(), getHeight()); 11335 getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect) 11336 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 11337 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 11338 } 11339 } 11340 11341 /** 11342 * Determines whether the given point, in local coordinates is inside the view. 11343 */ 11344 /*package*/ final boolean pointInView(float localX, float localY) { 11345 return localX >= 0 && localX < (mRight - mLeft) 11346 && localY >= 0 && localY < (mBottom - mTop); 11347 } 11348 11349 /** 11350 * Utility method to determine whether the given point, in local coordinates, 11351 * is inside the view, where the area of the view is expanded by the slop factor. 11352 * This method is called while processing touch-move events to determine if the event 11353 * is still within the view. 11354 * 11355 * @hide 11356 */ 11357 public boolean pointInView(float localX, float localY, float slop) { 11358 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 11359 localY < ((mBottom - mTop) + slop); 11360 } 11361 11362 /** 11363 * When a view has focus and the user navigates away from it, the next view is searched for 11364 * starting from the rectangle filled in by this method. 11365 * 11366 * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)}) 11367 * of the view. However, if your view maintains some idea of internal selection, 11368 * such as a cursor, or a selected row or column, you should override this method and 11369 * fill in a more specific rectangle. 11370 * 11371 * @param r The rectangle to fill in, in this view's coordinates. 11372 */ 11373 public void getFocusedRect(Rect r) { 11374 getDrawingRect(r); 11375 } 11376 11377 /** 11378 * If some part of this view is not clipped by any of its parents, then 11379 * return that area in r in global (root) coordinates. To convert r to local 11380 * coordinates (without taking possible View rotations into account), offset 11381 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 11382 * If the view is completely clipped or translated out, return false. 11383 * 11384 * @param r If true is returned, r holds the global coordinates of the 11385 * visible portion of this view. 11386 * @param globalOffset If true is returned, globalOffset holds the dx,dy 11387 * between this view and its root. globalOffet may be null. 11388 * @return true if r is non-empty (i.e. part of the view is visible at the 11389 * root level. 11390 */ 11391 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 11392 int width = mRight - mLeft; 11393 int height = mBottom - mTop; 11394 if (width > 0 && height > 0) { 11395 r.set(0, 0, width, height); 11396 if (globalOffset != null) { 11397 globalOffset.set(-mScrollX, -mScrollY); 11398 } 11399 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 11400 } 11401 return false; 11402 } 11403 11404 public final boolean getGlobalVisibleRect(Rect r) { 11405 return getGlobalVisibleRect(r, null); 11406 } 11407 11408 public final boolean getLocalVisibleRect(Rect r) { 11409 final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point(); 11410 if (getGlobalVisibleRect(r, offset)) { 11411 r.offset(-offset.x, -offset.y); // make r local 11412 return true; 11413 } 11414 return false; 11415 } 11416 11417 /** 11418 * Offset this view's vertical location by the specified number of pixels. 11419 * 11420 * @param offset the number of pixels to offset the view by 11421 */ 11422 public void offsetTopAndBottom(int offset) { 11423 if (offset != 0) { 11424 final boolean matrixIsIdentity = hasIdentityMatrix(); 11425 if (matrixIsIdentity) { 11426 if (isHardwareAccelerated()) { 11427 invalidateViewProperty(false, false); 11428 } else { 11429 final ViewParent p = mParent; 11430 if (p != null && mAttachInfo != null) { 11431 final Rect r = mAttachInfo.mTmpInvalRect; 11432 int minTop; 11433 int maxBottom; 11434 int yLoc; 11435 if (offset < 0) { 11436 minTop = mTop + offset; 11437 maxBottom = mBottom; 11438 yLoc = offset; 11439 } else { 11440 minTop = mTop; 11441 maxBottom = mBottom + offset; 11442 yLoc = 0; 11443 } 11444 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 11445 p.invalidateChild(this, r); 11446 } 11447 } 11448 } else { 11449 invalidateViewProperty(false, false); 11450 } 11451 11452 mTop += offset; 11453 mBottom += offset; 11454 mRenderNode.offsetTopAndBottom(offset); 11455 if (isHardwareAccelerated()) { 11456 invalidateViewProperty(false, false); 11457 } else { 11458 if (!matrixIsIdentity) { 11459 invalidateViewProperty(false, true); 11460 } 11461 invalidateParentIfNeeded(); 11462 } 11463 notifySubtreeAccessibilityStateChangedIfNeeded(); 11464 } 11465 } 11466 11467 /** 11468 * Offset this view's horizontal location by the specified amount of pixels. 11469 * 11470 * @param offset the number of pixels to offset the view by 11471 */ 11472 public void offsetLeftAndRight(int offset) { 11473 if (offset != 0) { 11474 final boolean matrixIsIdentity = hasIdentityMatrix(); 11475 if (matrixIsIdentity) { 11476 if (isHardwareAccelerated()) { 11477 invalidateViewProperty(false, false); 11478 } else { 11479 final ViewParent p = mParent; 11480 if (p != null && mAttachInfo != null) { 11481 final Rect r = mAttachInfo.mTmpInvalRect; 11482 int minLeft; 11483 int maxRight; 11484 if (offset < 0) { 11485 minLeft = mLeft + offset; 11486 maxRight = mRight; 11487 } else { 11488 minLeft = mLeft; 11489 maxRight = mRight + offset; 11490 } 11491 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 11492 p.invalidateChild(this, r); 11493 } 11494 } 11495 } else { 11496 invalidateViewProperty(false, false); 11497 } 11498 11499 mLeft += offset; 11500 mRight += offset; 11501 mRenderNode.offsetLeftAndRight(offset); 11502 if (isHardwareAccelerated()) { 11503 invalidateViewProperty(false, false); 11504 } else { 11505 if (!matrixIsIdentity) { 11506 invalidateViewProperty(false, true); 11507 } 11508 invalidateParentIfNeeded(); 11509 } 11510 notifySubtreeAccessibilityStateChangedIfNeeded(); 11511 } 11512 } 11513 11514 /** 11515 * Get the LayoutParams associated with this view. All views should have 11516 * layout parameters. These supply parameters to the <i>parent</i> of this 11517 * view specifying how it should be arranged. There are many subclasses of 11518 * ViewGroup.LayoutParams, and these correspond to the different subclasses 11519 * of ViewGroup that are responsible for arranging their children. 11520 * 11521 * This method may return null if this View is not attached to a parent 11522 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 11523 * was not invoked successfully. When a View is attached to a parent 11524 * ViewGroup, this method must not return null. 11525 * 11526 * @return The LayoutParams associated with this view, or null if no 11527 * parameters have been set yet 11528 */ 11529 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 11530 public ViewGroup.LayoutParams getLayoutParams() { 11531 return mLayoutParams; 11532 } 11533 11534 /** 11535 * Set the layout parameters associated with this view. These supply 11536 * parameters to the <i>parent</i> of this view specifying how it should be 11537 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 11538 * correspond to the different subclasses of ViewGroup that are responsible 11539 * for arranging their children. 11540 * 11541 * @param params The layout parameters for this view, cannot be null 11542 */ 11543 public void setLayoutParams(ViewGroup.LayoutParams params) { 11544 if (params == null) { 11545 throw new NullPointerException("Layout parameters cannot be null"); 11546 } 11547 mLayoutParams = params; 11548 resolveLayoutParams(); 11549 if (mParent instanceof ViewGroup) { 11550 ((ViewGroup) mParent).onSetLayoutParams(this, params); 11551 } 11552 requestLayout(); 11553 } 11554 11555 /** 11556 * Resolve the layout parameters depending on the resolved layout direction 11557 * 11558 * @hide 11559 */ 11560 public void resolveLayoutParams() { 11561 if (mLayoutParams != null) { 11562 mLayoutParams.resolveLayoutDirection(getLayoutDirection()); 11563 } 11564 } 11565 11566 /** 11567 * Set the scrolled position of your view. This will cause a call to 11568 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11569 * invalidated. 11570 * @param x the x position to scroll to 11571 * @param y the y position to scroll to 11572 */ 11573 public void scrollTo(int x, int y) { 11574 if (mScrollX != x || mScrollY != y) { 11575 int oldX = mScrollX; 11576 int oldY = mScrollY; 11577 mScrollX = x; 11578 mScrollY = y; 11579 invalidateParentCaches(); 11580 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 11581 if (!awakenScrollBars()) { 11582 postInvalidateOnAnimation(); 11583 } 11584 } 11585 } 11586 11587 /** 11588 * Move the scrolled position of your view. This will cause a call to 11589 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11590 * invalidated. 11591 * @param x the amount of pixels to scroll by horizontally 11592 * @param y the amount of pixels to scroll by vertically 11593 */ 11594 public void scrollBy(int x, int y) { 11595 scrollTo(mScrollX + x, mScrollY + y); 11596 } 11597 11598 /** 11599 * <p>Trigger the scrollbars to draw. When invoked this method starts an 11600 * animation to fade the scrollbars out after a default delay. If a subclass 11601 * provides animated scrolling, the start delay should equal the duration 11602 * of the scrolling animation.</p> 11603 * 11604 * <p>The animation starts only if at least one of the scrollbars is 11605 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 11606 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11607 * this method returns true, and false otherwise. If the animation is 11608 * started, this method calls {@link #invalidate()}; in that case the 11609 * caller should not call {@link #invalidate()}.</p> 11610 * 11611 * <p>This method should be invoked every time a subclass directly updates 11612 * the scroll parameters.</p> 11613 * 11614 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 11615 * and {@link #scrollTo(int, int)}.</p> 11616 * 11617 * @return true if the animation is played, false otherwise 11618 * 11619 * @see #awakenScrollBars(int) 11620 * @see #scrollBy(int, int) 11621 * @see #scrollTo(int, int) 11622 * @see #isHorizontalScrollBarEnabled() 11623 * @see #isVerticalScrollBarEnabled() 11624 * @see #setHorizontalScrollBarEnabled(boolean) 11625 * @see #setVerticalScrollBarEnabled(boolean) 11626 */ 11627 protected boolean awakenScrollBars() { 11628 return mScrollCache != null && 11629 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 11630 } 11631 11632 /** 11633 * Trigger the scrollbars to draw. 11634 * This method differs from awakenScrollBars() only in its default duration. 11635 * initialAwakenScrollBars() will show the scroll bars for longer than 11636 * usual to give the user more of a chance to notice them. 11637 * 11638 * @return true if the animation is played, false otherwise. 11639 */ 11640 private boolean initialAwakenScrollBars() { 11641 return mScrollCache != null && 11642 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 11643 } 11644 11645 /** 11646 * <p> 11647 * Trigger the scrollbars to draw. When invoked this method starts an 11648 * animation to fade the scrollbars out after a fixed delay. If a subclass 11649 * provides animated scrolling, the start delay should equal the duration of 11650 * the scrolling animation. 11651 * </p> 11652 * 11653 * <p> 11654 * The animation starts only if at least one of the scrollbars is enabled, 11655 * as specified by {@link #isHorizontalScrollBarEnabled()} and 11656 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11657 * this method returns true, and false otherwise. If the animation is 11658 * started, this method calls {@link #invalidate()}; in that case the caller 11659 * should not call {@link #invalidate()}. 11660 * </p> 11661 * 11662 * <p> 11663 * This method should be invoked everytime a subclass directly updates the 11664 * scroll parameters. 11665 * </p> 11666 * 11667 * @param startDelay the delay, in milliseconds, after which the animation 11668 * should start; when the delay is 0, the animation starts 11669 * immediately 11670 * @return true if the animation is played, false otherwise 11671 * 11672 * @see #scrollBy(int, int) 11673 * @see #scrollTo(int, int) 11674 * @see #isHorizontalScrollBarEnabled() 11675 * @see #isVerticalScrollBarEnabled() 11676 * @see #setHorizontalScrollBarEnabled(boolean) 11677 * @see #setVerticalScrollBarEnabled(boolean) 11678 */ 11679 protected boolean awakenScrollBars(int startDelay) { 11680 return awakenScrollBars(startDelay, true); 11681 } 11682 11683 /** 11684 * <p> 11685 * Trigger the scrollbars to draw. When invoked this method starts an 11686 * animation to fade the scrollbars out after a fixed delay. If a subclass 11687 * provides animated scrolling, the start delay should equal the duration of 11688 * the scrolling animation. 11689 * </p> 11690 * 11691 * <p> 11692 * The animation starts only if at least one of the scrollbars is enabled, 11693 * as specified by {@link #isHorizontalScrollBarEnabled()} and 11694 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11695 * this method returns true, and false otherwise. If the animation is 11696 * started, this method calls {@link #invalidate()} if the invalidate parameter 11697 * is set to true; in that case the caller 11698 * should not call {@link #invalidate()}. 11699 * </p> 11700 * 11701 * <p> 11702 * This method should be invoked everytime a subclass directly updates the 11703 * scroll parameters. 11704 * </p> 11705 * 11706 * @param startDelay the delay, in milliseconds, after which the animation 11707 * should start; when the delay is 0, the animation starts 11708 * immediately 11709 * 11710 * @param invalidate Wheter this method should call invalidate 11711 * 11712 * @return true if the animation is played, false otherwise 11713 * 11714 * @see #scrollBy(int, int) 11715 * @see #scrollTo(int, int) 11716 * @see #isHorizontalScrollBarEnabled() 11717 * @see #isVerticalScrollBarEnabled() 11718 * @see #setHorizontalScrollBarEnabled(boolean) 11719 * @see #setVerticalScrollBarEnabled(boolean) 11720 */ 11721 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 11722 final ScrollabilityCache scrollCache = mScrollCache; 11723 11724 if (scrollCache == null || !scrollCache.fadeScrollBars) { 11725 return false; 11726 } 11727 11728 if (scrollCache.scrollBar == null) { 11729 scrollCache.scrollBar = new ScrollBarDrawable(); 11730 } 11731 11732 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 11733 11734 if (invalidate) { 11735 // Invalidate to show the scrollbars 11736 postInvalidateOnAnimation(); 11737 } 11738 11739 if (scrollCache.state == ScrollabilityCache.OFF) { 11740 // FIXME: this is copied from WindowManagerService. 11741 // We should get this value from the system when it 11742 // is possible to do so. 11743 final int KEY_REPEAT_FIRST_DELAY = 750; 11744 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 11745 } 11746 11747 // Tell mScrollCache when we should start fading. This may 11748 // extend the fade start time if one was already scheduled 11749 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 11750 scrollCache.fadeStartTime = fadeStartTime; 11751 scrollCache.state = ScrollabilityCache.ON; 11752 11753 // Schedule our fader to run, unscheduling any old ones first 11754 if (mAttachInfo != null) { 11755 mAttachInfo.mHandler.removeCallbacks(scrollCache); 11756 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 11757 } 11758 11759 return true; 11760 } 11761 11762 return false; 11763 } 11764 11765 /** 11766 * Do not invalidate views which are not visible and which are not running an animation. They 11767 * will not get drawn and they should not set dirty flags as if they will be drawn 11768 */ 11769 private boolean skipInvalidate() { 11770 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 11771 (!(mParent instanceof ViewGroup) || 11772 !((ViewGroup) mParent).isViewTransitioning(this)); 11773 } 11774 11775 /** 11776 * Mark the area defined by dirty as needing to be drawn. If the view is 11777 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 11778 * point in the future. 11779 * <p> 11780 * This must be called from a UI thread. To call from a non-UI thread, call 11781 * {@link #postInvalidate()}. 11782 * <p> 11783 * <b>WARNING:</b> In API 19 and below, this method may be destructive to 11784 * {@code dirty}. 11785 * 11786 * @param dirty the rectangle representing the bounds of the dirty region 11787 */ 11788 public void invalidate(Rect dirty) { 11789 final int scrollX = mScrollX; 11790 final int scrollY = mScrollY; 11791 invalidateInternal(dirty.left - scrollX, dirty.top - scrollY, 11792 dirty.right - scrollX, dirty.bottom - scrollY, true, false); 11793 } 11794 11795 /** 11796 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The 11797 * coordinates of the dirty rect are relative to the view. If the view is 11798 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 11799 * point in the future. 11800 * <p> 11801 * This must be called from a UI thread. To call from a non-UI thread, call 11802 * {@link #postInvalidate()}. 11803 * 11804 * @param l the left position of the dirty region 11805 * @param t the top position of the dirty region 11806 * @param r the right position of the dirty region 11807 * @param b the bottom position of the dirty region 11808 */ 11809 public void invalidate(int l, int t, int r, int b) { 11810 final int scrollX = mScrollX; 11811 final int scrollY = mScrollY; 11812 invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false); 11813 } 11814 11815 /** 11816 * Invalidate the whole view. If the view is visible, 11817 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 11818 * the future. 11819 * <p> 11820 * This must be called from a UI thread. To call from a non-UI thread, call 11821 * {@link #postInvalidate()}. 11822 */ 11823 public void invalidate() { 11824 invalidate(true); 11825 } 11826 11827 /** 11828 * This is where the invalidate() work actually happens. A full invalidate() 11829 * causes the drawing cache to be invalidated, but this function can be 11830 * called with invalidateCache set to false to skip that invalidation step 11831 * for cases that do not need it (for example, a component that remains at 11832 * the same dimensions with the same content). 11833 * 11834 * @param invalidateCache Whether the drawing cache for this view should be 11835 * invalidated as well. This is usually true for a full 11836 * invalidate, but may be set to false if the View's contents or 11837 * dimensions have not changed. 11838 */ 11839 void invalidate(boolean invalidateCache) { 11840 invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true); 11841 } 11842 11843 void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache, 11844 boolean fullInvalidate) { 11845 if (mGhostView != null) { 11846 mGhostView.invalidate(invalidateCache); 11847 return; 11848 } 11849 11850 if (skipInvalidate()) { 11851 return; 11852 } 11853 11854 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) 11855 || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) 11856 || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED 11857 || (fullInvalidate && isOpaque() != mLastIsOpaque)) { 11858 if (fullInvalidate) { 11859 mLastIsOpaque = isOpaque(); 11860 mPrivateFlags &= ~PFLAG_DRAWN; 11861 } 11862 11863 mPrivateFlags |= PFLAG_DIRTY; 11864 11865 if (invalidateCache) { 11866 mPrivateFlags |= PFLAG_INVALIDATED; 11867 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 11868 } 11869 11870 // Propagate the damage rectangle to the parent view. 11871 final AttachInfo ai = mAttachInfo; 11872 final ViewParent p = mParent; 11873 if (p != null && ai != null && l < r && t < b) { 11874 final Rect damage = ai.mTmpInvalRect; 11875 damage.set(l, t, r, b); 11876 p.invalidateChild(this, damage); 11877 } 11878 11879 // Damage the entire projection receiver, if necessary. 11880 if (mBackground != null && mBackground.isProjected()) { 11881 final View receiver = getProjectionReceiver(); 11882 if (receiver != null) { 11883 receiver.damageInParent(); 11884 } 11885 } 11886 11887 // Damage the entire IsolatedZVolume receiving this view's shadow. 11888 if (isHardwareAccelerated() && getZ() != 0) { 11889 damageShadowReceiver(); 11890 } 11891 } 11892 } 11893 11894 /** 11895 * @return this view's projection receiver, or {@code null} if none exists 11896 */ 11897 private View getProjectionReceiver() { 11898 ViewParent p = getParent(); 11899 while (p != null && p instanceof View) { 11900 final View v = (View) p; 11901 if (v.isProjectionReceiver()) { 11902 return v; 11903 } 11904 p = p.getParent(); 11905 } 11906 11907 return null; 11908 } 11909 11910 /** 11911 * @return whether the view is a projection receiver 11912 */ 11913 private boolean isProjectionReceiver() { 11914 return mBackground != null; 11915 } 11916 11917 /** 11918 * Damage area of the screen that can be covered by this View's shadow. 11919 * 11920 * This method will guarantee that any changes to shadows cast by a View 11921 * are damaged on the screen for future redraw. 11922 */ 11923 private void damageShadowReceiver() { 11924 final AttachInfo ai = mAttachInfo; 11925 if (ai != null) { 11926 ViewParent p = getParent(); 11927 if (p != null && p instanceof ViewGroup) { 11928 final ViewGroup vg = (ViewGroup) p; 11929 vg.damageInParent(); 11930 } 11931 } 11932 } 11933 11934 /** 11935 * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to 11936 * set any flags or handle all of the cases handled by the default invalidation methods. 11937 * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate 11938 * dirty rect. This method calls into fast invalidation methods in ViewGroup that 11939 * walk up the hierarchy, transforming the dirty rect as necessary. 11940 * 11941 * The method also handles normal invalidation logic if display list properties are not 11942 * being used in this view. The invalidateParent and forceRedraw flags are used by that 11943 * backup approach, to handle these cases used in the various property-setting methods. 11944 * 11945 * @param invalidateParent Force a call to invalidateParentCaches() if display list properties 11946 * are not being used in this view 11947 * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display 11948 * list properties are not being used in this view 11949 */ 11950 void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) { 11951 if (!isHardwareAccelerated() 11952 || !mRenderNode.isValid() 11953 || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) { 11954 if (invalidateParent) { 11955 invalidateParentCaches(); 11956 } 11957 if (forceRedraw) { 11958 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 11959 } 11960 invalidate(false); 11961 } else { 11962 damageInParent(); 11963 } 11964 if (isHardwareAccelerated() && invalidateParent && getZ() != 0) { 11965 damageShadowReceiver(); 11966 } 11967 } 11968 11969 /** 11970 * Tells the parent view to damage this view's bounds. 11971 * 11972 * @hide 11973 */ 11974 protected void damageInParent() { 11975 final AttachInfo ai = mAttachInfo; 11976 final ViewParent p = mParent; 11977 if (p != null && ai != null) { 11978 final Rect r = ai.mTmpInvalRect; 11979 r.set(0, 0, mRight - mLeft, mBottom - mTop); 11980 if (mParent instanceof ViewGroup) { 11981 ((ViewGroup) mParent).damageChild(this, r); 11982 } else { 11983 mParent.invalidateChild(this, r); 11984 } 11985 } 11986 } 11987 11988 /** 11989 * Utility method to transform a given Rect by the current matrix of this view. 11990 */ 11991 void transformRect(final Rect rect) { 11992 if (!getMatrix().isIdentity()) { 11993 RectF boundingRect = mAttachInfo.mTmpTransformRect; 11994 boundingRect.set(rect); 11995 getMatrix().mapRect(boundingRect); 11996 rect.set((int) Math.floor(boundingRect.left), 11997 (int) Math.floor(boundingRect.top), 11998 (int) Math.ceil(boundingRect.right), 11999 (int) Math.ceil(boundingRect.bottom)); 12000 } 12001 } 12002 12003 /** 12004 * Used to indicate that the parent of this view should clear its caches. This functionality 12005 * is used to force the parent to rebuild its display list (when hardware-accelerated), 12006 * which is necessary when various parent-managed properties of the view change, such as 12007 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 12008 * clears the parent caches and does not causes an invalidate event. 12009 * 12010 * @hide 12011 */ 12012 protected void invalidateParentCaches() { 12013 if (mParent instanceof View) { 12014 ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED; 12015 } 12016 } 12017 12018 /** 12019 * Used to indicate that the parent of this view should be invalidated. This functionality 12020 * is used to force the parent to rebuild its display list (when hardware-accelerated), 12021 * which is necessary when various parent-managed properties of the view change, such as 12022 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 12023 * an invalidation event to the parent. 12024 * 12025 * @hide 12026 */ 12027 protected void invalidateParentIfNeeded() { 12028 if (isHardwareAccelerated() && mParent instanceof View) { 12029 ((View) mParent).invalidate(true); 12030 } 12031 } 12032 12033 /** 12034 * @hide 12035 */ 12036 protected void invalidateParentIfNeededAndWasQuickRejected() { 12037 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) { 12038 // View was rejected last time it was drawn by its parent; this may have changed 12039 invalidateParentIfNeeded(); 12040 } 12041 } 12042 12043 /** 12044 * Indicates whether this View is opaque. An opaque View guarantees that it will 12045 * draw all the pixels overlapping its bounds using a fully opaque color. 12046 * 12047 * Subclasses of View should override this method whenever possible to indicate 12048 * whether an instance is opaque. Opaque Views are treated in a special way by 12049 * the View hierarchy, possibly allowing it to perform optimizations during 12050 * invalidate/draw passes. 12051 * 12052 * @return True if this View is guaranteed to be fully opaque, false otherwise. 12053 */ 12054 @ViewDebug.ExportedProperty(category = "drawing") 12055 public boolean isOpaque() { 12056 return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK && 12057 getFinalAlpha() >= 1.0f; 12058 } 12059 12060 /** 12061 * @hide 12062 */ 12063 protected void computeOpaqueFlags() { 12064 // Opaque if: 12065 // - Has a background 12066 // - Background is opaque 12067 // - Doesn't have scrollbars or scrollbars overlay 12068 12069 if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) { 12070 mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND; 12071 } else { 12072 mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND; 12073 } 12074 12075 final int flags = mViewFlags; 12076 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 12077 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY || 12078 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) { 12079 mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS; 12080 } else { 12081 mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS; 12082 } 12083 } 12084 12085 /** 12086 * @hide 12087 */ 12088 protected boolean hasOpaqueScrollbars() { 12089 return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS; 12090 } 12091 12092 /** 12093 * @return A handler associated with the thread running the View. This 12094 * handler can be used to pump events in the UI events queue. 12095 */ 12096 public Handler getHandler() { 12097 final AttachInfo attachInfo = mAttachInfo; 12098 if (attachInfo != null) { 12099 return attachInfo.mHandler; 12100 } 12101 return null; 12102 } 12103 12104 /** 12105 * Gets the view root associated with the View. 12106 * @return The view root, or null if none. 12107 * @hide 12108 */ 12109 public ViewRootImpl getViewRootImpl() { 12110 if (mAttachInfo != null) { 12111 return mAttachInfo.mViewRootImpl; 12112 } 12113 return null; 12114 } 12115 12116 /** 12117 * @hide 12118 */ 12119 public HardwareRenderer getHardwareRenderer() { 12120 return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null; 12121 } 12122 12123 /** 12124 * <p>Causes the Runnable to be added to the message queue. 12125 * The runnable will be run on the user interface thread.</p> 12126 * 12127 * @param action The Runnable that will be executed. 12128 * 12129 * @return Returns true if the Runnable was successfully placed in to the 12130 * message queue. Returns false on failure, usually because the 12131 * looper processing the message queue is exiting. 12132 * 12133 * @see #postDelayed 12134 * @see #removeCallbacks 12135 */ 12136 public boolean post(Runnable action) { 12137 final AttachInfo attachInfo = mAttachInfo; 12138 if (attachInfo != null) { 12139 return attachInfo.mHandler.post(action); 12140 } 12141 // Assume that post will succeed later 12142 ViewRootImpl.getRunQueue().post(action); 12143 return true; 12144 } 12145 12146 /** 12147 * <p>Causes the Runnable to be added to the message queue, to be run 12148 * after the specified amount of time elapses. 12149 * The runnable will be run on the user interface thread.</p> 12150 * 12151 * @param action The Runnable that will be executed. 12152 * @param delayMillis The delay (in milliseconds) until the Runnable 12153 * will be executed. 12154 * 12155 * @return true if the Runnable was successfully placed in to the 12156 * message queue. Returns false on failure, usually because the 12157 * looper processing the message queue is exiting. Note that a 12158 * result of true does not mean the Runnable will be processed -- 12159 * if the looper is quit before the delivery time of the message 12160 * occurs then the message will be dropped. 12161 * 12162 * @see #post 12163 * @see #removeCallbacks 12164 */ 12165 public boolean postDelayed(Runnable action, long delayMillis) { 12166 final AttachInfo attachInfo = mAttachInfo; 12167 if (attachInfo != null) { 12168 return attachInfo.mHandler.postDelayed(action, delayMillis); 12169 } 12170 // Assume that post will succeed later 12171 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 12172 return true; 12173 } 12174 12175 /** 12176 * <p>Causes the Runnable to execute on the next animation time step. 12177 * The runnable will be run on the user interface thread.</p> 12178 * 12179 * @param action The Runnable that will be executed. 12180 * 12181 * @see #postOnAnimationDelayed 12182 * @see #removeCallbacks 12183 */ 12184 public void postOnAnimation(Runnable action) { 12185 final AttachInfo attachInfo = mAttachInfo; 12186 if (attachInfo != null) { 12187 attachInfo.mViewRootImpl.mChoreographer.postCallback( 12188 Choreographer.CALLBACK_ANIMATION, action, null); 12189 } else { 12190 // Assume that post will succeed later 12191 ViewRootImpl.getRunQueue().post(action); 12192 } 12193 } 12194 12195 /** 12196 * <p>Causes the Runnable to execute on the next animation time step, 12197 * after the specified amount of time elapses. 12198 * The runnable will be run on the user interface thread.</p> 12199 * 12200 * @param action The Runnable that will be executed. 12201 * @param delayMillis The delay (in milliseconds) until the Runnable 12202 * will be executed. 12203 * 12204 * @see #postOnAnimation 12205 * @see #removeCallbacks 12206 */ 12207 public void postOnAnimationDelayed(Runnable action, long delayMillis) { 12208 final AttachInfo attachInfo = mAttachInfo; 12209 if (attachInfo != null) { 12210 attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 12211 Choreographer.CALLBACK_ANIMATION, action, null, delayMillis); 12212 } else { 12213 // Assume that post will succeed later 12214 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 12215 } 12216 } 12217 12218 /** 12219 * <p>Removes the specified Runnable from the message queue.</p> 12220 * 12221 * @param action The Runnable to remove from the message handling queue 12222 * 12223 * @return true if this view could ask the Handler to remove the Runnable, 12224 * false otherwise. When the returned value is true, the Runnable 12225 * may or may not have been actually removed from the message queue 12226 * (for instance, if the Runnable was not in the queue already.) 12227 * 12228 * @see #post 12229 * @see #postDelayed 12230 * @see #postOnAnimation 12231 * @see #postOnAnimationDelayed 12232 */ 12233 public boolean removeCallbacks(Runnable action) { 12234 if (action != null) { 12235 final AttachInfo attachInfo = mAttachInfo; 12236 if (attachInfo != null) { 12237 attachInfo.mHandler.removeCallbacks(action); 12238 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 12239 Choreographer.CALLBACK_ANIMATION, action, null); 12240 } 12241 // Assume that post will succeed later 12242 ViewRootImpl.getRunQueue().removeCallbacks(action); 12243 } 12244 return true; 12245 } 12246 12247 /** 12248 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 12249 * Use this to invalidate the View from a non-UI thread.</p> 12250 * 12251 * <p>This method can be invoked from outside of the UI thread 12252 * only when this View is attached to a window.</p> 12253 * 12254 * @see #invalidate() 12255 * @see #postInvalidateDelayed(long) 12256 */ 12257 public void postInvalidate() { 12258 postInvalidateDelayed(0); 12259 } 12260 12261 /** 12262 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 12263 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 12264 * 12265 * <p>This method can be invoked from outside of the UI thread 12266 * only when this View is attached to a window.</p> 12267 * 12268 * @param left The left coordinate of the rectangle to invalidate. 12269 * @param top The top coordinate of the rectangle to invalidate. 12270 * @param right The right coordinate of the rectangle to invalidate. 12271 * @param bottom The bottom coordinate of the rectangle to invalidate. 12272 * 12273 * @see #invalidate(int, int, int, int) 12274 * @see #invalidate(Rect) 12275 * @see #postInvalidateDelayed(long, int, int, int, int) 12276 */ 12277 public void postInvalidate(int left, int top, int right, int bottom) { 12278 postInvalidateDelayed(0, left, top, right, bottom); 12279 } 12280 12281 /** 12282 * <p>Cause an invalidate to happen on a subsequent cycle through the event 12283 * loop. Waits for the specified amount of time.</p> 12284 * 12285 * <p>This method can be invoked from outside of the UI thread 12286 * only when this View is attached to a window.</p> 12287 * 12288 * @param delayMilliseconds the duration in milliseconds to delay the 12289 * invalidation by 12290 * 12291 * @see #invalidate() 12292 * @see #postInvalidate() 12293 */ 12294 public void postInvalidateDelayed(long delayMilliseconds) { 12295 // We try only with the AttachInfo because there's no point in invalidating 12296 // if we are not attached to our window 12297 final AttachInfo attachInfo = mAttachInfo; 12298 if (attachInfo != null) { 12299 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); 12300 } 12301 } 12302 12303 /** 12304 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 12305 * through the event loop. Waits for the specified amount of time.</p> 12306 * 12307 * <p>This method can be invoked from outside of the UI thread 12308 * only when this View is attached to a window.</p> 12309 * 12310 * @param delayMilliseconds the duration in milliseconds to delay the 12311 * invalidation by 12312 * @param left The left coordinate of the rectangle to invalidate. 12313 * @param top The top coordinate of the rectangle to invalidate. 12314 * @param right The right coordinate of the rectangle to invalidate. 12315 * @param bottom The bottom coordinate of the rectangle to invalidate. 12316 * 12317 * @see #invalidate(int, int, int, int) 12318 * @see #invalidate(Rect) 12319 * @see #postInvalidate(int, int, int, int) 12320 */ 12321 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 12322 int right, int bottom) { 12323 12324 // We try only with the AttachInfo because there's no point in invalidating 12325 // if we are not attached to our window 12326 final AttachInfo attachInfo = mAttachInfo; 12327 if (attachInfo != null) { 12328 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 12329 info.target = this; 12330 info.left = left; 12331 info.top = top; 12332 info.right = right; 12333 info.bottom = bottom; 12334 12335 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); 12336 } 12337 } 12338 12339 /** 12340 * <p>Cause an invalidate to happen on the next animation time step, typically the 12341 * next display frame.</p> 12342 * 12343 * <p>This method can be invoked from outside of the UI thread 12344 * only when this View is attached to a window.</p> 12345 * 12346 * @see #invalidate() 12347 */ 12348 public void postInvalidateOnAnimation() { 12349 // We try only with the AttachInfo because there's no point in invalidating 12350 // if we are not attached to our window 12351 final AttachInfo attachInfo = mAttachInfo; 12352 if (attachInfo != null) { 12353 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); 12354 } 12355 } 12356 12357 /** 12358 * <p>Cause an invalidate of the specified area to happen on the next animation 12359 * time step, typically the next display frame.</p> 12360 * 12361 * <p>This method can be invoked from outside of the UI thread 12362 * only when this View is attached to a window.</p> 12363 * 12364 * @param left The left coordinate of the rectangle to invalidate. 12365 * @param top The top coordinate of the rectangle to invalidate. 12366 * @param right The right coordinate of the rectangle to invalidate. 12367 * @param bottom The bottom coordinate of the rectangle to invalidate. 12368 * 12369 * @see #invalidate(int, int, int, int) 12370 * @see #invalidate(Rect) 12371 */ 12372 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { 12373 // We try only with the AttachInfo because there's no point in invalidating 12374 // if we are not attached to our window 12375 final AttachInfo attachInfo = mAttachInfo; 12376 if (attachInfo != null) { 12377 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 12378 info.target = this; 12379 info.left = left; 12380 info.top = top; 12381 info.right = right; 12382 info.bottom = bottom; 12383 12384 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); 12385 } 12386 } 12387 12388 /** 12389 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 12390 * This event is sent at most once every 12391 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 12392 */ 12393 private void postSendViewScrolledAccessibilityEventCallback() { 12394 if (mSendViewScrolledAccessibilityEvent == null) { 12395 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 12396 } 12397 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 12398 mSendViewScrolledAccessibilityEvent.mIsPending = true; 12399 postDelayed(mSendViewScrolledAccessibilityEvent, 12400 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 12401 } 12402 } 12403 12404 /** 12405 * Called by a parent to request that a child update its values for mScrollX 12406 * and mScrollY if necessary. This will typically be done if the child is 12407 * animating a scroll using a {@link android.widget.Scroller Scroller} 12408 * object. 12409 */ 12410 public void computeScroll() { 12411 } 12412 12413 /** 12414 * <p>Indicate whether the horizontal edges are faded when the view is 12415 * scrolled horizontally.</p> 12416 * 12417 * @return true if the horizontal edges should are faded on scroll, false 12418 * otherwise 12419 * 12420 * @see #setHorizontalFadingEdgeEnabled(boolean) 12421 * 12422 * @attr ref android.R.styleable#View_requiresFadingEdge 12423 */ 12424 public boolean isHorizontalFadingEdgeEnabled() { 12425 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 12426 } 12427 12428 /** 12429 * <p>Define whether the horizontal edges should be faded when this view 12430 * is scrolled horizontally.</p> 12431 * 12432 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 12433 * be faded when the view is scrolled 12434 * horizontally 12435 * 12436 * @see #isHorizontalFadingEdgeEnabled() 12437 * 12438 * @attr ref android.R.styleable#View_requiresFadingEdge 12439 */ 12440 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 12441 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 12442 if (horizontalFadingEdgeEnabled) { 12443 initScrollCache(); 12444 } 12445 12446 mViewFlags ^= FADING_EDGE_HORIZONTAL; 12447 } 12448 } 12449 12450 /** 12451 * <p>Indicate whether the vertical edges are faded when the view is 12452 * scrolled horizontally.</p> 12453 * 12454 * @return true if the vertical edges should are faded on scroll, false 12455 * otherwise 12456 * 12457 * @see #setVerticalFadingEdgeEnabled(boolean) 12458 * 12459 * @attr ref android.R.styleable#View_requiresFadingEdge 12460 */ 12461 public boolean isVerticalFadingEdgeEnabled() { 12462 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 12463 } 12464 12465 /** 12466 * <p>Define whether the vertical edges should be faded when this view 12467 * is scrolled vertically.</p> 12468 * 12469 * @param verticalFadingEdgeEnabled true if the vertical edges should 12470 * be faded when the view is scrolled 12471 * vertically 12472 * 12473 * @see #isVerticalFadingEdgeEnabled() 12474 * 12475 * @attr ref android.R.styleable#View_requiresFadingEdge 12476 */ 12477 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 12478 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 12479 if (verticalFadingEdgeEnabled) { 12480 initScrollCache(); 12481 } 12482 12483 mViewFlags ^= FADING_EDGE_VERTICAL; 12484 } 12485 } 12486 12487 /** 12488 * Returns the strength, or intensity, of the top faded edge. The strength is 12489 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12490 * returns 0.0 or 1.0 but no value in between. 12491 * 12492 * Subclasses should override this method to provide a smoother fade transition 12493 * when scrolling occurs. 12494 * 12495 * @return the intensity of the top fade as a float between 0.0f and 1.0f 12496 */ 12497 protected float getTopFadingEdgeStrength() { 12498 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 12499 } 12500 12501 /** 12502 * Returns the strength, or intensity, of the bottom faded edge. The strength is 12503 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12504 * returns 0.0 or 1.0 but no value in between. 12505 * 12506 * Subclasses should override this method to provide a smoother fade transition 12507 * when scrolling occurs. 12508 * 12509 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 12510 */ 12511 protected float getBottomFadingEdgeStrength() { 12512 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 12513 computeVerticalScrollRange() ? 1.0f : 0.0f; 12514 } 12515 12516 /** 12517 * Returns the strength, or intensity, of the left faded edge. The strength is 12518 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12519 * returns 0.0 or 1.0 but no value in between. 12520 * 12521 * Subclasses should override this method to provide a smoother fade transition 12522 * when scrolling occurs. 12523 * 12524 * @return the intensity of the left fade as a float between 0.0f and 1.0f 12525 */ 12526 protected float getLeftFadingEdgeStrength() { 12527 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 12528 } 12529 12530 /** 12531 * Returns the strength, or intensity, of the right faded edge. The strength is 12532 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12533 * returns 0.0 or 1.0 but no value in between. 12534 * 12535 * Subclasses should override this method to provide a smoother fade transition 12536 * when scrolling occurs. 12537 * 12538 * @return the intensity of the right fade as a float between 0.0f and 1.0f 12539 */ 12540 protected float getRightFadingEdgeStrength() { 12541 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 12542 computeHorizontalScrollRange() ? 1.0f : 0.0f; 12543 } 12544 12545 /** 12546 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 12547 * scrollbar is not drawn by default.</p> 12548 * 12549 * @return true if the horizontal scrollbar should be painted, false 12550 * otherwise 12551 * 12552 * @see #setHorizontalScrollBarEnabled(boolean) 12553 */ 12554 public boolean isHorizontalScrollBarEnabled() { 12555 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 12556 } 12557 12558 /** 12559 * <p>Define whether the horizontal scrollbar should be drawn or not. The 12560 * scrollbar is not drawn by default.</p> 12561 * 12562 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 12563 * be painted 12564 * 12565 * @see #isHorizontalScrollBarEnabled() 12566 */ 12567 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 12568 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 12569 mViewFlags ^= SCROLLBARS_HORIZONTAL; 12570 computeOpaqueFlags(); 12571 resolvePadding(); 12572 } 12573 } 12574 12575 /** 12576 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 12577 * scrollbar is not drawn by default.</p> 12578 * 12579 * @return true if the vertical scrollbar should be painted, false 12580 * otherwise 12581 * 12582 * @see #setVerticalScrollBarEnabled(boolean) 12583 */ 12584 public boolean isVerticalScrollBarEnabled() { 12585 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 12586 } 12587 12588 /** 12589 * <p>Define whether the vertical scrollbar should be drawn or not. The 12590 * scrollbar is not drawn by default.</p> 12591 * 12592 * @param verticalScrollBarEnabled true if the vertical scrollbar should 12593 * be painted 12594 * 12595 * @see #isVerticalScrollBarEnabled() 12596 */ 12597 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 12598 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 12599 mViewFlags ^= SCROLLBARS_VERTICAL; 12600 computeOpaqueFlags(); 12601 resolvePadding(); 12602 } 12603 } 12604 12605 /** 12606 * @hide 12607 */ 12608 protected void recomputePadding() { 12609 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 12610 } 12611 12612 /** 12613 * Define whether scrollbars will fade when the view is not scrolling. 12614 * 12615 * @param fadeScrollbars wheter to enable fading 12616 * 12617 * @attr ref android.R.styleable#View_fadeScrollbars 12618 */ 12619 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 12620 initScrollCache(); 12621 final ScrollabilityCache scrollabilityCache = mScrollCache; 12622 scrollabilityCache.fadeScrollBars = fadeScrollbars; 12623 if (fadeScrollbars) { 12624 scrollabilityCache.state = ScrollabilityCache.OFF; 12625 } else { 12626 scrollabilityCache.state = ScrollabilityCache.ON; 12627 } 12628 } 12629 12630 /** 12631 * 12632 * Returns true if scrollbars will fade when this view is not scrolling 12633 * 12634 * @return true if scrollbar fading is enabled 12635 * 12636 * @attr ref android.R.styleable#View_fadeScrollbars 12637 */ 12638 public boolean isScrollbarFadingEnabled() { 12639 return mScrollCache != null && mScrollCache.fadeScrollBars; 12640 } 12641 12642 /** 12643 * 12644 * Returns the delay before scrollbars fade. 12645 * 12646 * @return the delay before scrollbars fade 12647 * 12648 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 12649 */ 12650 public int getScrollBarDefaultDelayBeforeFade() { 12651 return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() : 12652 mScrollCache.scrollBarDefaultDelayBeforeFade; 12653 } 12654 12655 /** 12656 * Define the delay before scrollbars fade. 12657 * 12658 * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade 12659 * 12660 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 12661 */ 12662 public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) { 12663 getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade; 12664 } 12665 12666 /** 12667 * 12668 * Returns the scrollbar fade duration. 12669 * 12670 * @return the scrollbar fade duration 12671 * 12672 * @attr ref android.R.styleable#View_scrollbarFadeDuration 12673 */ 12674 public int getScrollBarFadeDuration() { 12675 return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() : 12676 mScrollCache.scrollBarFadeDuration; 12677 } 12678 12679 /** 12680 * Define the scrollbar fade duration. 12681 * 12682 * @param scrollBarFadeDuration - the scrollbar fade duration 12683 * 12684 * @attr ref android.R.styleable#View_scrollbarFadeDuration 12685 */ 12686 public void setScrollBarFadeDuration(int scrollBarFadeDuration) { 12687 getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration; 12688 } 12689 12690 /** 12691 * 12692 * Returns the scrollbar size. 12693 * 12694 * @return the scrollbar size 12695 * 12696 * @attr ref android.R.styleable#View_scrollbarSize 12697 */ 12698 public int getScrollBarSize() { 12699 return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() : 12700 mScrollCache.scrollBarSize; 12701 } 12702 12703 /** 12704 * Define the scrollbar size. 12705 * 12706 * @param scrollBarSize - the scrollbar size 12707 * 12708 * @attr ref android.R.styleable#View_scrollbarSize 12709 */ 12710 public void setScrollBarSize(int scrollBarSize) { 12711 getScrollCache().scrollBarSize = scrollBarSize; 12712 } 12713 12714 /** 12715 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 12716 * inset. When inset, they add to the padding of the view. And the scrollbars 12717 * can be drawn inside the padding area or on the edge of the view. For example, 12718 * if a view has a background drawable and you want to draw the scrollbars 12719 * inside the padding specified by the drawable, you can use 12720 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 12721 * appear at the edge of the view, ignoring the padding, then you can use 12722 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 12723 * @param style the style of the scrollbars. Should be one of 12724 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 12725 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 12726 * @see #SCROLLBARS_INSIDE_OVERLAY 12727 * @see #SCROLLBARS_INSIDE_INSET 12728 * @see #SCROLLBARS_OUTSIDE_OVERLAY 12729 * @see #SCROLLBARS_OUTSIDE_INSET 12730 * 12731 * @attr ref android.R.styleable#View_scrollbarStyle 12732 */ 12733 public void setScrollBarStyle(@ScrollBarStyle int style) { 12734 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 12735 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 12736 computeOpaqueFlags(); 12737 resolvePadding(); 12738 } 12739 } 12740 12741 /** 12742 * <p>Returns the current scrollbar style.</p> 12743 * @return the current scrollbar style 12744 * @see #SCROLLBARS_INSIDE_OVERLAY 12745 * @see #SCROLLBARS_INSIDE_INSET 12746 * @see #SCROLLBARS_OUTSIDE_OVERLAY 12747 * @see #SCROLLBARS_OUTSIDE_INSET 12748 * 12749 * @attr ref android.R.styleable#View_scrollbarStyle 12750 */ 12751 @ViewDebug.ExportedProperty(mapping = { 12752 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 12753 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 12754 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 12755 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 12756 }) 12757 @ScrollBarStyle 12758 public int getScrollBarStyle() { 12759 return mViewFlags & SCROLLBARS_STYLE_MASK; 12760 } 12761 12762 /** 12763 * <p>Compute the horizontal range that the horizontal scrollbar 12764 * represents.</p> 12765 * 12766 * <p>The range is expressed in arbitrary units that must be the same as the 12767 * units used by {@link #computeHorizontalScrollExtent()} and 12768 * {@link #computeHorizontalScrollOffset()}.</p> 12769 * 12770 * <p>The default range is the drawing width of this view.</p> 12771 * 12772 * @return the total horizontal range represented by the horizontal 12773 * scrollbar 12774 * 12775 * @see #computeHorizontalScrollExtent() 12776 * @see #computeHorizontalScrollOffset() 12777 * @see android.widget.ScrollBarDrawable 12778 */ 12779 protected int computeHorizontalScrollRange() { 12780 return getWidth(); 12781 } 12782 12783 /** 12784 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 12785 * within the horizontal range. This value is used to compute the position 12786 * of the thumb within the scrollbar's track.</p> 12787 * 12788 * <p>The range is expressed in arbitrary units that must be the same as the 12789 * units used by {@link #computeHorizontalScrollRange()} and 12790 * {@link #computeHorizontalScrollExtent()}.</p> 12791 * 12792 * <p>The default offset is the scroll offset of this view.</p> 12793 * 12794 * @return the horizontal offset of the scrollbar's thumb 12795 * 12796 * @see #computeHorizontalScrollRange() 12797 * @see #computeHorizontalScrollExtent() 12798 * @see android.widget.ScrollBarDrawable 12799 */ 12800 protected int computeHorizontalScrollOffset() { 12801 return mScrollX; 12802 } 12803 12804 /** 12805 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 12806 * within the horizontal range. This value is used to compute the length 12807 * of the thumb within the scrollbar's track.</p> 12808 * 12809 * <p>The range is expressed in arbitrary units that must be the same as the 12810 * units used by {@link #computeHorizontalScrollRange()} and 12811 * {@link #computeHorizontalScrollOffset()}.</p> 12812 * 12813 * <p>The default extent is the drawing width of this view.</p> 12814 * 12815 * @return the horizontal extent of the scrollbar's thumb 12816 * 12817 * @see #computeHorizontalScrollRange() 12818 * @see #computeHorizontalScrollOffset() 12819 * @see android.widget.ScrollBarDrawable 12820 */ 12821 protected int computeHorizontalScrollExtent() { 12822 return getWidth(); 12823 } 12824 12825 /** 12826 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 12827 * 12828 * <p>The range is expressed in arbitrary units that must be the same as the 12829 * units used by {@link #computeVerticalScrollExtent()} and 12830 * {@link #computeVerticalScrollOffset()}.</p> 12831 * 12832 * @return the total vertical range represented by the vertical scrollbar 12833 * 12834 * <p>The default range is the drawing height of this view.</p> 12835 * 12836 * @see #computeVerticalScrollExtent() 12837 * @see #computeVerticalScrollOffset() 12838 * @see android.widget.ScrollBarDrawable 12839 */ 12840 protected int computeVerticalScrollRange() { 12841 return getHeight(); 12842 } 12843 12844 /** 12845 * <p>Compute the vertical offset of the vertical scrollbar's thumb 12846 * within the horizontal range. This value is used to compute the position 12847 * of the thumb within the scrollbar's track.</p> 12848 * 12849 * <p>The range is expressed in arbitrary units that must be the same as the 12850 * units used by {@link #computeVerticalScrollRange()} and 12851 * {@link #computeVerticalScrollExtent()}.</p> 12852 * 12853 * <p>The default offset is the scroll offset of this view.</p> 12854 * 12855 * @return the vertical offset of the scrollbar's thumb 12856 * 12857 * @see #computeVerticalScrollRange() 12858 * @see #computeVerticalScrollExtent() 12859 * @see android.widget.ScrollBarDrawable 12860 */ 12861 protected int computeVerticalScrollOffset() { 12862 return mScrollY; 12863 } 12864 12865 /** 12866 * <p>Compute the vertical extent of the vertical scrollbar's thumb 12867 * within the vertical range. This value is used to compute the length 12868 * of the thumb within the scrollbar's track.</p> 12869 * 12870 * <p>The range is expressed in arbitrary units that must be the same as the 12871 * units used by {@link #computeVerticalScrollRange()} and 12872 * {@link #computeVerticalScrollOffset()}.</p> 12873 * 12874 * <p>The default extent is the drawing height of this view.</p> 12875 * 12876 * @return the vertical extent of the scrollbar's thumb 12877 * 12878 * @see #computeVerticalScrollRange() 12879 * @see #computeVerticalScrollOffset() 12880 * @see android.widget.ScrollBarDrawable 12881 */ 12882 protected int computeVerticalScrollExtent() { 12883 return getHeight(); 12884 } 12885 12886 /** 12887 * Check if this view can be scrolled horizontally in a certain direction. 12888 * 12889 * @param direction Negative to check scrolling left, positive to check scrolling right. 12890 * @return true if this view can be scrolled in the specified direction, false otherwise. 12891 */ 12892 public boolean canScrollHorizontally(int direction) { 12893 final int offset = computeHorizontalScrollOffset(); 12894 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 12895 if (range == 0) return false; 12896 if (direction < 0) { 12897 return offset > 0; 12898 } else { 12899 return offset < range - 1; 12900 } 12901 } 12902 12903 /** 12904 * Check if this view can be scrolled vertically in a certain direction. 12905 * 12906 * @param direction Negative to check scrolling up, positive to check scrolling down. 12907 * @return true if this view can be scrolled in the specified direction, false otherwise. 12908 */ 12909 public boolean canScrollVertically(int direction) { 12910 final int offset = computeVerticalScrollOffset(); 12911 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 12912 if (range == 0) return false; 12913 if (direction < 0) { 12914 return offset > 0; 12915 } else { 12916 return offset < range - 1; 12917 } 12918 } 12919 12920 /** 12921 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 12922 * scrollbars are painted only if they have been awakened first.</p> 12923 * 12924 * @param canvas the canvas on which to draw the scrollbars 12925 * 12926 * @see #awakenScrollBars(int) 12927 */ 12928 protected final void onDrawScrollBars(Canvas canvas) { 12929 // scrollbars are drawn only when the animation is running 12930 final ScrollabilityCache cache = mScrollCache; 12931 if (cache != null) { 12932 12933 int state = cache.state; 12934 12935 if (state == ScrollabilityCache.OFF) { 12936 return; 12937 } 12938 12939 boolean invalidate = false; 12940 12941 if (state == ScrollabilityCache.FADING) { 12942 // We're fading -- get our fade interpolation 12943 if (cache.interpolatorValues == null) { 12944 cache.interpolatorValues = new float[1]; 12945 } 12946 12947 float[] values = cache.interpolatorValues; 12948 12949 // Stops the animation if we're done 12950 if (cache.scrollBarInterpolator.timeToValues(values) == 12951 Interpolator.Result.FREEZE_END) { 12952 cache.state = ScrollabilityCache.OFF; 12953 } else { 12954 cache.scrollBar.setAlpha(Math.round(values[0])); 12955 } 12956 12957 // This will make the scroll bars inval themselves after 12958 // drawing. We only want this when we're fading so that 12959 // we prevent excessive redraws 12960 invalidate = true; 12961 } else { 12962 // We're just on -- but we may have been fading before so 12963 // reset alpha 12964 cache.scrollBar.setAlpha(255); 12965 } 12966 12967 12968 final int viewFlags = mViewFlags; 12969 12970 final boolean drawHorizontalScrollBar = 12971 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 12972 final boolean drawVerticalScrollBar = 12973 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 12974 && !isVerticalScrollBarHidden(); 12975 12976 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 12977 final int width = mRight - mLeft; 12978 final int height = mBottom - mTop; 12979 12980 final ScrollBarDrawable scrollBar = cache.scrollBar; 12981 12982 final int scrollX = mScrollX; 12983 final int scrollY = mScrollY; 12984 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 12985 12986 int left; 12987 int top; 12988 int right; 12989 int bottom; 12990 12991 if (drawHorizontalScrollBar) { 12992 int size = scrollBar.getSize(false); 12993 if (size <= 0) { 12994 size = cache.scrollBarSize; 12995 } 12996 12997 scrollBar.setParameters(computeHorizontalScrollRange(), 12998 computeHorizontalScrollOffset(), 12999 computeHorizontalScrollExtent(), false); 13000 final int verticalScrollBarGap = drawVerticalScrollBar ? 13001 getVerticalScrollbarWidth() : 0; 13002 top = scrollY + height - size - (mUserPaddingBottom & inside); 13003 left = scrollX + (mPaddingLeft & inside); 13004 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 13005 bottom = top + size; 13006 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 13007 if (invalidate) { 13008 invalidate(left, top, right, bottom); 13009 } 13010 } 13011 13012 if (drawVerticalScrollBar) { 13013 int size = scrollBar.getSize(true); 13014 if (size <= 0) { 13015 size = cache.scrollBarSize; 13016 } 13017 13018 scrollBar.setParameters(computeVerticalScrollRange(), 13019 computeVerticalScrollOffset(), 13020 computeVerticalScrollExtent(), true); 13021 int verticalScrollbarPosition = mVerticalScrollbarPosition; 13022 if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) { 13023 verticalScrollbarPosition = isLayoutRtl() ? 13024 SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT; 13025 } 13026 switch (verticalScrollbarPosition) { 13027 default: 13028 case SCROLLBAR_POSITION_RIGHT: 13029 left = scrollX + width - size - (mUserPaddingRight & inside); 13030 break; 13031 case SCROLLBAR_POSITION_LEFT: 13032 left = scrollX + (mUserPaddingLeft & inside); 13033 break; 13034 } 13035 top = scrollY + (mPaddingTop & inside); 13036 right = left + size; 13037 bottom = scrollY + height - (mUserPaddingBottom & inside); 13038 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 13039 if (invalidate) { 13040 invalidate(left, top, right, bottom); 13041 } 13042 } 13043 } 13044 } 13045 } 13046 13047 /** 13048 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 13049 * FastScroller is visible. 13050 * @return whether to temporarily hide the vertical scrollbar 13051 * @hide 13052 */ 13053 protected boolean isVerticalScrollBarHidden() { 13054 return false; 13055 } 13056 13057 /** 13058 * <p>Draw the horizontal scrollbar if 13059 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 13060 * 13061 * @param canvas the canvas on which to draw the scrollbar 13062 * @param scrollBar the scrollbar's drawable 13063 * 13064 * @see #isHorizontalScrollBarEnabled() 13065 * @see #computeHorizontalScrollRange() 13066 * @see #computeHorizontalScrollExtent() 13067 * @see #computeHorizontalScrollOffset() 13068 * @see android.widget.ScrollBarDrawable 13069 * @hide 13070 */ 13071 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 13072 int l, int t, int r, int b) { 13073 scrollBar.setBounds(l, t, r, b); 13074 scrollBar.draw(canvas); 13075 } 13076 13077 /** 13078 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 13079 * returns true.</p> 13080 * 13081 * @param canvas the canvas on which to draw the scrollbar 13082 * @param scrollBar the scrollbar's drawable 13083 * 13084 * @see #isVerticalScrollBarEnabled() 13085 * @see #computeVerticalScrollRange() 13086 * @see #computeVerticalScrollExtent() 13087 * @see #computeVerticalScrollOffset() 13088 * @see android.widget.ScrollBarDrawable 13089 * @hide 13090 */ 13091 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 13092 int l, int t, int r, int b) { 13093 scrollBar.setBounds(l, t, r, b); 13094 scrollBar.draw(canvas); 13095 } 13096 13097 /** 13098 * Implement this to do your drawing. 13099 * 13100 * @param canvas the canvas on which the background will be drawn 13101 */ 13102 protected void onDraw(Canvas canvas) { 13103 } 13104 13105 /* 13106 * Caller is responsible for calling requestLayout if necessary. 13107 * (This allows addViewInLayout to not request a new layout.) 13108 */ 13109 void assignParent(ViewParent parent) { 13110 if (mParent == null) { 13111 mParent = parent; 13112 } else if (parent == null) { 13113 mParent = null; 13114 } else { 13115 throw new RuntimeException("view " + this + " being added, but" 13116 + " it already has a parent"); 13117 } 13118 } 13119 13120 /** 13121 * This is called when the view is attached to a window. At this point it 13122 * has a Surface and will start drawing. Note that this function is 13123 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 13124 * however it may be called any time before the first onDraw -- including 13125 * before or after {@link #onMeasure(int, int)}. 13126 * 13127 * @see #onDetachedFromWindow() 13128 */ 13129 protected void onAttachedToWindow() { 13130 if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 13131 mParent.requestTransparentRegion(this); 13132 } 13133 13134 if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { 13135 initialAwakenScrollBars(); 13136 mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 13137 } 13138 13139 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 13140 13141 jumpDrawablesToCurrentState(); 13142 13143 resetSubtreeAccessibilityStateChanged(); 13144 13145 // rebuild, since Outline not maintained while View is detached 13146 rebuildOutline(); 13147 13148 if (isFocused()) { 13149 InputMethodManager imm = InputMethodManager.peekInstance(); 13150 imm.focusIn(this); 13151 } 13152 } 13153 13154 /** 13155 * Resolve all RTL related properties. 13156 * 13157 * @return true if resolution of RTL properties has been done 13158 * 13159 * @hide 13160 */ 13161 public boolean resolveRtlPropertiesIfNeeded() { 13162 if (!needRtlPropertiesResolution()) return false; 13163 13164 // Order is important here: LayoutDirection MUST be resolved first 13165 if (!isLayoutDirectionResolved()) { 13166 resolveLayoutDirection(); 13167 resolveLayoutParams(); 13168 } 13169 // ... then we can resolve the others properties depending on the resolved LayoutDirection. 13170 if (!isTextDirectionResolved()) { 13171 resolveTextDirection(); 13172 } 13173 if (!isTextAlignmentResolved()) { 13174 resolveTextAlignment(); 13175 } 13176 // Should resolve Drawables before Padding because we need the layout direction of the 13177 // Drawable to correctly resolve Padding. 13178 if (!isDrawablesResolved()) { 13179 resolveDrawables(); 13180 } 13181 if (!isPaddingResolved()) { 13182 resolvePadding(); 13183 } 13184 onRtlPropertiesChanged(getLayoutDirection()); 13185 return true; 13186 } 13187 13188 /** 13189 * Reset resolution of all RTL related properties. 13190 * 13191 * @hide 13192 */ 13193 public void resetRtlProperties() { 13194 resetResolvedLayoutDirection(); 13195 resetResolvedTextDirection(); 13196 resetResolvedTextAlignment(); 13197 resetResolvedPadding(); 13198 resetResolvedDrawables(); 13199 } 13200 13201 /** 13202 * @see #onScreenStateChanged(int) 13203 */ 13204 void dispatchScreenStateChanged(int screenState) { 13205 onScreenStateChanged(screenState); 13206 } 13207 13208 /** 13209 * This method is called whenever the state of the screen this view is 13210 * attached to changes. A state change will usually occurs when the screen 13211 * turns on or off (whether it happens automatically or the user does it 13212 * manually.) 13213 * 13214 * @param screenState The new state of the screen. Can be either 13215 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF} 13216 */ 13217 public void onScreenStateChanged(int screenState) { 13218 } 13219 13220 /** 13221 * Return true if the application tag in the AndroidManifest has set "supportRtl" to true 13222 */ 13223 private boolean hasRtlSupport() { 13224 return mContext.getApplicationInfo().hasRtlSupport(); 13225 } 13226 13227 /** 13228 * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or 13229 * RTL not supported) 13230 */ 13231 private boolean isRtlCompatibilityMode() { 13232 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 13233 return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport(); 13234 } 13235 13236 /** 13237 * @return true if RTL properties need resolution. 13238 * 13239 */ 13240 private boolean needRtlPropertiesResolution() { 13241 return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED; 13242 } 13243 13244 /** 13245 * Called when any RTL property (layout direction or text direction or text alignment) has 13246 * been changed. 13247 * 13248 * Subclasses need to override this method to take care of cached information that depends on the 13249 * resolved layout direction, or to inform child views that inherit their layout direction. 13250 * 13251 * The default implementation does nothing. 13252 * 13253 * @param layoutDirection the direction of the layout 13254 * 13255 * @see #LAYOUT_DIRECTION_LTR 13256 * @see #LAYOUT_DIRECTION_RTL 13257 */ 13258 public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) { 13259 } 13260 13261 /** 13262 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 13263 * that the parent directionality can and will be resolved before its children. 13264 * 13265 * @return true if resolution has been done, false otherwise. 13266 * 13267 * @hide 13268 */ 13269 public boolean resolveLayoutDirection() { 13270 // Clear any previous layout direction resolution 13271 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 13272 13273 if (hasRtlSupport()) { 13274 // Set resolved depending on layout direction 13275 switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> 13276 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) { 13277 case LAYOUT_DIRECTION_INHERIT: 13278 // We cannot resolve yet. LTR is by default and let the resolution happen again 13279 // later to get the correct resolved value 13280 if (!canResolveLayoutDirection()) return false; 13281 13282 // Parent has not yet resolved, LTR is still the default 13283 try { 13284 if (!mParent.isLayoutDirectionResolved()) return false; 13285 13286 if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 13287 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 13288 } 13289 } catch (AbstractMethodError e) { 13290 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 13291 " does not fully implement ViewParent", e); 13292 } 13293 break; 13294 case LAYOUT_DIRECTION_RTL: 13295 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 13296 break; 13297 case LAYOUT_DIRECTION_LOCALE: 13298 if((LAYOUT_DIRECTION_RTL == 13299 TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) { 13300 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 13301 } 13302 break; 13303 default: 13304 // Nothing to do, LTR by default 13305 } 13306 } 13307 13308 // Set to resolved 13309 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 13310 return true; 13311 } 13312 13313 /** 13314 * Check if layout direction resolution can be done. 13315 * 13316 * @return true if layout direction resolution can be done otherwise return false. 13317 */ 13318 public boolean canResolveLayoutDirection() { 13319 switch (getRawLayoutDirection()) { 13320 case LAYOUT_DIRECTION_INHERIT: 13321 if (mParent != null) { 13322 try { 13323 return mParent.canResolveLayoutDirection(); 13324 } catch (AbstractMethodError e) { 13325 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 13326 " does not fully implement ViewParent", e); 13327 } 13328 } 13329 return false; 13330 13331 default: 13332 return true; 13333 } 13334 } 13335 13336 /** 13337 * Reset the resolved layout direction. Layout direction will be resolved during a call to 13338 * {@link #onMeasure(int, int)}. 13339 * 13340 * @hide 13341 */ 13342 public void resetResolvedLayoutDirection() { 13343 // Reset the current resolved bits 13344 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 13345 } 13346 13347 /** 13348 * @return true if the layout direction is inherited. 13349 * 13350 * @hide 13351 */ 13352 public boolean isLayoutDirectionInherited() { 13353 return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT); 13354 } 13355 13356 /** 13357 * @return true if layout direction has been resolved. 13358 */ 13359 public boolean isLayoutDirectionResolved() { 13360 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED; 13361 } 13362 13363 /** 13364 * Return if padding has been resolved 13365 * 13366 * @hide 13367 */ 13368 boolean isPaddingResolved() { 13369 return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED; 13370 } 13371 13372 /** 13373 * Resolves padding depending on layout direction, if applicable, and 13374 * recomputes internal padding values to adjust for scroll bars. 13375 * 13376 * @hide 13377 */ 13378 public void resolvePadding() { 13379 final int resolvedLayoutDirection = getLayoutDirection(); 13380 13381 if (!isRtlCompatibilityMode()) { 13382 // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account. 13383 // If start / end padding are defined, they will be resolved (hence overriding) to 13384 // left / right or right / left depending on the resolved layout direction. 13385 // If start / end padding are not defined, use the left / right ones. 13386 if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) { 13387 Rect padding = sThreadLocal.get(); 13388 if (padding == null) { 13389 padding = new Rect(); 13390 sThreadLocal.set(padding); 13391 } 13392 mBackground.getPadding(padding); 13393 if (!mLeftPaddingDefined) { 13394 mUserPaddingLeftInitial = padding.left; 13395 } 13396 if (!mRightPaddingDefined) { 13397 mUserPaddingRightInitial = padding.right; 13398 } 13399 } 13400 switch (resolvedLayoutDirection) { 13401 case LAYOUT_DIRECTION_RTL: 13402 if (mUserPaddingStart != UNDEFINED_PADDING) { 13403 mUserPaddingRight = mUserPaddingStart; 13404 } else { 13405 mUserPaddingRight = mUserPaddingRightInitial; 13406 } 13407 if (mUserPaddingEnd != UNDEFINED_PADDING) { 13408 mUserPaddingLeft = mUserPaddingEnd; 13409 } else { 13410 mUserPaddingLeft = mUserPaddingLeftInitial; 13411 } 13412 break; 13413 case LAYOUT_DIRECTION_LTR: 13414 default: 13415 if (mUserPaddingStart != UNDEFINED_PADDING) { 13416 mUserPaddingLeft = mUserPaddingStart; 13417 } else { 13418 mUserPaddingLeft = mUserPaddingLeftInitial; 13419 } 13420 if (mUserPaddingEnd != UNDEFINED_PADDING) { 13421 mUserPaddingRight = mUserPaddingEnd; 13422 } else { 13423 mUserPaddingRight = mUserPaddingRightInitial; 13424 } 13425 } 13426 13427 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 13428 } 13429 13430 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 13431 onRtlPropertiesChanged(resolvedLayoutDirection); 13432 13433 mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED; 13434 } 13435 13436 /** 13437 * Reset the resolved layout direction. 13438 * 13439 * @hide 13440 */ 13441 public void resetResolvedPadding() { 13442 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 13443 } 13444 13445 /** 13446 * This is called when the view is detached from a window. At this point it 13447 * no longer has a surface for drawing. 13448 * 13449 * @see #onAttachedToWindow() 13450 */ 13451 protected void onDetachedFromWindow() { 13452 } 13453 13454 /** 13455 * This is a framework-internal mirror of onDetachedFromWindow() that's called 13456 * after onDetachedFromWindow(). 13457 * 13458 * If you override this you *MUST* call super.onDetachedFromWindowInternal()! 13459 * The super method should be called at the end of the overriden method to ensure 13460 * subclasses are destroyed first 13461 * 13462 * @hide 13463 */ 13464 protected void onDetachedFromWindowInternal() { 13465 mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT; 13466 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 13467 13468 removeUnsetPressCallback(); 13469 removeLongPressCallback(); 13470 removePerformClickCallback(); 13471 removeSendViewScrolledAccessibilityEventCallback(); 13472 stopNestedScroll(); 13473 13474 // Anything that started animating right before detach should already 13475 // be in its final state when re-attached. 13476 jumpDrawablesToCurrentState(); 13477 13478 destroyDrawingCache(); 13479 13480 cleanupDraw(); 13481 mCurrentAnimation = null; 13482 } 13483 13484 private void cleanupDraw() { 13485 resetDisplayList(); 13486 if (mAttachInfo != null) { 13487 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 13488 } 13489 } 13490 13491 void invalidateInheritedLayoutMode(int layoutModeOfRoot) { 13492 } 13493 13494 /** 13495 * @return The number of times this view has been attached to a window 13496 */ 13497 protected int getWindowAttachCount() { 13498 return mWindowAttachCount; 13499 } 13500 13501 /** 13502 * Retrieve a unique token identifying the window this view is attached to. 13503 * @return Return the window's token for use in 13504 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 13505 */ 13506 public IBinder getWindowToken() { 13507 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 13508 } 13509 13510 /** 13511 * Retrieve the {@link WindowId} for the window this view is 13512 * currently attached to. 13513 */ 13514 public WindowId getWindowId() { 13515 if (mAttachInfo == null) { 13516 return null; 13517 } 13518 if (mAttachInfo.mWindowId == null) { 13519 try { 13520 mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId( 13521 mAttachInfo.mWindowToken); 13522 mAttachInfo.mWindowId = new WindowId( 13523 mAttachInfo.mIWindowId); 13524 } catch (RemoteException e) { 13525 } 13526 } 13527 return mAttachInfo.mWindowId; 13528 } 13529 13530 /** 13531 * Retrieve a unique token identifying the top-level "real" window of 13532 * the window that this view is attached to. That is, this is like 13533 * {@link #getWindowToken}, except if the window this view in is a panel 13534 * window (attached to another containing window), then the token of 13535 * the containing window is returned instead. 13536 * 13537 * @return Returns the associated window token, either 13538 * {@link #getWindowToken()} or the containing window's token. 13539 */ 13540 public IBinder getApplicationWindowToken() { 13541 AttachInfo ai = mAttachInfo; 13542 if (ai != null) { 13543 IBinder appWindowToken = ai.mPanelParentWindowToken; 13544 if (appWindowToken == null) { 13545 appWindowToken = ai.mWindowToken; 13546 } 13547 return appWindowToken; 13548 } 13549 return null; 13550 } 13551 13552 /** 13553 * Gets the logical display to which the view's window has been attached. 13554 * 13555 * @return The logical display, or null if the view is not currently attached to a window. 13556 */ 13557 public Display getDisplay() { 13558 return mAttachInfo != null ? mAttachInfo.mDisplay : null; 13559 } 13560 13561 /** 13562 * Retrieve private session object this view hierarchy is using to 13563 * communicate with the window manager. 13564 * @return the session object to communicate with the window manager 13565 */ 13566 /*package*/ IWindowSession getWindowSession() { 13567 return mAttachInfo != null ? mAttachInfo.mSession : null; 13568 } 13569 13570 /** 13571 * @param info the {@link android.view.View.AttachInfo} to associated with 13572 * this view 13573 */ 13574 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 13575 //System.out.println("Attached! " + this); 13576 mAttachInfo = info; 13577 if (mOverlay != null) { 13578 mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility); 13579 } 13580 mWindowAttachCount++; 13581 // We will need to evaluate the drawable state at least once. 13582 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 13583 if (mFloatingTreeObserver != null) { 13584 info.mTreeObserver.merge(mFloatingTreeObserver); 13585 mFloatingTreeObserver = null; 13586 } 13587 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) { 13588 mAttachInfo.mScrollContainers.add(this); 13589 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 13590 } 13591 performCollectViewAttributes(mAttachInfo, visibility); 13592 onAttachedToWindow(); 13593 13594 ListenerInfo li = mListenerInfo; 13595 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 13596 li != null ? li.mOnAttachStateChangeListeners : null; 13597 if (listeners != null && listeners.size() > 0) { 13598 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 13599 // perform the dispatching. The iterator is a safe guard against listeners that 13600 // could mutate the list by calling the various add/remove methods. This prevents 13601 // the array from being modified while we iterate it. 13602 for (OnAttachStateChangeListener listener : listeners) { 13603 listener.onViewAttachedToWindow(this); 13604 } 13605 } 13606 13607 int vis = info.mWindowVisibility; 13608 if (vis != GONE) { 13609 onWindowVisibilityChanged(vis); 13610 } 13611 if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) { 13612 // If nobody has evaluated the drawable state yet, then do it now. 13613 refreshDrawableState(); 13614 } 13615 needGlobalAttributesUpdate(false); 13616 } 13617 13618 void dispatchDetachedFromWindow() { 13619 AttachInfo info = mAttachInfo; 13620 if (info != null) { 13621 int vis = info.mWindowVisibility; 13622 if (vis != GONE) { 13623 onWindowVisibilityChanged(GONE); 13624 } 13625 } 13626 13627 onDetachedFromWindow(); 13628 onDetachedFromWindowInternal(); 13629 13630 ListenerInfo li = mListenerInfo; 13631 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 13632 li != null ? li.mOnAttachStateChangeListeners : null; 13633 if (listeners != null && listeners.size() > 0) { 13634 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 13635 // perform the dispatching. The iterator is a safe guard against listeners that 13636 // could mutate the list by calling the various add/remove methods. This prevents 13637 // the array from being modified while we iterate it. 13638 for (OnAttachStateChangeListener listener : listeners) { 13639 listener.onViewDetachedFromWindow(this); 13640 } 13641 } 13642 13643 if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 13644 mAttachInfo.mScrollContainers.remove(this); 13645 mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED; 13646 } 13647 13648 mAttachInfo = null; 13649 if (mOverlay != null) { 13650 mOverlay.getOverlayView().dispatchDetachedFromWindow(); 13651 } 13652 } 13653 13654 /** 13655 * Cancel any deferred high-level input events that were previously posted to the event queue. 13656 * 13657 * <p>Many views post high-level events such as click handlers to the event queue 13658 * to run deferred in order to preserve a desired user experience - clearing visible 13659 * pressed states before executing, etc. This method will abort any events of this nature 13660 * that are currently in flight.</p> 13661 * 13662 * <p>Custom views that generate their own high-level deferred input events should override 13663 * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p> 13664 * 13665 * <p>This will also cancel pending input events for any child views.</p> 13666 * 13667 * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases. 13668 * This will not impact newer events posted after this call that may occur as a result of 13669 * lower-level input events still waiting in the queue. If you are trying to prevent 13670 * double-submitted events for the duration of some sort of asynchronous transaction 13671 * you should also take other steps to protect against unexpected double inputs e.g. calling 13672 * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when 13673 * the transaction completes, tracking already submitted transaction IDs, etc.</p> 13674 */ 13675 public final void cancelPendingInputEvents() { 13676 dispatchCancelPendingInputEvents(); 13677 } 13678 13679 /** 13680 * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight. 13681 * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling. 13682 */ 13683 void dispatchCancelPendingInputEvents() { 13684 mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER; 13685 onCancelPendingInputEvents(); 13686 if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) { 13687 throw new SuperNotCalledException("View " + getClass().getSimpleName() + 13688 " did not call through to super.onCancelPendingInputEvents()"); 13689 } 13690 } 13691 13692 /** 13693 * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or 13694 * a parent view. 13695 * 13696 * <p>This method is responsible for removing any pending high-level input events that were 13697 * posted to the event queue to run later. Custom view classes that post their own deferred 13698 * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or 13699 * {@link android.os.Handler} should override this method, call 13700 * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate. 13701 * </p> 13702 */ 13703 public void onCancelPendingInputEvents() { 13704 removePerformClickCallback(); 13705 cancelLongPress(); 13706 mPrivateFlags3 |= PFLAG3_CALLED_SUPER; 13707 } 13708 13709 /** 13710 * Store this view hierarchy's frozen state into the given container. 13711 * 13712 * @param container The SparseArray in which to save the view's state. 13713 * 13714 * @see #restoreHierarchyState(android.util.SparseArray) 13715 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13716 * @see #onSaveInstanceState() 13717 */ 13718 public void saveHierarchyState(SparseArray<Parcelable> container) { 13719 dispatchSaveInstanceState(container); 13720 } 13721 13722 /** 13723 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 13724 * this view and its children. May be overridden to modify how freezing happens to a 13725 * view's children; for example, some views may want to not store state for their children. 13726 * 13727 * @param container The SparseArray in which to save the view's state. 13728 * 13729 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13730 * @see #saveHierarchyState(android.util.SparseArray) 13731 * @see #onSaveInstanceState() 13732 */ 13733 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 13734 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 13735 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 13736 Parcelable state = onSaveInstanceState(); 13737 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 13738 throw new IllegalStateException( 13739 "Derived class did not call super.onSaveInstanceState()"); 13740 } 13741 if (state != null) { 13742 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 13743 // + ": " + state); 13744 container.put(mID, state); 13745 } 13746 } 13747 } 13748 13749 /** 13750 * Hook allowing a view to generate a representation of its internal state 13751 * that can later be used to create a new instance with that same state. 13752 * This state should only contain information that is not persistent or can 13753 * not be reconstructed later. For example, you will never store your 13754 * current position on screen because that will be computed again when a 13755 * new instance of the view is placed in its view hierarchy. 13756 * <p> 13757 * Some examples of things you may store here: the current cursor position 13758 * in a text view (but usually not the text itself since that is stored in a 13759 * content provider or other persistent storage), the currently selected 13760 * item in a list view. 13761 * 13762 * @return Returns a Parcelable object containing the view's current dynamic 13763 * state, or null if there is nothing interesting to save. The 13764 * default implementation returns null. 13765 * @see #onRestoreInstanceState(android.os.Parcelable) 13766 * @see #saveHierarchyState(android.util.SparseArray) 13767 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13768 * @see #setSaveEnabled(boolean) 13769 */ 13770 protected Parcelable onSaveInstanceState() { 13771 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 13772 return BaseSavedState.EMPTY_STATE; 13773 } 13774 13775 /** 13776 * Restore this view hierarchy's frozen state from the given container. 13777 * 13778 * @param container The SparseArray which holds previously frozen states. 13779 * 13780 * @see #saveHierarchyState(android.util.SparseArray) 13781 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13782 * @see #onRestoreInstanceState(android.os.Parcelable) 13783 */ 13784 public void restoreHierarchyState(SparseArray<Parcelable> container) { 13785 dispatchRestoreInstanceState(container); 13786 } 13787 13788 /** 13789 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 13790 * state for this view and its children. May be overridden to modify how restoring 13791 * happens to a view's children; for example, some views may want to not store state 13792 * for their children. 13793 * 13794 * @param container The SparseArray which holds previously saved state. 13795 * 13796 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13797 * @see #restoreHierarchyState(android.util.SparseArray) 13798 * @see #onRestoreInstanceState(android.os.Parcelable) 13799 */ 13800 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 13801 if (mID != NO_ID) { 13802 Parcelable state = container.get(mID); 13803 if (state != null) { 13804 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 13805 // + ": " + state); 13806 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 13807 onRestoreInstanceState(state); 13808 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 13809 throw new IllegalStateException( 13810 "Derived class did not call super.onRestoreInstanceState()"); 13811 } 13812 } 13813 } 13814 } 13815 13816 /** 13817 * Hook allowing a view to re-apply a representation of its internal state that had previously 13818 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 13819 * null state. 13820 * 13821 * @param state The frozen state that had previously been returned by 13822 * {@link #onSaveInstanceState}. 13823 * 13824 * @see #onSaveInstanceState() 13825 * @see #restoreHierarchyState(android.util.SparseArray) 13826 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13827 */ 13828 protected void onRestoreInstanceState(Parcelable state) { 13829 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 13830 if (state != BaseSavedState.EMPTY_STATE && state != null) { 13831 throw new IllegalArgumentException("Wrong state class, expecting View State but " 13832 + "received " + state.getClass().toString() + " instead. This usually happens " 13833 + "when two views of different type have the same id in the same hierarchy. " 13834 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 13835 + "other views do not use the same id."); 13836 } 13837 } 13838 13839 /** 13840 * <p>Return the time at which the drawing of the view hierarchy started.</p> 13841 * 13842 * @return the drawing start time in milliseconds 13843 */ 13844 public long getDrawingTime() { 13845 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 13846 } 13847 13848 /** 13849 * <p>Enables or disables the duplication of the parent's state into this view. When 13850 * duplication is enabled, this view gets its drawable state from its parent rather 13851 * than from its own internal properties.</p> 13852 * 13853 * <p>Note: in the current implementation, setting this property to true after the 13854 * view was added to a ViewGroup might have no effect at all. This property should 13855 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 13856 * 13857 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 13858 * property is enabled, an exception will be thrown.</p> 13859 * 13860 * <p>Note: if the child view uses and updates additionnal states which are unknown to the 13861 * parent, these states should not be affected by this method.</p> 13862 * 13863 * @param enabled True to enable duplication of the parent's drawable state, false 13864 * to disable it. 13865 * 13866 * @see #getDrawableState() 13867 * @see #isDuplicateParentStateEnabled() 13868 */ 13869 public void setDuplicateParentStateEnabled(boolean enabled) { 13870 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 13871 } 13872 13873 /** 13874 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 13875 * 13876 * @return True if this view's drawable state is duplicated from the parent, 13877 * false otherwise 13878 * 13879 * @see #getDrawableState() 13880 * @see #setDuplicateParentStateEnabled(boolean) 13881 */ 13882 public boolean isDuplicateParentStateEnabled() { 13883 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 13884 } 13885 13886 /** 13887 * <p>Specifies the type of layer backing this view. The layer can be 13888 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13889 * {@link #LAYER_TYPE_HARDWARE}.</p> 13890 * 13891 * <p>A layer is associated with an optional {@link android.graphics.Paint} 13892 * instance that controls how the layer is composed on screen. The following 13893 * properties of the paint are taken into account when composing the layer:</p> 13894 * <ul> 13895 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 13896 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 13897 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 13898 * </ul> 13899 * 13900 * <p>If this view has an alpha value set to < 1.0 by calling 13901 * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded 13902 * by this view's alpha value.</p> 13903 * 13904 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE}, 13905 * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE} 13906 * for more information on when and how to use layers.</p> 13907 * 13908 * @param layerType The type of layer to use with this view, must be one of 13909 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13910 * {@link #LAYER_TYPE_HARDWARE} 13911 * @param paint The paint used to compose the layer. This argument is optional 13912 * and can be null. It is ignored when the layer type is 13913 * {@link #LAYER_TYPE_NONE} 13914 * 13915 * @see #getLayerType() 13916 * @see #LAYER_TYPE_NONE 13917 * @see #LAYER_TYPE_SOFTWARE 13918 * @see #LAYER_TYPE_HARDWARE 13919 * @see #setAlpha(float) 13920 * 13921 * @attr ref android.R.styleable#View_layerType 13922 */ 13923 public void setLayerType(int layerType, Paint paint) { 13924 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 13925 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 13926 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 13927 } 13928 13929 boolean typeChanged = mRenderNode.setLayerType(layerType); 13930 13931 if (!typeChanged) { 13932 setLayerPaint(paint); 13933 return; 13934 } 13935 13936 // Destroy any previous software drawing cache if needed 13937 if (mLayerType == LAYER_TYPE_SOFTWARE) { 13938 destroyDrawingCache(); 13939 } 13940 13941 mLayerType = layerType; 13942 final boolean layerDisabled = (mLayerType == LAYER_TYPE_NONE); 13943 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 13944 mRenderNode.setLayerPaint(mLayerPaint); 13945 13946 // draw() behaves differently if we are on a layer, so we need to 13947 // invalidate() here 13948 invalidateParentCaches(); 13949 invalidate(true); 13950 } 13951 13952 /** 13953 * Updates the {@link Paint} object used with the current layer (used only if the current 13954 * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint 13955 * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time 13956 * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to 13957 * ensure that the view gets redrawn immediately. 13958 * 13959 * <p>A layer is associated with an optional {@link android.graphics.Paint} 13960 * instance that controls how the layer is composed on screen. The following 13961 * properties of the paint are taken into account when composing the layer:</p> 13962 * <ul> 13963 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 13964 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 13965 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 13966 * </ul> 13967 * 13968 * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the 13969 * alpha value of the layer's paint is superceded by this view's alpha value.</p> 13970 * 13971 * @param paint The paint used to compose the layer. This argument is optional 13972 * and can be null. It is ignored when the layer type is 13973 * {@link #LAYER_TYPE_NONE} 13974 * 13975 * @see #setLayerType(int, android.graphics.Paint) 13976 */ 13977 public void setLayerPaint(Paint paint) { 13978 int layerType = getLayerType(); 13979 if (layerType != LAYER_TYPE_NONE) { 13980 mLayerPaint = paint == null ? new Paint() : paint; 13981 if (layerType == LAYER_TYPE_HARDWARE) { 13982 if (mRenderNode.setLayerPaint(mLayerPaint)) { 13983 invalidateViewProperty(false, false); 13984 } 13985 } else { 13986 invalidate(); 13987 } 13988 } 13989 } 13990 13991 /** 13992 * Indicates whether this view has a static layer. A view with layer type 13993 * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are 13994 * dynamic. 13995 */ 13996 boolean hasStaticLayer() { 13997 return true; 13998 } 13999 14000 /** 14001 * Indicates what type of layer is currently associated with this view. By default 14002 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 14003 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 14004 * for more information on the different types of layers. 14005 * 14006 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 14007 * {@link #LAYER_TYPE_HARDWARE} 14008 * 14009 * @see #setLayerType(int, android.graphics.Paint) 14010 * @see #buildLayer() 14011 * @see #LAYER_TYPE_NONE 14012 * @see #LAYER_TYPE_SOFTWARE 14013 * @see #LAYER_TYPE_HARDWARE 14014 */ 14015 public int getLayerType() { 14016 return mLayerType; 14017 } 14018 14019 /** 14020 * Forces this view's layer to be created and this view to be rendered 14021 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 14022 * invoking this method will have no effect. 14023 * 14024 * This method can for instance be used to render a view into its layer before 14025 * starting an animation. If this view is complex, rendering into the layer 14026 * before starting the animation will avoid skipping frames. 14027 * 14028 * @throws IllegalStateException If this view is not attached to a window 14029 * 14030 * @see #setLayerType(int, android.graphics.Paint) 14031 */ 14032 public void buildLayer() { 14033 if (mLayerType == LAYER_TYPE_NONE) return; 14034 14035 final AttachInfo attachInfo = mAttachInfo; 14036 if (attachInfo == null) { 14037 throw new IllegalStateException("This view must be attached to a window first"); 14038 } 14039 14040 if (getWidth() == 0 || getHeight() == 0) { 14041 return; 14042 } 14043 14044 switch (mLayerType) { 14045 case LAYER_TYPE_HARDWARE: 14046 updateDisplayListIfDirty(); 14047 if (attachInfo.mHardwareRenderer != null && mRenderNode.isValid()) { 14048 attachInfo.mHardwareRenderer.buildLayer(mRenderNode); 14049 } 14050 break; 14051 case LAYER_TYPE_SOFTWARE: 14052 buildDrawingCache(true); 14053 break; 14054 } 14055 } 14056 14057 /** 14058 * If this View draws with a HardwareLayer, returns it. 14059 * Otherwise returns null 14060 * 14061 * TODO: Only TextureView uses this, can we eliminate it? 14062 */ 14063 HardwareLayer getHardwareLayer() { 14064 return null; 14065 } 14066 14067 /** 14068 * Destroys all hardware rendering resources. This method is invoked 14069 * when the system needs to reclaim resources. Upon execution of this 14070 * method, you should free any OpenGL resources created by the view. 14071 * 14072 * Note: you <strong>must</strong> call 14073 * <code>super.destroyHardwareResources()</code> when overriding 14074 * this method. 14075 * 14076 * @hide 14077 */ 14078 protected void destroyHardwareResources() { 14079 // Although the Layer will be destroyed by RenderNode, we want to release 14080 // the staging display list, which is also a signal to RenderNode that it's 14081 // safe to free its copy of the display list as it knows that we will 14082 // push an updated DisplayList if we try to draw again 14083 resetDisplayList(); 14084 } 14085 14086 /** 14087 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 14088 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 14089 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 14090 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 14091 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 14092 * null.</p> 14093 * 14094 * <p>Enabling the drawing cache is similar to 14095 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 14096 * acceleration is turned off. When hardware acceleration is turned on, enabling the 14097 * drawing cache has no effect on rendering because the system uses a different mechanism 14098 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 14099 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 14100 * for information on how to enable software and hardware layers.</p> 14101 * 14102 * <p>This API can be used to manually generate 14103 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 14104 * {@link #getDrawingCache()}.</p> 14105 * 14106 * @param enabled true to enable the drawing cache, false otherwise 14107 * 14108 * @see #isDrawingCacheEnabled() 14109 * @see #getDrawingCache() 14110 * @see #buildDrawingCache() 14111 * @see #setLayerType(int, android.graphics.Paint) 14112 */ 14113 public void setDrawingCacheEnabled(boolean enabled) { 14114 mCachingFailed = false; 14115 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 14116 } 14117 14118 /** 14119 * <p>Indicates whether the drawing cache is enabled for this view.</p> 14120 * 14121 * @return true if the drawing cache is enabled 14122 * 14123 * @see #setDrawingCacheEnabled(boolean) 14124 * @see #getDrawingCache() 14125 */ 14126 @ViewDebug.ExportedProperty(category = "drawing") 14127 public boolean isDrawingCacheEnabled() { 14128 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 14129 } 14130 14131 /** 14132 * Debugging utility which recursively outputs the dirty state of a view and its 14133 * descendants. 14134 * 14135 * @hide 14136 */ 14137 @SuppressWarnings({"UnusedDeclaration"}) 14138 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 14139 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) + 14140 ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" + 14141 (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) + 14142 ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")"); 14143 if (clear) { 14144 mPrivateFlags &= clearMask; 14145 } 14146 if (this instanceof ViewGroup) { 14147 ViewGroup parent = (ViewGroup) this; 14148 final int count = parent.getChildCount(); 14149 for (int i = 0; i < count; i++) { 14150 final View child = parent.getChildAt(i); 14151 child.outputDirtyFlags(indent + " ", clear, clearMask); 14152 } 14153 } 14154 } 14155 14156 /** 14157 * This method is used by ViewGroup to cause its children to restore or recreate their 14158 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 14159 * to recreate its own display list, which would happen if it went through the normal 14160 * draw/dispatchDraw mechanisms. 14161 * 14162 * @hide 14163 */ 14164 protected void dispatchGetDisplayList() {} 14165 14166 /** 14167 * A view that is not attached or hardware accelerated cannot create a display list. 14168 * This method checks these conditions and returns the appropriate result. 14169 * 14170 * @return true if view has the ability to create a display list, false otherwise. 14171 * 14172 * @hide 14173 */ 14174 public boolean canHaveDisplayList() { 14175 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 14176 } 14177 14178 private void updateDisplayListIfDirty() { 14179 final RenderNode renderNode = mRenderNode; 14180 if (!canHaveDisplayList()) { 14181 // can't populate RenderNode, don't try 14182 return; 14183 } 14184 14185 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 14186 || !renderNode.isValid() 14187 || (mRecreateDisplayList)) { 14188 // Don't need to recreate the display list, just need to tell our 14189 // children to restore/recreate theirs 14190 if (renderNode.isValid() 14191 && !mRecreateDisplayList) { 14192 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 14193 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14194 dispatchGetDisplayList(); 14195 14196 return; // no work needed 14197 } 14198 14199 // If we got here, we're recreating it. Mark it as such to ensure that 14200 // we copy in child display lists into ours in drawChild() 14201 mRecreateDisplayList = true; 14202 14203 int width = mRight - mLeft; 14204 int height = mBottom - mTop; 14205 int layerType = getLayerType(); 14206 14207 final HardwareCanvas canvas = renderNode.start(width, height); 14208 canvas.setHighContrastText(mAttachInfo.mHighContrastText); 14209 14210 try { 14211 final HardwareLayer layer = getHardwareLayer(); 14212 if (layer != null && layer.isValid()) { 14213 canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint); 14214 } else if (layerType == LAYER_TYPE_SOFTWARE) { 14215 buildDrawingCache(true); 14216 Bitmap cache = getDrawingCache(true); 14217 if (cache != null) { 14218 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 14219 } 14220 } else { 14221 computeScroll(); 14222 14223 canvas.translate(-mScrollX, -mScrollY); 14224 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 14225 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14226 14227 // Fast path for layouts with no backgrounds 14228 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14229 dispatchDraw(canvas); 14230 if (mOverlay != null && !mOverlay.isEmpty()) { 14231 mOverlay.getOverlayView().draw(canvas); 14232 } 14233 } else { 14234 draw(canvas); 14235 } 14236 } 14237 } finally { 14238 renderNode.end(canvas); 14239 setDisplayListProperties(renderNode); 14240 } 14241 } else { 14242 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 14243 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14244 } 14245 } 14246 14247 /** 14248 * Returns a RenderNode with View draw content recorded, which can be 14249 * used to draw this view again without executing its draw method. 14250 * 14251 * @return A RenderNode ready to replay, or null if caching is not enabled. 14252 * 14253 * @hide 14254 */ 14255 public RenderNode getDisplayList() { 14256 updateDisplayListIfDirty(); 14257 return mRenderNode; 14258 } 14259 14260 private void resetDisplayList() { 14261 if (mRenderNode.isValid()) { 14262 mRenderNode.destroyDisplayListData(); 14263 } 14264 14265 if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) { 14266 mBackgroundRenderNode.destroyDisplayListData(); 14267 } 14268 } 14269 14270 /** 14271 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 14272 * 14273 * @return A non-scaled bitmap representing this view or null if cache is disabled. 14274 * 14275 * @see #getDrawingCache(boolean) 14276 */ 14277 public Bitmap getDrawingCache() { 14278 return getDrawingCache(false); 14279 } 14280 14281 /** 14282 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 14283 * is null when caching is disabled. If caching is enabled and the cache is not ready, 14284 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 14285 * draw from the cache when the cache is enabled. To benefit from the cache, you must 14286 * request the drawing cache by calling this method and draw it on screen if the 14287 * returned bitmap is not null.</p> 14288 * 14289 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 14290 * this method will create a bitmap of the same size as this view. Because this bitmap 14291 * will be drawn scaled by the parent ViewGroup, the result on screen might show 14292 * scaling artifacts. To avoid such artifacts, you should call this method by setting 14293 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 14294 * size than the view. This implies that your application must be able to handle this 14295 * size.</p> 14296 * 14297 * @param autoScale Indicates whether the generated bitmap should be scaled based on 14298 * the current density of the screen when the application is in compatibility 14299 * mode. 14300 * 14301 * @return A bitmap representing this view or null if cache is disabled. 14302 * 14303 * @see #setDrawingCacheEnabled(boolean) 14304 * @see #isDrawingCacheEnabled() 14305 * @see #buildDrawingCache(boolean) 14306 * @see #destroyDrawingCache() 14307 */ 14308 public Bitmap getDrawingCache(boolean autoScale) { 14309 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 14310 return null; 14311 } 14312 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 14313 buildDrawingCache(autoScale); 14314 } 14315 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 14316 } 14317 14318 /** 14319 * <p>Frees the resources used by the drawing cache. If you call 14320 * {@link #buildDrawingCache()} manually without calling 14321 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 14322 * should cleanup the cache with this method afterwards.</p> 14323 * 14324 * @see #setDrawingCacheEnabled(boolean) 14325 * @see #buildDrawingCache() 14326 * @see #getDrawingCache() 14327 */ 14328 public void destroyDrawingCache() { 14329 if (mDrawingCache != null) { 14330 mDrawingCache.recycle(); 14331 mDrawingCache = null; 14332 } 14333 if (mUnscaledDrawingCache != null) { 14334 mUnscaledDrawingCache.recycle(); 14335 mUnscaledDrawingCache = null; 14336 } 14337 } 14338 14339 /** 14340 * Setting a solid background color for the drawing cache's bitmaps will improve 14341 * performance and memory usage. Note, though that this should only be used if this 14342 * view will always be drawn on top of a solid color. 14343 * 14344 * @param color The background color to use for the drawing cache's bitmap 14345 * 14346 * @see #setDrawingCacheEnabled(boolean) 14347 * @see #buildDrawingCache() 14348 * @see #getDrawingCache() 14349 */ 14350 public void setDrawingCacheBackgroundColor(int color) { 14351 if (color != mDrawingCacheBackgroundColor) { 14352 mDrawingCacheBackgroundColor = color; 14353 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 14354 } 14355 } 14356 14357 /** 14358 * @see #setDrawingCacheBackgroundColor(int) 14359 * 14360 * @return The background color to used for the drawing cache's bitmap 14361 */ 14362 public int getDrawingCacheBackgroundColor() { 14363 return mDrawingCacheBackgroundColor; 14364 } 14365 14366 /** 14367 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 14368 * 14369 * @see #buildDrawingCache(boolean) 14370 */ 14371 public void buildDrawingCache() { 14372 buildDrawingCache(false); 14373 } 14374 14375 /** 14376 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 14377 * 14378 * <p>If you call {@link #buildDrawingCache()} manually without calling 14379 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 14380 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 14381 * 14382 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 14383 * this method will create a bitmap of the same size as this view. Because this bitmap 14384 * will be drawn scaled by the parent ViewGroup, the result on screen might show 14385 * scaling artifacts. To avoid such artifacts, you should call this method by setting 14386 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 14387 * size than the view. This implies that your application must be able to handle this 14388 * size.</p> 14389 * 14390 * <p>You should avoid calling this method when hardware acceleration is enabled. If 14391 * you do not need the drawing cache bitmap, calling this method will increase memory 14392 * usage and cause the view to be rendered in software once, thus negatively impacting 14393 * performance.</p> 14394 * 14395 * @see #getDrawingCache() 14396 * @see #destroyDrawingCache() 14397 */ 14398 public void buildDrawingCache(boolean autoScale) { 14399 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ? 14400 mDrawingCache == null : mUnscaledDrawingCache == null)) { 14401 if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) { 14402 Trace.traceBegin(Trace.TRACE_TAG_VIEW, 14403 "buildDrawingCache/SW Layer for " + getClass().getSimpleName()); 14404 } 14405 try { 14406 buildDrawingCacheImpl(autoScale); 14407 } finally { 14408 Trace.traceEnd(Trace.TRACE_TAG_VIEW); 14409 } 14410 } 14411 } 14412 14413 /** 14414 * private, internal implementation of buildDrawingCache, used to enable tracing 14415 */ 14416 private void buildDrawingCacheImpl(boolean autoScale) { 14417 mCachingFailed = false; 14418 14419 int width = mRight - mLeft; 14420 int height = mBottom - mTop; 14421 14422 final AttachInfo attachInfo = mAttachInfo; 14423 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 14424 14425 if (autoScale && scalingRequired) { 14426 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 14427 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 14428 } 14429 14430 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 14431 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 14432 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 14433 14434 final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4); 14435 final long drawingCacheSize = 14436 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize(); 14437 if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) { 14438 if (width > 0 && height > 0) { 14439 Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs " 14440 + projectedBitmapSize + " bytes, only " 14441 + drawingCacheSize + " available"); 14442 } 14443 destroyDrawingCache(); 14444 mCachingFailed = true; 14445 return; 14446 } 14447 14448 boolean clear = true; 14449 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 14450 14451 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 14452 Bitmap.Config quality; 14453 if (!opaque) { 14454 // Never pick ARGB_4444 because it looks awful 14455 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 14456 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 14457 case DRAWING_CACHE_QUALITY_AUTO: 14458 case DRAWING_CACHE_QUALITY_LOW: 14459 case DRAWING_CACHE_QUALITY_HIGH: 14460 default: 14461 quality = Bitmap.Config.ARGB_8888; 14462 break; 14463 } 14464 } else { 14465 // Optimization for translucent windows 14466 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 14467 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 14468 } 14469 14470 // Try to cleanup memory 14471 if (bitmap != null) bitmap.recycle(); 14472 14473 try { 14474 bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 14475 width, height, quality); 14476 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 14477 if (autoScale) { 14478 mDrawingCache = bitmap; 14479 } else { 14480 mUnscaledDrawingCache = bitmap; 14481 } 14482 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 14483 } catch (OutOfMemoryError e) { 14484 // If there is not enough memory to create the bitmap cache, just 14485 // ignore the issue as bitmap caches are not required to draw the 14486 // view hierarchy 14487 if (autoScale) { 14488 mDrawingCache = null; 14489 } else { 14490 mUnscaledDrawingCache = null; 14491 } 14492 mCachingFailed = true; 14493 return; 14494 } 14495 14496 clear = drawingCacheBackgroundColor != 0; 14497 } 14498 14499 Canvas canvas; 14500 if (attachInfo != null) { 14501 canvas = attachInfo.mCanvas; 14502 if (canvas == null) { 14503 canvas = new Canvas(); 14504 } 14505 canvas.setBitmap(bitmap); 14506 // Temporarily clobber the cached Canvas in case one of our children 14507 // is also using a drawing cache. Without this, the children would 14508 // steal the canvas by attaching their own bitmap to it and bad, bad 14509 // thing would happen (invisible views, corrupted drawings, etc.) 14510 attachInfo.mCanvas = null; 14511 } else { 14512 // This case should hopefully never or seldom happen 14513 canvas = new Canvas(bitmap); 14514 } 14515 14516 if (clear) { 14517 bitmap.eraseColor(drawingCacheBackgroundColor); 14518 } 14519 14520 computeScroll(); 14521 final int restoreCount = canvas.save(); 14522 14523 if (autoScale && scalingRequired) { 14524 final float scale = attachInfo.mApplicationScale; 14525 canvas.scale(scale, scale); 14526 } 14527 14528 canvas.translate(-mScrollX, -mScrollY); 14529 14530 mPrivateFlags |= PFLAG_DRAWN; 14531 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 14532 mLayerType != LAYER_TYPE_NONE) { 14533 mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID; 14534 } 14535 14536 // Fast path for layouts with no backgrounds 14537 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14538 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14539 dispatchDraw(canvas); 14540 if (mOverlay != null && !mOverlay.isEmpty()) { 14541 mOverlay.getOverlayView().draw(canvas); 14542 } 14543 } else { 14544 draw(canvas); 14545 } 14546 14547 canvas.restoreToCount(restoreCount); 14548 canvas.setBitmap(null); 14549 14550 if (attachInfo != null) { 14551 // Restore the cached Canvas for our siblings 14552 attachInfo.mCanvas = canvas; 14553 } 14554 } 14555 14556 /** 14557 * Create a snapshot of the view into a bitmap. We should probably make 14558 * some form of this public, but should think about the API. 14559 */ 14560 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 14561 int width = mRight - mLeft; 14562 int height = mBottom - mTop; 14563 14564 final AttachInfo attachInfo = mAttachInfo; 14565 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 14566 width = (int) ((width * scale) + 0.5f); 14567 height = (int) ((height * scale) + 0.5f); 14568 14569 Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 14570 width > 0 ? width : 1, height > 0 ? height : 1, quality); 14571 if (bitmap == null) { 14572 throw new OutOfMemoryError(); 14573 } 14574 14575 Resources resources = getResources(); 14576 if (resources != null) { 14577 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 14578 } 14579 14580 Canvas canvas; 14581 if (attachInfo != null) { 14582 canvas = attachInfo.mCanvas; 14583 if (canvas == null) { 14584 canvas = new Canvas(); 14585 } 14586 canvas.setBitmap(bitmap); 14587 // Temporarily clobber the cached Canvas in case one of our children 14588 // is also using a drawing cache. Without this, the children would 14589 // steal the canvas by attaching their own bitmap to it and bad, bad 14590 // things would happen (invisible views, corrupted drawings, etc.) 14591 attachInfo.mCanvas = null; 14592 } else { 14593 // This case should hopefully never or seldom happen 14594 canvas = new Canvas(bitmap); 14595 } 14596 14597 if ((backgroundColor & 0xff000000) != 0) { 14598 bitmap.eraseColor(backgroundColor); 14599 } 14600 14601 computeScroll(); 14602 final int restoreCount = canvas.save(); 14603 canvas.scale(scale, scale); 14604 canvas.translate(-mScrollX, -mScrollY); 14605 14606 // Temporarily remove the dirty mask 14607 int flags = mPrivateFlags; 14608 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14609 14610 // Fast path for layouts with no backgrounds 14611 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14612 dispatchDraw(canvas); 14613 if (mOverlay != null && !mOverlay.isEmpty()) { 14614 mOverlay.getOverlayView().draw(canvas); 14615 } 14616 } else { 14617 draw(canvas); 14618 } 14619 14620 mPrivateFlags = flags; 14621 14622 canvas.restoreToCount(restoreCount); 14623 canvas.setBitmap(null); 14624 14625 if (attachInfo != null) { 14626 // Restore the cached Canvas for our siblings 14627 attachInfo.mCanvas = canvas; 14628 } 14629 14630 return bitmap; 14631 } 14632 14633 /** 14634 * Indicates whether this View is currently in edit mode. A View is usually 14635 * in edit mode when displayed within a developer tool. For instance, if 14636 * this View is being drawn by a visual user interface builder, this method 14637 * should return true. 14638 * 14639 * Subclasses should check the return value of this method to provide 14640 * different behaviors if their normal behavior might interfere with the 14641 * host environment. For instance: the class spawns a thread in its 14642 * constructor, the drawing code relies on device-specific features, etc. 14643 * 14644 * This method is usually checked in the drawing code of custom widgets. 14645 * 14646 * @return True if this View is in edit mode, false otherwise. 14647 */ 14648 public boolean isInEditMode() { 14649 return false; 14650 } 14651 14652 /** 14653 * If the View draws content inside its padding and enables fading edges, 14654 * it needs to support padding offsets. Padding offsets are added to the 14655 * fading edges to extend the length of the fade so that it covers pixels 14656 * drawn inside the padding. 14657 * 14658 * Subclasses of this class should override this method if they need 14659 * to draw content inside the padding. 14660 * 14661 * @return True if padding offset must be applied, false otherwise. 14662 * 14663 * @see #getLeftPaddingOffset() 14664 * @see #getRightPaddingOffset() 14665 * @see #getTopPaddingOffset() 14666 * @see #getBottomPaddingOffset() 14667 * 14668 * @since CURRENT 14669 */ 14670 protected boolean isPaddingOffsetRequired() { 14671 return false; 14672 } 14673 14674 /** 14675 * Amount by which to extend the left fading region. Called only when 14676 * {@link #isPaddingOffsetRequired()} returns true. 14677 * 14678 * @return The left padding offset in pixels. 14679 * 14680 * @see #isPaddingOffsetRequired() 14681 * 14682 * @since CURRENT 14683 */ 14684 protected int getLeftPaddingOffset() { 14685 return 0; 14686 } 14687 14688 /** 14689 * Amount by which to extend the right fading region. Called only when 14690 * {@link #isPaddingOffsetRequired()} returns true. 14691 * 14692 * @return The right padding offset in pixels. 14693 * 14694 * @see #isPaddingOffsetRequired() 14695 * 14696 * @since CURRENT 14697 */ 14698 protected int getRightPaddingOffset() { 14699 return 0; 14700 } 14701 14702 /** 14703 * Amount by which to extend the top fading region. Called only when 14704 * {@link #isPaddingOffsetRequired()} returns true. 14705 * 14706 * @return The top padding offset in pixels. 14707 * 14708 * @see #isPaddingOffsetRequired() 14709 * 14710 * @since CURRENT 14711 */ 14712 protected int getTopPaddingOffset() { 14713 return 0; 14714 } 14715 14716 /** 14717 * Amount by which to extend the bottom fading region. Called only when 14718 * {@link #isPaddingOffsetRequired()} returns true. 14719 * 14720 * @return The bottom padding offset in pixels. 14721 * 14722 * @see #isPaddingOffsetRequired() 14723 * 14724 * @since CURRENT 14725 */ 14726 protected int getBottomPaddingOffset() { 14727 return 0; 14728 } 14729 14730 /** 14731 * @hide 14732 * @param offsetRequired 14733 */ 14734 protected int getFadeTop(boolean offsetRequired) { 14735 int top = mPaddingTop; 14736 if (offsetRequired) top += getTopPaddingOffset(); 14737 return top; 14738 } 14739 14740 /** 14741 * @hide 14742 * @param offsetRequired 14743 */ 14744 protected int getFadeHeight(boolean offsetRequired) { 14745 int padding = mPaddingTop; 14746 if (offsetRequired) padding += getTopPaddingOffset(); 14747 return mBottom - mTop - mPaddingBottom - padding; 14748 } 14749 14750 /** 14751 * <p>Indicates whether this view is attached to a hardware accelerated 14752 * window or not.</p> 14753 * 14754 * <p>Even if this method returns true, it does not mean that every call 14755 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 14756 * accelerated {@link android.graphics.Canvas}. For instance, if this view 14757 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 14758 * window is hardware accelerated, 14759 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 14760 * return false, and this method will return true.</p> 14761 * 14762 * @return True if the view is attached to a window and the window is 14763 * hardware accelerated; false in any other case. 14764 */ 14765 @ViewDebug.ExportedProperty(category = "drawing") 14766 public boolean isHardwareAccelerated() { 14767 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 14768 } 14769 14770 /** 14771 * Sets a rectangular area on this view to which the view will be clipped 14772 * when it is drawn. Setting the value to null will remove the clip bounds 14773 * and the view will draw normally, using its full bounds. 14774 * 14775 * @param clipBounds The rectangular area, in the local coordinates of 14776 * this view, to which future drawing operations will be clipped. 14777 */ 14778 public void setClipBounds(Rect clipBounds) { 14779 if (clipBounds != null) { 14780 if (clipBounds.equals(mClipBounds)) { 14781 return; 14782 } 14783 if (mClipBounds == null) { 14784 invalidate(); 14785 mClipBounds = new Rect(clipBounds); 14786 } else { 14787 invalidate(Math.min(mClipBounds.left, clipBounds.left), 14788 Math.min(mClipBounds.top, clipBounds.top), 14789 Math.max(mClipBounds.right, clipBounds.right), 14790 Math.max(mClipBounds.bottom, clipBounds.bottom)); 14791 mClipBounds.set(clipBounds); 14792 } 14793 } else { 14794 if (mClipBounds != null) { 14795 invalidate(); 14796 mClipBounds = null; 14797 } 14798 } 14799 mRenderNode.setClipBounds(mClipBounds); 14800 } 14801 14802 /** 14803 * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}. 14804 * 14805 * @return A copy of the current clip bounds if clip bounds are set, 14806 * otherwise null. 14807 */ 14808 public Rect getClipBounds() { 14809 return (mClipBounds != null) ? new Rect(mClipBounds) : null; 14810 } 14811 14812 /** 14813 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 14814 * case of an active Animation being run on the view. 14815 */ 14816 private boolean drawAnimation(ViewGroup parent, long drawingTime, 14817 Animation a, boolean scalingRequired) { 14818 Transformation invalidationTransform; 14819 final int flags = parent.mGroupFlags; 14820 final boolean initialized = a.isInitialized(); 14821 if (!initialized) { 14822 a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight()); 14823 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 14824 if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler); 14825 onAnimationStart(); 14826 } 14827 14828 final Transformation t = parent.getChildTransformation(); 14829 boolean more = a.getTransformation(drawingTime, t, 1f); 14830 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 14831 if (parent.mInvalidationTransformation == null) { 14832 parent.mInvalidationTransformation = new Transformation(); 14833 } 14834 invalidationTransform = parent.mInvalidationTransformation; 14835 a.getTransformation(drawingTime, invalidationTransform, 1f); 14836 } else { 14837 invalidationTransform = t; 14838 } 14839 14840 if (more) { 14841 if (!a.willChangeBounds()) { 14842 if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) == 14843 ViewGroup.FLAG_OPTIMIZE_INVALIDATE) { 14844 parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED; 14845 } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) { 14846 // The child need to draw an animation, potentially offscreen, so 14847 // make sure we do not cancel invalidate requests 14848 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 14849 parent.invalidate(mLeft, mTop, mRight, mBottom); 14850 } 14851 } else { 14852 if (parent.mInvalidateRegion == null) { 14853 parent.mInvalidateRegion = new RectF(); 14854 } 14855 final RectF region = parent.mInvalidateRegion; 14856 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 14857 invalidationTransform); 14858 14859 // The child need to draw an animation, potentially offscreen, so 14860 // make sure we do not cancel invalidate requests 14861 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 14862 14863 final int left = mLeft + (int) region.left; 14864 final int top = mTop + (int) region.top; 14865 parent.invalidate(left, top, left + (int) (region.width() + .5f), 14866 top + (int) (region.height() + .5f)); 14867 } 14868 } 14869 return more; 14870 } 14871 14872 /** 14873 * This method is called by getDisplayList() when a display list is recorded for a View. 14874 * It pushes any properties to the RenderNode that aren't managed by the RenderNode. 14875 */ 14876 void setDisplayListProperties(RenderNode renderNode) { 14877 if (renderNode != null) { 14878 if ((mPrivateFlags3 & PFLAG3_OUTLINE_INVALID) != 0) { 14879 rebuildOutline(); 14880 mPrivateFlags3 &= ~PFLAG3_OUTLINE_INVALID; 14881 } 14882 renderNode.setHasOverlappingRendering(hasOverlappingRendering()); 14883 if (mParent instanceof ViewGroup) { 14884 renderNode.setClipToBounds( 14885 (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0); 14886 } 14887 float alpha = 1; 14888 if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags & 14889 ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 14890 ViewGroup parentVG = (ViewGroup) mParent; 14891 final Transformation t = parentVG.getChildTransformation(); 14892 if (parentVG.getChildStaticTransformation(this, t)) { 14893 final int transformType = t.getTransformationType(); 14894 if (transformType != Transformation.TYPE_IDENTITY) { 14895 if ((transformType & Transformation.TYPE_ALPHA) != 0) { 14896 alpha = t.getAlpha(); 14897 } 14898 if ((transformType & Transformation.TYPE_MATRIX) != 0) { 14899 renderNode.setStaticMatrix(t.getMatrix()); 14900 } 14901 } 14902 } 14903 } 14904 if (mTransformationInfo != null) { 14905 alpha *= getFinalAlpha(); 14906 if (alpha < 1) { 14907 final int multipliedAlpha = (int) (255 * alpha); 14908 if (onSetAlpha(multipliedAlpha)) { 14909 alpha = 1; 14910 } 14911 } 14912 renderNode.setAlpha(alpha); 14913 } else if (alpha < 1) { 14914 renderNode.setAlpha(alpha); 14915 } 14916 } 14917 } 14918 14919 /** 14920 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 14921 * This draw() method is an implementation detail and is not intended to be overridden or 14922 * to be called from anywhere else other than ViewGroup.drawChild(). 14923 */ 14924 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 14925 boolean usingRenderNodeProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 14926 boolean more = false; 14927 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 14928 final int flags = parent.mGroupFlags; 14929 14930 if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) { 14931 parent.getChildTransformation().clear(); 14932 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14933 } 14934 14935 Transformation transformToApply = null; 14936 boolean concatMatrix = false; 14937 14938 boolean scalingRequired = false; 14939 boolean caching; 14940 int layerType = getLayerType(); 14941 14942 final boolean hardwareAccelerated = canvas.isHardwareAccelerated(); 14943 if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 || 14944 (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) { 14945 caching = true; 14946 // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList 14947 if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired; 14948 } else { 14949 caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated; 14950 } 14951 14952 final Animation a = getAnimation(); 14953 if (a != null) { 14954 more = drawAnimation(parent, drawingTime, a, scalingRequired); 14955 concatMatrix = a.willChangeTransformationMatrix(); 14956 if (concatMatrix) { 14957 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 14958 } 14959 transformToApply = parent.getChildTransformation(); 14960 } else { 14961 if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) { 14962 // No longer animating: clear out old animation matrix 14963 mRenderNode.setAnimationMatrix(null); 14964 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 14965 } 14966 if (!usingRenderNodeProperties && 14967 (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 14968 final Transformation t = parent.getChildTransformation(); 14969 final boolean hasTransform = parent.getChildStaticTransformation(this, t); 14970 if (hasTransform) { 14971 final int transformType = t.getTransformationType(); 14972 transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null; 14973 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 14974 } 14975 } 14976 } 14977 14978 concatMatrix |= !childHasIdentityMatrix; 14979 14980 // Sets the flag as early as possible to allow draw() implementations 14981 // to call invalidate() successfully when doing animations 14982 mPrivateFlags |= PFLAG_DRAWN; 14983 14984 if (!concatMatrix && 14985 (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS | 14986 ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN && 14987 canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 14988 (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) { 14989 mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED; 14990 return more; 14991 } 14992 mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED; 14993 14994 if (hardwareAccelerated) { 14995 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 14996 // retain the flag's value temporarily in the mRecreateDisplayList flag 14997 mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED; 14998 mPrivateFlags &= ~PFLAG_INVALIDATED; 14999 } 15000 15001 RenderNode renderNode = null; 15002 Bitmap cache = null; 15003 boolean hasDisplayList = false; 15004 if (caching) { 15005 if (!hardwareAccelerated) { 15006 if (layerType != LAYER_TYPE_NONE) { 15007 layerType = LAYER_TYPE_SOFTWARE; 15008 buildDrawingCache(true); 15009 } 15010 cache = getDrawingCache(true); 15011 } else { 15012 switch (layerType) { 15013 case LAYER_TYPE_SOFTWARE: 15014 if (usingRenderNodeProperties) { 15015 hasDisplayList = canHaveDisplayList(); 15016 } else { 15017 buildDrawingCache(true); 15018 cache = getDrawingCache(true); 15019 } 15020 break; 15021 case LAYER_TYPE_HARDWARE: 15022 if (usingRenderNodeProperties) { 15023 hasDisplayList = canHaveDisplayList(); 15024 } 15025 break; 15026 case LAYER_TYPE_NONE: 15027 // Delay getting the display list until animation-driven alpha values are 15028 // set up and possibly passed on to the view 15029 hasDisplayList = canHaveDisplayList(); 15030 break; 15031 } 15032 } 15033 } 15034 usingRenderNodeProperties &= hasDisplayList; 15035 if (usingRenderNodeProperties) { 15036 renderNode = getDisplayList(); 15037 if (!renderNode.isValid()) { 15038 // Uncommon, but possible. If a view is removed from the hierarchy during the call 15039 // to getDisplayList(), the display list will be marked invalid and we should not 15040 // try to use it again. 15041 renderNode = null; 15042 hasDisplayList = false; 15043 usingRenderNodeProperties = false; 15044 } 15045 } 15046 15047 int sx = 0; 15048 int sy = 0; 15049 if (!hasDisplayList) { 15050 computeScroll(); 15051 sx = mScrollX; 15052 sy = mScrollY; 15053 } 15054 15055 final boolean hasNoCache = cache == null || hasDisplayList; 15056 final boolean offsetForScroll = cache == null && !hasDisplayList && 15057 layerType != LAYER_TYPE_HARDWARE; 15058 15059 int restoreTo = -1; 15060 if (!usingRenderNodeProperties || transformToApply != null) { 15061 restoreTo = canvas.save(); 15062 } 15063 if (offsetForScroll) { 15064 canvas.translate(mLeft - sx, mTop - sy); 15065 } else { 15066 if (!usingRenderNodeProperties) { 15067 canvas.translate(mLeft, mTop); 15068 } 15069 if (scalingRequired) { 15070 if (usingRenderNodeProperties) { 15071 // TODO: Might not need this if we put everything inside the DL 15072 restoreTo = canvas.save(); 15073 } 15074 // mAttachInfo cannot be null, otherwise scalingRequired == false 15075 final float scale = 1.0f / mAttachInfo.mApplicationScale; 15076 canvas.scale(scale, scale); 15077 } 15078 } 15079 15080 float alpha = usingRenderNodeProperties ? 1 : (getAlpha() * getTransitionAlpha()); 15081 if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() || 15082 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 15083 if (transformToApply != null || !childHasIdentityMatrix) { 15084 int transX = 0; 15085 int transY = 0; 15086 15087 if (offsetForScroll) { 15088 transX = -sx; 15089 transY = -sy; 15090 } 15091 15092 if (transformToApply != null) { 15093 if (concatMatrix) { 15094 if (usingRenderNodeProperties) { 15095 renderNode.setAnimationMatrix(transformToApply.getMatrix()); 15096 } else { 15097 // Undo the scroll translation, apply the transformation matrix, 15098 // then redo the scroll translate to get the correct result. 15099 canvas.translate(-transX, -transY); 15100 canvas.concat(transformToApply.getMatrix()); 15101 canvas.translate(transX, transY); 15102 } 15103 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 15104 } 15105 15106 float transformAlpha = transformToApply.getAlpha(); 15107 if (transformAlpha < 1) { 15108 alpha *= transformAlpha; 15109 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 15110 } 15111 } 15112 15113 if (!childHasIdentityMatrix && !usingRenderNodeProperties) { 15114 canvas.translate(-transX, -transY); 15115 canvas.concat(getMatrix()); 15116 canvas.translate(transX, transY); 15117 } 15118 } 15119 15120 // Deal with alpha if it is or used to be <1 15121 if (alpha < 1 || 15122 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 15123 if (alpha < 1) { 15124 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA; 15125 } else { 15126 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA; 15127 } 15128 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 15129 if (hasNoCache) { 15130 final int multipliedAlpha = (int) (255 * alpha); 15131 if (!onSetAlpha(multipliedAlpha)) { 15132 int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 15133 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 || 15134 layerType != LAYER_TYPE_NONE) { 15135 layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG; 15136 } 15137 if (usingRenderNodeProperties) { 15138 renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha()); 15139 } else if (layerType == LAYER_TYPE_NONE) { 15140 final int scrollX = hasDisplayList ? 0 : sx; 15141 final int scrollY = hasDisplayList ? 0 : sy; 15142 canvas.saveLayerAlpha(scrollX, scrollY, 15143 scrollX + (mRight - mLeft), scrollY + (mBottom - mTop), 15144 multipliedAlpha, layerFlags); 15145 } 15146 } else { 15147 // Alpha is handled by the child directly, clobber the layer's alpha 15148 mPrivateFlags |= PFLAG_ALPHA_SET; 15149 } 15150 } 15151 } 15152 } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 15153 onSetAlpha(255); 15154 mPrivateFlags &= ~PFLAG_ALPHA_SET; 15155 } 15156 15157 if (!usingRenderNodeProperties) { 15158 // apply clips directly, since RenderNode won't do it for this draw 15159 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN 15160 && cache == null) { 15161 if (offsetForScroll) { 15162 canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop)); 15163 } else { 15164 if (!scalingRequired || cache == null) { 15165 canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop); 15166 } else { 15167 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 15168 } 15169 } 15170 } 15171 15172 if (mClipBounds != null) { 15173 // clip bounds ignore scroll 15174 canvas.clipRect(mClipBounds); 15175 } 15176 } 15177 15178 15179 15180 if (!usingRenderNodeProperties && hasDisplayList) { 15181 renderNode = getDisplayList(); 15182 if (!renderNode.isValid()) { 15183 // Uncommon, but possible. If a view is removed from the hierarchy during the call 15184 // to getDisplayList(), the display list will be marked invalid and we should not 15185 // try to use it again. 15186 renderNode = null; 15187 hasDisplayList = false; 15188 } 15189 } 15190 15191 if (hasNoCache) { 15192 boolean layerRendered = false; 15193 if (layerType == LAYER_TYPE_HARDWARE && !usingRenderNodeProperties) { 15194 final HardwareLayer layer = getHardwareLayer(); 15195 if (layer != null && layer.isValid()) { 15196 int restoreAlpha = mLayerPaint.getAlpha(); 15197 mLayerPaint.setAlpha((int) (alpha * 255)); 15198 ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint); 15199 mLayerPaint.setAlpha(restoreAlpha); 15200 layerRendered = true; 15201 } else { 15202 final int scrollX = hasDisplayList ? 0 : sx; 15203 final int scrollY = hasDisplayList ? 0 : sy; 15204 canvas.saveLayer(scrollX, scrollY, 15205 scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint, 15206 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG); 15207 } 15208 } 15209 15210 if (!layerRendered) { 15211 if (!hasDisplayList) { 15212 // Fast path for layouts with no backgrounds 15213 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 15214 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 15215 dispatchDraw(canvas); 15216 } else { 15217 draw(canvas); 15218 } 15219 } else { 15220 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 15221 ((HardwareCanvas) canvas).drawRenderNode(renderNode, null, flags); 15222 } 15223 } 15224 } else if (cache != null) { 15225 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 15226 Paint cachePaint; 15227 int restoreAlpha = 0; 15228 15229 if (layerType == LAYER_TYPE_NONE) { 15230 cachePaint = parent.mCachePaint; 15231 if (cachePaint == null) { 15232 cachePaint = new Paint(); 15233 cachePaint.setDither(false); 15234 parent.mCachePaint = cachePaint; 15235 } 15236 } else { 15237 cachePaint = mLayerPaint; 15238 restoreAlpha = mLayerPaint.getAlpha(); 15239 } 15240 cachePaint.setAlpha((int) (alpha * 255)); 15241 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 15242 cachePaint.setAlpha(restoreAlpha); 15243 } 15244 15245 if (restoreTo >= 0) { 15246 canvas.restoreToCount(restoreTo); 15247 } 15248 15249 if (a != null && !more) { 15250 if (!hardwareAccelerated && !a.getFillAfter()) { 15251 onSetAlpha(255); 15252 } 15253 parent.finishAnimatingView(this, a); 15254 } 15255 15256 if (more && hardwareAccelerated) { 15257 if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 15258 // alpha animations should cause the child to recreate its display list 15259 invalidate(true); 15260 } 15261 } 15262 15263 mRecreateDisplayList = false; 15264 15265 return more; 15266 } 15267 15268 /** 15269 * Manually render this view (and all of its children) to the given Canvas. 15270 * The view must have already done a full layout before this function is 15271 * called. When implementing a view, implement 15272 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 15273 * If you do need to override this method, call the superclass version. 15274 * 15275 * @param canvas The Canvas to which the View is rendered. 15276 */ 15277 public void draw(Canvas canvas) { 15278 final int privateFlags = mPrivateFlags; 15279 final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE && 15280 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 15281 mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN; 15282 15283 /* 15284 * Draw traversal performs several drawing steps which must be executed 15285 * in the appropriate order: 15286 * 15287 * 1. Draw the background 15288 * 2. If necessary, save the canvas' layers to prepare for fading 15289 * 3. Draw view's content 15290 * 4. Draw children 15291 * 5. If necessary, draw the fading edges and restore layers 15292 * 6. Draw decorations (scrollbars for instance) 15293 */ 15294 15295 // Step 1, draw the background, if needed 15296 int saveCount; 15297 15298 if (!dirtyOpaque) { 15299 drawBackground(canvas); 15300 } 15301 15302 // skip step 2 & 5 if possible (common case) 15303 final int viewFlags = mViewFlags; 15304 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 15305 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 15306 if (!verticalEdges && !horizontalEdges) { 15307 // Step 3, draw the content 15308 if (!dirtyOpaque) onDraw(canvas); 15309 15310 // Step 4, draw the children 15311 dispatchDraw(canvas); 15312 15313 // Step 6, draw decorations (scrollbars) 15314 onDrawScrollBars(canvas); 15315 15316 if (mOverlay != null && !mOverlay.isEmpty()) { 15317 mOverlay.getOverlayView().dispatchDraw(canvas); 15318 } 15319 15320 // we're done... 15321 return; 15322 } 15323 15324 /* 15325 * Here we do the full fledged routine... 15326 * (this is an uncommon case where speed matters less, 15327 * this is why we repeat some of the tests that have been 15328 * done above) 15329 */ 15330 15331 boolean drawTop = false; 15332 boolean drawBottom = false; 15333 boolean drawLeft = false; 15334 boolean drawRight = false; 15335 15336 float topFadeStrength = 0.0f; 15337 float bottomFadeStrength = 0.0f; 15338 float leftFadeStrength = 0.0f; 15339 float rightFadeStrength = 0.0f; 15340 15341 // Step 2, save the canvas' layers 15342 int paddingLeft = mPaddingLeft; 15343 15344 final boolean offsetRequired = isPaddingOffsetRequired(); 15345 if (offsetRequired) { 15346 paddingLeft += getLeftPaddingOffset(); 15347 } 15348 15349 int left = mScrollX + paddingLeft; 15350 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 15351 int top = mScrollY + getFadeTop(offsetRequired); 15352 int bottom = top + getFadeHeight(offsetRequired); 15353 15354 if (offsetRequired) { 15355 right += getRightPaddingOffset(); 15356 bottom += getBottomPaddingOffset(); 15357 } 15358 15359 final ScrollabilityCache scrollabilityCache = mScrollCache; 15360 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 15361 int length = (int) fadeHeight; 15362 15363 // clip the fade length if top and bottom fades overlap 15364 // overlapping fades produce odd-looking artifacts 15365 if (verticalEdges && (top + length > bottom - length)) { 15366 length = (bottom - top) / 2; 15367 } 15368 15369 // also clip horizontal fades if necessary 15370 if (horizontalEdges && (left + length > right - length)) { 15371 length = (right - left) / 2; 15372 } 15373 15374 if (verticalEdges) { 15375 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 15376 drawTop = topFadeStrength * fadeHeight > 1.0f; 15377 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 15378 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 15379 } 15380 15381 if (horizontalEdges) { 15382 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 15383 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 15384 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 15385 drawRight = rightFadeStrength * fadeHeight > 1.0f; 15386 } 15387 15388 saveCount = canvas.getSaveCount(); 15389 15390 int solidColor = getSolidColor(); 15391 if (solidColor == 0) { 15392 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 15393 15394 if (drawTop) { 15395 canvas.saveLayer(left, top, right, top + length, null, flags); 15396 } 15397 15398 if (drawBottom) { 15399 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 15400 } 15401 15402 if (drawLeft) { 15403 canvas.saveLayer(left, top, left + length, bottom, null, flags); 15404 } 15405 15406 if (drawRight) { 15407 canvas.saveLayer(right - length, top, right, bottom, null, flags); 15408 } 15409 } else { 15410 scrollabilityCache.setFadeColor(solidColor); 15411 } 15412 15413 // Step 3, draw the content 15414 if (!dirtyOpaque) onDraw(canvas); 15415 15416 // Step 4, draw the children 15417 dispatchDraw(canvas); 15418 15419 // Step 5, draw the fade effect and restore layers 15420 final Paint p = scrollabilityCache.paint; 15421 final Matrix matrix = scrollabilityCache.matrix; 15422 final Shader fade = scrollabilityCache.shader; 15423 15424 if (drawTop) { 15425 matrix.setScale(1, fadeHeight * topFadeStrength); 15426 matrix.postTranslate(left, top); 15427 fade.setLocalMatrix(matrix); 15428 p.setShader(fade); 15429 canvas.drawRect(left, top, right, top + length, p); 15430 } 15431 15432 if (drawBottom) { 15433 matrix.setScale(1, fadeHeight * bottomFadeStrength); 15434 matrix.postRotate(180); 15435 matrix.postTranslate(left, bottom); 15436 fade.setLocalMatrix(matrix); 15437 p.setShader(fade); 15438 canvas.drawRect(left, bottom - length, right, bottom, p); 15439 } 15440 15441 if (drawLeft) { 15442 matrix.setScale(1, fadeHeight * leftFadeStrength); 15443 matrix.postRotate(-90); 15444 matrix.postTranslate(left, top); 15445 fade.setLocalMatrix(matrix); 15446 p.setShader(fade); 15447 canvas.drawRect(left, top, left + length, bottom, p); 15448 } 15449 15450 if (drawRight) { 15451 matrix.setScale(1, fadeHeight * rightFadeStrength); 15452 matrix.postRotate(90); 15453 matrix.postTranslate(right, top); 15454 fade.setLocalMatrix(matrix); 15455 p.setShader(fade); 15456 canvas.drawRect(right - length, top, right, bottom, p); 15457 } 15458 15459 canvas.restoreToCount(saveCount); 15460 15461 // Step 6, draw decorations (scrollbars) 15462 onDrawScrollBars(canvas); 15463 15464 if (mOverlay != null && !mOverlay.isEmpty()) { 15465 mOverlay.getOverlayView().dispatchDraw(canvas); 15466 } 15467 } 15468 15469 /** 15470 * Draws the background onto the specified canvas. 15471 * 15472 * @param canvas Canvas on which to draw the background 15473 */ 15474 private void drawBackground(Canvas canvas) { 15475 final Drawable background = mBackground; 15476 if (background == null) { 15477 return; 15478 } 15479 15480 if (mBackgroundSizeChanged) { 15481 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 15482 mBackgroundSizeChanged = false; 15483 mPrivateFlags3 |= PFLAG3_OUTLINE_INVALID; 15484 } 15485 15486 // Attempt to use a display list if requested. 15487 if (canvas.isHardwareAccelerated() && mAttachInfo != null 15488 && mAttachInfo.mHardwareRenderer != null) { 15489 mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode); 15490 15491 final RenderNode renderNode = mBackgroundRenderNode; 15492 if (renderNode != null && renderNode.isValid()) { 15493 setBackgroundRenderNodeProperties(renderNode); 15494 ((HardwareCanvas) canvas).drawRenderNode(renderNode); 15495 return; 15496 } 15497 } 15498 15499 final int scrollX = mScrollX; 15500 final int scrollY = mScrollY; 15501 if ((scrollX | scrollY) == 0) { 15502 background.draw(canvas); 15503 } else { 15504 canvas.translate(scrollX, scrollY); 15505 background.draw(canvas); 15506 canvas.translate(-scrollX, -scrollY); 15507 } 15508 } 15509 15510 private void setBackgroundRenderNodeProperties(RenderNode renderNode) { 15511 renderNode.setTranslationX(mScrollX); 15512 renderNode.setTranslationY(mScrollY); 15513 } 15514 15515 /** 15516 * Creates a new display list or updates the existing display list for the 15517 * specified Drawable. 15518 * 15519 * @param drawable Drawable for which to create a display list 15520 * @param renderNode Existing RenderNode, or {@code null} 15521 * @return A valid display list for the specified drawable 15522 */ 15523 private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) { 15524 if (renderNode == null) { 15525 renderNode = RenderNode.create(drawable.getClass().getName(), this); 15526 } 15527 15528 final Rect bounds = drawable.getBounds(); 15529 final int width = bounds.width(); 15530 final int height = bounds.height(); 15531 final HardwareCanvas canvas = renderNode.start(width, height); 15532 try { 15533 drawable.draw(canvas); 15534 } finally { 15535 renderNode.end(canvas); 15536 } 15537 15538 // Set up drawable properties that are view-independent. 15539 renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom); 15540 renderNode.setProjectBackwards(drawable.isProjected()); 15541 renderNode.setProjectionReceiver(true); 15542 renderNode.setClipToBounds(false); 15543 return renderNode; 15544 } 15545 15546 /** 15547 * Returns the overlay for this view, creating it if it does not yet exist. 15548 * Adding drawables to the overlay will cause them to be displayed whenever 15549 * the view itself is redrawn. Objects in the overlay should be actively 15550 * managed: remove them when they should not be displayed anymore. The 15551 * overlay will always have the same size as its host view. 15552 * 15553 * <p>Note: Overlays do not currently work correctly with {@link 15554 * SurfaceView} or {@link TextureView}; contents in overlays for these 15555 * types of views may not display correctly.</p> 15556 * 15557 * @return The ViewOverlay object for this view. 15558 * @see ViewOverlay 15559 */ 15560 public ViewOverlay getOverlay() { 15561 if (mOverlay == null) { 15562 mOverlay = new ViewOverlay(mContext, this); 15563 } 15564 return mOverlay; 15565 } 15566 15567 /** 15568 * Override this if your view is known to always be drawn on top of a solid color background, 15569 * and needs to draw fading edges. Returning a non-zero color enables the view system to 15570 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 15571 * should be set to 0xFF. 15572 * 15573 * @see #setVerticalFadingEdgeEnabled(boolean) 15574 * @see #setHorizontalFadingEdgeEnabled(boolean) 15575 * 15576 * @return The known solid color background for this view, or 0 if the color may vary 15577 */ 15578 @ViewDebug.ExportedProperty(category = "drawing") 15579 public int getSolidColor() { 15580 return 0; 15581 } 15582 15583 /** 15584 * Build a human readable string representation of the specified view flags. 15585 * 15586 * @param flags the view flags to convert to a string 15587 * @return a String representing the supplied flags 15588 */ 15589 private static String printFlags(int flags) { 15590 String output = ""; 15591 int numFlags = 0; 15592 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 15593 output += "TAKES_FOCUS"; 15594 numFlags++; 15595 } 15596 15597 switch (flags & VISIBILITY_MASK) { 15598 case INVISIBLE: 15599 if (numFlags > 0) { 15600 output += " "; 15601 } 15602 output += "INVISIBLE"; 15603 // USELESS HERE numFlags++; 15604 break; 15605 case GONE: 15606 if (numFlags > 0) { 15607 output += " "; 15608 } 15609 output += "GONE"; 15610 // USELESS HERE numFlags++; 15611 break; 15612 default: 15613 break; 15614 } 15615 return output; 15616 } 15617 15618 /** 15619 * Build a human readable string representation of the specified private 15620 * view flags. 15621 * 15622 * @param privateFlags the private view flags to convert to a string 15623 * @return a String representing the supplied flags 15624 */ 15625 private static String printPrivateFlags(int privateFlags) { 15626 String output = ""; 15627 int numFlags = 0; 15628 15629 if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) { 15630 output += "WANTS_FOCUS"; 15631 numFlags++; 15632 } 15633 15634 if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) { 15635 if (numFlags > 0) { 15636 output += " "; 15637 } 15638 output += "FOCUSED"; 15639 numFlags++; 15640 } 15641 15642 if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) { 15643 if (numFlags > 0) { 15644 output += " "; 15645 } 15646 output += "SELECTED"; 15647 numFlags++; 15648 } 15649 15650 if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) { 15651 if (numFlags > 0) { 15652 output += " "; 15653 } 15654 output += "IS_ROOT_NAMESPACE"; 15655 numFlags++; 15656 } 15657 15658 if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) { 15659 if (numFlags > 0) { 15660 output += " "; 15661 } 15662 output += "HAS_BOUNDS"; 15663 numFlags++; 15664 } 15665 15666 if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) { 15667 if (numFlags > 0) { 15668 output += " "; 15669 } 15670 output += "DRAWN"; 15671 // USELESS HERE numFlags++; 15672 } 15673 return output; 15674 } 15675 15676 /** 15677 * <p>Indicates whether or not this view's layout will be requested during 15678 * the next hierarchy layout pass.</p> 15679 * 15680 * @return true if the layout will be forced during next layout pass 15681 */ 15682 public boolean isLayoutRequested() { 15683 return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 15684 } 15685 15686 /** 15687 * Return true if o is a ViewGroup that is laying out using optical bounds. 15688 * @hide 15689 */ 15690 public static boolean isLayoutModeOptical(Object o) { 15691 return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical(); 15692 } 15693 15694 private boolean setOpticalFrame(int left, int top, int right, int bottom) { 15695 Insets parentInsets = mParent instanceof View ? 15696 ((View) mParent).getOpticalInsets() : Insets.NONE; 15697 Insets childInsets = getOpticalInsets(); 15698 return setFrame( 15699 left + parentInsets.left - childInsets.left, 15700 top + parentInsets.top - childInsets.top, 15701 right + parentInsets.left + childInsets.right, 15702 bottom + parentInsets.top + childInsets.bottom); 15703 } 15704 15705 /** 15706 * Assign a size and position to a view and all of its 15707 * descendants 15708 * 15709 * <p>This is the second phase of the layout mechanism. 15710 * (The first is measuring). In this phase, each parent calls 15711 * layout on all of its children to position them. 15712 * This is typically done using the child measurements 15713 * that were stored in the measure pass().</p> 15714 * 15715 * <p>Derived classes should not override this method. 15716 * Derived classes with children should override 15717 * onLayout. In that method, they should 15718 * call layout on each of their children.</p> 15719 * 15720 * @param l Left position, relative to parent 15721 * @param t Top position, relative to parent 15722 * @param r Right position, relative to parent 15723 * @param b Bottom position, relative to parent 15724 */ 15725 @SuppressWarnings({"unchecked"}) 15726 public void layout(int l, int t, int r, int b) { 15727 if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) { 15728 onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec); 15729 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 15730 } 15731 15732 int oldL = mLeft; 15733 int oldT = mTop; 15734 int oldB = mBottom; 15735 int oldR = mRight; 15736 15737 boolean changed = isLayoutModeOptical(mParent) ? 15738 setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b); 15739 15740 if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) { 15741 onLayout(changed, l, t, r, b); 15742 mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED; 15743 15744 ListenerInfo li = mListenerInfo; 15745 if (li != null && li.mOnLayoutChangeListeners != null) { 15746 ArrayList<OnLayoutChangeListener> listenersCopy = 15747 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 15748 int numListeners = listenersCopy.size(); 15749 for (int i = 0; i < numListeners; ++i) { 15750 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 15751 } 15752 } 15753 } 15754 15755 mPrivateFlags &= ~PFLAG_FORCE_LAYOUT; 15756 mPrivateFlags3 |= PFLAG3_IS_LAID_OUT; 15757 } 15758 15759 /** 15760 * Called from layout when this view should 15761 * assign a size and position to each of its children. 15762 * 15763 * Derived classes with children should override 15764 * this method and call layout on each of 15765 * their children. 15766 * @param changed This is a new size or position for this view 15767 * @param left Left position, relative to parent 15768 * @param top Top position, relative to parent 15769 * @param right Right position, relative to parent 15770 * @param bottom Bottom position, relative to parent 15771 */ 15772 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 15773 } 15774 15775 /** 15776 * Assign a size and position to this view. 15777 * 15778 * This is called from layout. 15779 * 15780 * @param left Left position, relative to parent 15781 * @param top Top position, relative to parent 15782 * @param right Right position, relative to parent 15783 * @param bottom Bottom position, relative to parent 15784 * @return true if the new size and position are different than the 15785 * previous ones 15786 * {@hide} 15787 */ 15788 protected boolean setFrame(int left, int top, int right, int bottom) { 15789 boolean changed = false; 15790 15791 if (DBG) { 15792 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 15793 + right + "," + bottom + ")"); 15794 } 15795 15796 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 15797 changed = true; 15798 15799 // Remember our drawn bit 15800 int drawn = mPrivateFlags & PFLAG_DRAWN; 15801 15802 int oldWidth = mRight - mLeft; 15803 int oldHeight = mBottom - mTop; 15804 int newWidth = right - left; 15805 int newHeight = bottom - top; 15806 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 15807 15808 // Invalidate our old position 15809 invalidate(sizeChanged); 15810 15811 mLeft = left; 15812 mTop = top; 15813 mRight = right; 15814 mBottom = bottom; 15815 mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 15816 15817 mPrivateFlags |= PFLAG_HAS_BOUNDS; 15818 15819 15820 if (sizeChanged) { 15821 sizeChange(newWidth, newHeight, oldWidth, oldHeight); 15822 } 15823 15824 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) { 15825 // If we are visible, force the DRAWN bit to on so that 15826 // this invalidate will go through (at least to our parent). 15827 // This is because someone may have invalidated this view 15828 // before this call to setFrame came in, thereby clearing 15829 // the DRAWN bit. 15830 mPrivateFlags |= PFLAG_DRAWN; 15831 invalidate(sizeChanged); 15832 // parent display list may need to be recreated based on a change in the bounds 15833 // of any child 15834 invalidateParentCaches(); 15835 } 15836 15837 // Reset drawn bit to original value (invalidate turns it off) 15838 mPrivateFlags |= drawn; 15839 15840 mBackgroundSizeChanged = true; 15841 15842 notifySubtreeAccessibilityStateChangedIfNeeded(); 15843 } 15844 return changed; 15845 } 15846 15847 /** 15848 * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}. 15849 * @hide 15850 */ 15851 public void setLeftTopRightBottom(int left, int top, int right, int bottom) { 15852 setFrame(left, top, right, bottom); 15853 } 15854 15855 private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) { 15856 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 15857 if (mOverlay != null) { 15858 mOverlay.getOverlayView().setRight(newWidth); 15859 mOverlay.getOverlayView().setBottom(newHeight); 15860 } 15861 mPrivateFlags3 |= PFLAG3_OUTLINE_INVALID; 15862 } 15863 15864 /** 15865 * Finalize inflating a view from XML. This is called as the last phase 15866 * of inflation, after all child views have been added. 15867 * 15868 * <p>Even if the subclass overrides onFinishInflate, they should always be 15869 * sure to call the super method, so that we get called. 15870 */ 15871 protected void onFinishInflate() { 15872 } 15873 15874 /** 15875 * Returns the resources associated with this view. 15876 * 15877 * @return Resources object. 15878 */ 15879 public Resources getResources() { 15880 return mResources; 15881 } 15882 15883 /** 15884 * Invalidates the specified Drawable. 15885 * 15886 * @param drawable the drawable to invalidate 15887 */ 15888 @Override 15889 public void invalidateDrawable(@NonNull Drawable drawable) { 15890 if (verifyDrawable(drawable)) { 15891 final Rect dirty = drawable.getDirtyBounds(); 15892 final int scrollX = mScrollX; 15893 final int scrollY = mScrollY; 15894 15895 invalidate(dirty.left + scrollX, dirty.top + scrollY, 15896 dirty.right + scrollX, dirty.bottom + scrollY); 15897 15898 mPrivateFlags3 |= PFLAG3_OUTLINE_INVALID; 15899 } 15900 } 15901 15902 /** 15903 * Schedules an action on a drawable to occur at a specified time. 15904 * 15905 * @param who the recipient of the action 15906 * @param what the action to run on the drawable 15907 * @param when the time at which the action must occur. Uses the 15908 * {@link SystemClock#uptimeMillis} timebase. 15909 */ 15910 @Override 15911 public void scheduleDrawable(Drawable who, Runnable what, long when) { 15912 if (verifyDrawable(who) && what != null) { 15913 final long delay = when - SystemClock.uptimeMillis(); 15914 if (mAttachInfo != null) { 15915 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 15916 Choreographer.CALLBACK_ANIMATION, what, who, 15917 Choreographer.subtractFrameDelay(delay)); 15918 } else { 15919 ViewRootImpl.getRunQueue().postDelayed(what, delay); 15920 } 15921 } 15922 } 15923 15924 /** 15925 * Cancels a scheduled action on a drawable. 15926 * 15927 * @param who the recipient of the action 15928 * @param what the action to cancel 15929 */ 15930 @Override 15931 public void unscheduleDrawable(Drawable who, Runnable what) { 15932 if (verifyDrawable(who) && what != null) { 15933 if (mAttachInfo != null) { 15934 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 15935 Choreographer.CALLBACK_ANIMATION, what, who); 15936 } 15937 ViewRootImpl.getRunQueue().removeCallbacks(what); 15938 } 15939 } 15940 15941 /** 15942 * Unschedule any events associated with the given Drawable. This can be 15943 * used when selecting a new Drawable into a view, so that the previous 15944 * one is completely unscheduled. 15945 * 15946 * @param who The Drawable to unschedule. 15947 * 15948 * @see #drawableStateChanged 15949 */ 15950 public void unscheduleDrawable(Drawable who) { 15951 if (mAttachInfo != null && who != null) { 15952 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 15953 Choreographer.CALLBACK_ANIMATION, null, who); 15954 } 15955 } 15956 15957 /** 15958 * Resolve the Drawables depending on the layout direction. This is implicitly supposing 15959 * that the View directionality can and will be resolved before its Drawables. 15960 * 15961 * Will call {@link View#onResolveDrawables} when resolution is done. 15962 * 15963 * @hide 15964 */ 15965 protected void resolveDrawables() { 15966 // Drawables resolution may need to happen before resolving the layout direction (which is 15967 // done only during the measure() call). 15968 // If the layout direction is not resolved yet, we cannot resolve the Drawables except in 15969 // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT. 15970 // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or 15971 // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout 15972 // direction to be resolved as its resolved value will be the same as its raw value. 15973 if (!isLayoutDirectionResolved() && 15974 getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) { 15975 return; 15976 } 15977 15978 final int layoutDirection = isLayoutDirectionResolved() ? 15979 getLayoutDirection() : getRawLayoutDirection(); 15980 15981 if (mBackground != null) { 15982 mBackground.setLayoutDirection(layoutDirection); 15983 } 15984 mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED; 15985 onResolveDrawables(layoutDirection); 15986 } 15987 15988 /** 15989 * Called when layout direction has been resolved. 15990 * 15991 * The default implementation does nothing. 15992 * 15993 * @param layoutDirection The resolved layout direction. 15994 * 15995 * @see #LAYOUT_DIRECTION_LTR 15996 * @see #LAYOUT_DIRECTION_RTL 15997 * 15998 * @hide 15999 */ 16000 public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) { 16001 } 16002 16003 /** 16004 * @hide 16005 */ 16006 protected void resetResolvedDrawables() { 16007 mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED; 16008 } 16009 16010 private boolean isDrawablesResolved() { 16011 return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED; 16012 } 16013 16014 /** 16015 * If your view subclass is displaying its own Drawable objects, it should 16016 * override this function and return true for any Drawable it is 16017 * displaying. This allows animations for those drawables to be 16018 * scheduled. 16019 * 16020 * <p>Be sure to call through to the super class when overriding this 16021 * function. 16022 * 16023 * @param who The Drawable to verify. Return true if it is one you are 16024 * displaying, else return the result of calling through to the 16025 * super class. 16026 * 16027 * @return boolean If true than the Drawable is being displayed in the 16028 * view; else false and it is not allowed to animate. 16029 * 16030 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 16031 * @see #drawableStateChanged() 16032 */ 16033 protected boolean verifyDrawable(Drawable who) { 16034 return who == mBackground; 16035 } 16036 16037 /** 16038 * This function is called whenever the state of the view changes in such 16039 * a way that it impacts the state of drawables being shown. 16040 * <p> 16041 * If the View has a StateListAnimator, it will also be called to run necessary state 16042 * change animations. 16043 * <p> 16044 * Be sure to call through to the superclass when overriding this function. 16045 * 16046 * @see Drawable#setState(int[]) 16047 */ 16048 protected void drawableStateChanged() { 16049 final Drawable d = mBackground; 16050 if (d != null && d.isStateful()) { 16051 d.setState(getDrawableState()); 16052 } 16053 16054 if (mStateListAnimator != null) { 16055 mStateListAnimator.setState(getDrawableState()); 16056 } 16057 } 16058 16059 /** 16060 * This function is called whenever the view hotspot changes and needs to 16061 * be propagated to drawables managed by the view. 16062 * <p> 16063 * Be sure to call through to the superclass when overriding this function. 16064 * 16065 * @param x hotspot x coordinate 16066 * @param y hotspot y coordinate 16067 */ 16068 public void drawableHotspotChanged(float x, float y) { 16069 if (mBackground != null) { 16070 mBackground.setHotspot(x, y); 16071 } 16072 } 16073 16074 /** 16075 * Call this to force a view to update its drawable state. This will cause 16076 * drawableStateChanged to be called on this view. Views that are interested 16077 * in the new state should call getDrawableState. 16078 * 16079 * @see #drawableStateChanged 16080 * @see #getDrawableState 16081 */ 16082 public void refreshDrawableState() { 16083 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 16084 drawableStateChanged(); 16085 16086 ViewParent parent = mParent; 16087 if (parent != null) { 16088 parent.childDrawableStateChanged(this); 16089 } 16090 } 16091 16092 /** 16093 * Return an array of resource IDs of the drawable states representing the 16094 * current state of the view. 16095 * 16096 * @return The current drawable state 16097 * 16098 * @see Drawable#setState(int[]) 16099 * @see #drawableStateChanged() 16100 * @see #onCreateDrawableState(int) 16101 */ 16102 public final int[] getDrawableState() { 16103 if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) { 16104 return mDrawableState; 16105 } else { 16106 mDrawableState = onCreateDrawableState(0); 16107 mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY; 16108 return mDrawableState; 16109 } 16110 } 16111 16112 /** 16113 * Generate the new {@link android.graphics.drawable.Drawable} state for 16114 * this view. This is called by the view 16115 * system when the cached Drawable state is determined to be invalid. To 16116 * retrieve the current state, you should use {@link #getDrawableState}. 16117 * 16118 * @param extraSpace if non-zero, this is the number of extra entries you 16119 * would like in the returned array in which you can place your own 16120 * states. 16121 * 16122 * @return Returns an array holding the current {@link Drawable} state of 16123 * the view. 16124 * 16125 * @see #mergeDrawableStates(int[], int[]) 16126 */ 16127 protected int[] onCreateDrawableState(int extraSpace) { 16128 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 16129 mParent instanceof View) { 16130 return ((View) mParent).onCreateDrawableState(extraSpace); 16131 } 16132 16133 int[] drawableState; 16134 16135 int privateFlags = mPrivateFlags; 16136 16137 int viewStateIndex = 0; 16138 if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED; 16139 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED; 16140 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED; 16141 if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED; 16142 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED; 16143 if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED; 16144 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 16145 HardwareRenderer.isAvailable()) { 16146 // This is set if HW acceleration is requested, even if the current 16147 // process doesn't allow it. This is just to allow app preview 16148 // windows to better match their app. 16149 viewStateIndex |= VIEW_STATE_ACCELERATED; 16150 } 16151 if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED; 16152 16153 final int privateFlags2 = mPrivateFlags2; 16154 if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT; 16155 if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED; 16156 16157 drawableState = VIEW_STATE_SETS[viewStateIndex]; 16158 16159 //noinspection ConstantIfStatement 16160 if (false) { 16161 Log.i("View", "drawableStateIndex=" + viewStateIndex); 16162 Log.i("View", toString() 16163 + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0) 16164 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 16165 + " fo=" + hasFocus() 16166 + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0) 16167 + " wf=" + hasWindowFocus() 16168 + ": " + Arrays.toString(drawableState)); 16169 } 16170 16171 if (extraSpace == 0) { 16172 return drawableState; 16173 } 16174 16175 final int[] fullState; 16176 if (drawableState != null) { 16177 fullState = new int[drawableState.length + extraSpace]; 16178 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 16179 } else { 16180 fullState = new int[extraSpace]; 16181 } 16182 16183 return fullState; 16184 } 16185 16186 /** 16187 * Merge your own state values in <var>additionalState</var> into the base 16188 * state values <var>baseState</var> that were returned by 16189 * {@link #onCreateDrawableState(int)}. 16190 * 16191 * @param baseState The base state values returned by 16192 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 16193 * own additional state values. 16194 * 16195 * @param additionalState The additional state values you would like 16196 * added to <var>baseState</var>; this array is not modified. 16197 * 16198 * @return As a convenience, the <var>baseState</var> array you originally 16199 * passed into the function is returned. 16200 * 16201 * @see #onCreateDrawableState(int) 16202 */ 16203 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 16204 final int N = baseState.length; 16205 int i = N - 1; 16206 while (i >= 0 && baseState[i] == 0) { 16207 i--; 16208 } 16209 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 16210 return baseState; 16211 } 16212 16213 /** 16214 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 16215 * on all Drawable objects associated with this view. 16216 * <p> 16217 * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator 16218 * attached to this view. 16219 */ 16220 public void jumpDrawablesToCurrentState() { 16221 if (mBackground != null) { 16222 mBackground.jumpToCurrentState(); 16223 } 16224 if (mStateListAnimator != null) { 16225 mStateListAnimator.jumpToCurrentState(); 16226 } 16227 } 16228 16229 /** 16230 * Sets the background color for this view. 16231 * @param color the color of the background 16232 */ 16233 @RemotableViewMethod 16234 public void setBackgroundColor(int color) { 16235 if (mBackground instanceof ColorDrawable) { 16236 ((ColorDrawable) mBackground.mutate()).setColor(color); 16237 computeOpaqueFlags(); 16238 mBackgroundResource = 0; 16239 } else { 16240 setBackground(new ColorDrawable(color)); 16241 } 16242 } 16243 16244 /** 16245 * Set the background to a given resource. The resource should refer to 16246 * a Drawable object or 0 to remove the background. 16247 * @param resid The identifier of the resource. 16248 * 16249 * @attr ref android.R.styleable#View_background 16250 */ 16251 @RemotableViewMethod 16252 public void setBackgroundResource(int resid) { 16253 if (resid != 0 && resid == mBackgroundResource) { 16254 return; 16255 } 16256 16257 Drawable d = null; 16258 if (resid != 0) { 16259 d = mContext.getDrawable(resid); 16260 } 16261 setBackground(d); 16262 16263 mBackgroundResource = resid; 16264 } 16265 16266 /** 16267 * Set the background to a given Drawable, or remove the background. If the 16268 * background has padding, this View's padding is set to the background's 16269 * padding. However, when a background is removed, this View's padding isn't 16270 * touched. If setting the padding is desired, please use 16271 * {@link #setPadding(int, int, int, int)}. 16272 * 16273 * @param background The Drawable to use as the background, or null to remove the 16274 * background 16275 */ 16276 public void setBackground(Drawable background) { 16277 //noinspection deprecation 16278 setBackgroundDrawable(background); 16279 } 16280 16281 /** 16282 * @deprecated use {@link #setBackground(Drawable)} instead 16283 */ 16284 @Deprecated 16285 public void setBackgroundDrawable(Drawable background) { 16286 computeOpaqueFlags(); 16287 16288 if (background == mBackground) { 16289 return; 16290 } 16291 16292 boolean requestLayout = false; 16293 16294 mBackgroundResource = 0; 16295 16296 /* 16297 * Regardless of whether we're setting a new background or not, we want 16298 * to clear the previous drawable. 16299 */ 16300 if (mBackground != null) { 16301 mBackground.setCallback(null); 16302 unscheduleDrawable(mBackground); 16303 } 16304 16305 if (background != null) { 16306 Rect padding = sThreadLocal.get(); 16307 if (padding == null) { 16308 padding = new Rect(); 16309 sThreadLocal.set(padding); 16310 } 16311 resetResolvedDrawables(); 16312 background.setLayoutDirection(getLayoutDirection()); 16313 if (background.getPadding(padding)) { 16314 resetResolvedPadding(); 16315 switch (background.getLayoutDirection()) { 16316 case LAYOUT_DIRECTION_RTL: 16317 mUserPaddingLeftInitial = padding.right; 16318 mUserPaddingRightInitial = padding.left; 16319 internalSetPadding(padding.right, padding.top, padding.left, padding.bottom); 16320 break; 16321 case LAYOUT_DIRECTION_LTR: 16322 default: 16323 mUserPaddingLeftInitial = padding.left; 16324 mUserPaddingRightInitial = padding.right; 16325 internalSetPadding(padding.left, padding.top, padding.right, padding.bottom); 16326 } 16327 mLeftPaddingDefined = false; 16328 mRightPaddingDefined = false; 16329 } 16330 16331 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 16332 // if it has a different minimum size, we should layout again 16333 if (mBackground == null 16334 || mBackground.getMinimumHeight() != background.getMinimumHeight() 16335 || mBackground.getMinimumWidth() != background.getMinimumWidth()) { 16336 requestLayout = true; 16337 } 16338 16339 background.setCallback(this); 16340 if (background.isStateful()) { 16341 background.setState(getDrawableState()); 16342 } 16343 background.setVisible(getVisibility() == VISIBLE, false); 16344 mBackground = background; 16345 16346 applyBackgroundTint(); 16347 16348 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 16349 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 16350 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 16351 requestLayout = true; 16352 } 16353 } else { 16354 /* Remove the background */ 16355 mBackground = null; 16356 16357 if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) { 16358 /* 16359 * This view ONLY drew the background before and we're removing 16360 * the background, so now it won't draw anything 16361 * (hence we SKIP_DRAW) 16362 */ 16363 mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND; 16364 mPrivateFlags |= PFLAG_SKIP_DRAW; 16365 } 16366 16367 /* 16368 * When the background is set, we try to apply its padding to this 16369 * View. When the background is removed, we don't touch this View's 16370 * padding. This is noted in the Javadocs. Hence, we don't need to 16371 * requestLayout(), the invalidate() below is sufficient. 16372 */ 16373 16374 // The old background's minimum size could have affected this 16375 // View's layout, so let's requestLayout 16376 requestLayout = true; 16377 } 16378 16379 computeOpaqueFlags(); 16380 16381 if (requestLayout) { 16382 requestLayout(); 16383 } 16384 16385 mBackgroundSizeChanged = true; 16386 invalidate(true); 16387 } 16388 16389 /** 16390 * Gets the background drawable 16391 * 16392 * @return The drawable used as the background for this view, if any. 16393 * 16394 * @see #setBackground(Drawable) 16395 * 16396 * @attr ref android.R.styleable#View_background 16397 */ 16398 public Drawable getBackground() { 16399 return mBackground; 16400 } 16401 16402 /** 16403 * Applies a tint to the background drawable. Does not modify the current tint 16404 * mode, which is {@link PorterDuff.Mode#SRC_IN} by default. 16405 * <p> 16406 * Subsequent calls to {@link #setBackground(Drawable)} will automatically 16407 * mutate the drawable and apply the specified tint and tint mode using 16408 * {@link Drawable#setTintList(ColorStateList)}. 16409 * 16410 * @param tint the tint to apply, may be {@code null} to clear tint 16411 * 16412 * @attr ref android.R.styleable#View_backgroundTint 16413 * @see #getBackgroundTintList() 16414 * @see Drawable#setTintList(ColorStateList) 16415 */ 16416 public void setBackgroundTintList(@Nullable ColorStateList tint) { 16417 if (mBackgroundTint == null) { 16418 mBackgroundTint = new TintInfo(); 16419 } 16420 mBackgroundTint.mTintList = tint; 16421 mBackgroundTint.mHasTintList = true; 16422 16423 applyBackgroundTint(); 16424 } 16425 16426 /** 16427 * Return the tint applied to the background drawable, if specified. 16428 * 16429 * @return the tint applied to the background drawable 16430 * @attr ref android.R.styleable#View_backgroundTint 16431 * @see #setBackgroundTintList(ColorStateList) 16432 */ 16433 @Nullable 16434 public ColorStateList getBackgroundTintList() { 16435 return mBackgroundTint != null ? mBackgroundTint.mTintList : null; 16436 } 16437 16438 /** 16439 * Specifies the blending mode used to apply the tint specified by 16440 * {@link #setBackgroundTintList(ColorStateList)}} to the background 16441 * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}. 16442 * 16443 * @param tintMode the blending mode used to apply the tint, may be 16444 * {@code null} to clear tint 16445 * @attr ref android.R.styleable#View_backgroundTintMode 16446 * @see #getBackgroundTintMode() 16447 * @see Drawable#setTintMode(PorterDuff.Mode) 16448 */ 16449 public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) { 16450 if (mBackgroundTint == null) { 16451 mBackgroundTint = new TintInfo(); 16452 } 16453 mBackgroundTint.mTintMode = tintMode; 16454 mBackgroundTint.mHasTintMode = true; 16455 16456 applyBackgroundTint(); 16457 } 16458 16459 /** 16460 * Return the blending mode used to apply the tint to the background 16461 * drawable, if specified. 16462 * 16463 * @return the blending mode used to apply the tint to the background 16464 * drawable 16465 * @attr ref android.R.styleable#View_backgroundTintMode 16466 * @see #setBackgroundTintMode(PorterDuff.Mode) 16467 */ 16468 @Nullable 16469 public PorterDuff.Mode getBackgroundTintMode() { 16470 return mBackgroundTint != null ? mBackgroundTint.mTintMode : null; 16471 } 16472 16473 private void applyBackgroundTint() { 16474 if (mBackground != null && mBackgroundTint != null) { 16475 final TintInfo tintInfo = mBackgroundTint; 16476 if (tintInfo.mHasTintList || tintInfo.mHasTintMode) { 16477 mBackground = mBackground.mutate(); 16478 16479 if (tintInfo.mHasTintList) { 16480 mBackground.setTintList(tintInfo.mTintList); 16481 } 16482 16483 if (tintInfo.mHasTintMode) { 16484 mBackground.setTintMode(tintInfo.mTintMode); 16485 } 16486 16487 // The drawable (or one of its children) may not have been 16488 // stateful before applying the tint, so let's try again. 16489 if (mBackground.isStateful()) { 16490 mBackground.setState(getDrawableState()); 16491 } 16492 } 16493 } 16494 } 16495 16496 /** 16497 * Sets the padding. The view may add on the space required to display 16498 * the scrollbars, depending on the style and visibility of the scrollbars. 16499 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 16500 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 16501 * from the values set in this call. 16502 * 16503 * @attr ref android.R.styleable#View_padding 16504 * @attr ref android.R.styleable#View_paddingBottom 16505 * @attr ref android.R.styleable#View_paddingLeft 16506 * @attr ref android.R.styleable#View_paddingRight 16507 * @attr ref android.R.styleable#View_paddingTop 16508 * @param left the left padding in pixels 16509 * @param top the top padding in pixels 16510 * @param right the right padding in pixels 16511 * @param bottom the bottom padding in pixels 16512 */ 16513 public void setPadding(int left, int top, int right, int bottom) { 16514 resetResolvedPadding(); 16515 16516 mUserPaddingStart = UNDEFINED_PADDING; 16517 mUserPaddingEnd = UNDEFINED_PADDING; 16518 16519 mUserPaddingLeftInitial = left; 16520 mUserPaddingRightInitial = right; 16521 16522 mLeftPaddingDefined = true; 16523 mRightPaddingDefined = true; 16524 16525 internalSetPadding(left, top, right, bottom); 16526 } 16527 16528 /** 16529 * @hide 16530 */ 16531 protected void internalSetPadding(int left, int top, int right, int bottom) { 16532 mUserPaddingLeft = left; 16533 mUserPaddingRight = right; 16534 mUserPaddingBottom = bottom; 16535 16536 final int viewFlags = mViewFlags; 16537 boolean changed = false; 16538 16539 // Common case is there are no scroll bars. 16540 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 16541 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 16542 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 16543 ? 0 : getVerticalScrollbarWidth(); 16544 switch (mVerticalScrollbarPosition) { 16545 case SCROLLBAR_POSITION_DEFAULT: 16546 if (isLayoutRtl()) { 16547 left += offset; 16548 } else { 16549 right += offset; 16550 } 16551 break; 16552 case SCROLLBAR_POSITION_RIGHT: 16553 right += offset; 16554 break; 16555 case SCROLLBAR_POSITION_LEFT: 16556 left += offset; 16557 break; 16558 } 16559 } 16560 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 16561 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 16562 ? 0 : getHorizontalScrollbarHeight(); 16563 } 16564 } 16565 16566 if (mPaddingLeft != left) { 16567 changed = true; 16568 mPaddingLeft = left; 16569 } 16570 if (mPaddingTop != top) { 16571 changed = true; 16572 mPaddingTop = top; 16573 } 16574 if (mPaddingRight != right) { 16575 changed = true; 16576 mPaddingRight = right; 16577 } 16578 if (mPaddingBottom != bottom) { 16579 changed = true; 16580 mPaddingBottom = bottom; 16581 } 16582 16583 if (changed) { 16584 requestLayout(); 16585 } 16586 } 16587 16588 /** 16589 * Sets the relative padding. The view may add on the space required to display 16590 * the scrollbars, depending on the style and visibility of the scrollbars. 16591 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 16592 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 16593 * from the values set in this call. 16594 * 16595 * @attr ref android.R.styleable#View_padding 16596 * @attr ref android.R.styleable#View_paddingBottom 16597 * @attr ref android.R.styleable#View_paddingStart 16598 * @attr ref android.R.styleable#View_paddingEnd 16599 * @attr ref android.R.styleable#View_paddingTop 16600 * @param start the start padding in pixels 16601 * @param top the top padding in pixels 16602 * @param end the end padding in pixels 16603 * @param bottom the bottom padding in pixels 16604 */ 16605 public void setPaddingRelative(int start, int top, int end, int bottom) { 16606 resetResolvedPadding(); 16607 16608 mUserPaddingStart = start; 16609 mUserPaddingEnd = end; 16610 mLeftPaddingDefined = true; 16611 mRightPaddingDefined = true; 16612 16613 switch(getLayoutDirection()) { 16614 case LAYOUT_DIRECTION_RTL: 16615 mUserPaddingLeftInitial = end; 16616 mUserPaddingRightInitial = start; 16617 internalSetPadding(end, top, start, bottom); 16618 break; 16619 case LAYOUT_DIRECTION_LTR: 16620 default: 16621 mUserPaddingLeftInitial = start; 16622 mUserPaddingRightInitial = end; 16623 internalSetPadding(start, top, end, bottom); 16624 } 16625 } 16626 16627 /** 16628 * Returns the top padding of this view. 16629 * 16630 * @return the top padding in pixels 16631 */ 16632 public int getPaddingTop() { 16633 return mPaddingTop; 16634 } 16635 16636 /** 16637 * Returns the bottom padding of this view. If there are inset and enabled 16638 * scrollbars, this value may include the space required to display the 16639 * scrollbars as well. 16640 * 16641 * @return the bottom padding in pixels 16642 */ 16643 public int getPaddingBottom() { 16644 return mPaddingBottom; 16645 } 16646 16647 /** 16648 * Returns the left padding of this view. If there are inset and enabled 16649 * scrollbars, this value may include the space required to display the 16650 * scrollbars as well. 16651 * 16652 * @return the left padding in pixels 16653 */ 16654 public int getPaddingLeft() { 16655 if (!isPaddingResolved()) { 16656 resolvePadding(); 16657 } 16658 return mPaddingLeft; 16659 } 16660 16661 /** 16662 * Returns the start padding of this view depending on its resolved layout direction. 16663 * If there are inset and enabled scrollbars, this value may include the space 16664 * required to display the scrollbars as well. 16665 * 16666 * @return the start padding in pixels 16667 */ 16668 public int getPaddingStart() { 16669 if (!isPaddingResolved()) { 16670 resolvePadding(); 16671 } 16672 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 16673 mPaddingRight : mPaddingLeft; 16674 } 16675 16676 /** 16677 * Returns the right padding of this view. If there are inset and enabled 16678 * scrollbars, this value may include the space required to display the 16679 * scrollbars as well. 16680 * 16681 * @return the right padding in pixels 16682 */ 16683 public int getPaddingRight() { 16684 if (!isPaddingResolved()) { 16685 resolvePadding(); 16686 } 16687 return mPaddingRight; 16688 } 16689 16690 /** 16691 * Returns the end padding of this view depending on its resolved layout direction. 16692 * If there are inset and enabled scrollbars, this value may include the space 16693 * required to display the scrollbars as well. 16694 * 16695 * @return the end padding in pixels 16696 */ 16697 public int getPaddingEnd() { 16698 if (!isPaddingResolved()) { 16699 resolvePadding(); 16700 } 16701 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 16702 mPaddingLeft : mPaddingRight; 16703 } 16704 16705 /** 16706 * Return if the padding as been set thru relative values 16707 * {@link #setPaddingRelative(int, int, int, int)} or thru 16708 * @attr ref android.R.styleable#View_paddingStart or 16709 * @attr ref android.R.styleable#View_paddingEnd 16710 * 16711 * @return true if the padding is relative or false if it is not. 16712 */ 16713 public boolean isPaddingRelative() { 16714 return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING); 16715 } 16716 16717 Insets computeOpticalInsets() { 16718 return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets(); 16719 } 16720 16721 /** 16722 * @hide 16723 */ 16724 public void resetPaddingToInitialValues() { 16725 if (isRtlCompatibilityMode()) { 16726 mPaddingLeft = mUserPaddingLeftInitial; 16727 mPaddingRight = mUserPaddingRightInitial; 16728 return; 16729 } 16730 if (isLayoutRtl()) { 16731 mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial; 16732 mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial; 16733 } else { 16734 mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial; 16735 mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial; 16736 } 16737 } 16738 16739 /** 16740 * @hide 16741 */ 16742 public Insets getOpticalInsets() { 16743 if (mLayoutInsets == null) { 16744 mLayoutInsets = computeOpticalInsets(); 16745 } 16746 return mLayoutInsets; 16747 } 16748 16749 /** 16750 * Set this view's optical insets. 16751 * 16752 * <p>This method should be treated similarly to setMeasuredDimension and not as a general 16753 * property. Views that compute their own optical insets should call it as part of measurement. 16754 * This method does not request layout. If you are setting optical insets outside of 16755 * measure/layout itself you will want to call requestLayout() yourself. 16756 * </p> 16757 * @hide 16758 */ 16759 public void setOpticalInsets(Insets insets) { 16760 mLayoutInsets = insets; 16761 } 16762 16763 /** 16764 * Changes the selection state of this view. A view can be selected or not. 16765 * Note that selection is not the same as focus. Views are typically 16766 * selected in the context of an AdapterView like ListView or GridView; 16767 * the selected view is the view that is highlighted. 16768 * 16769 * @param selected true if the view must be selected, false otherwise 16770 */ 16771 public void setSelected(boolean selected) { 16772 //noinspection DoubleNegation 16773 if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) { 16774 mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0); 16775 if (!selected) resetPressedState(); 16776 invalidate(true); 16777 refreshDrawableState(); 16778 dispatchSetSelected(selected); 16779 if (selected) { 16780 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED); 16781 } else { 16782 notifyViewAccessibilityStateChangedIfNeeded( 16783 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 16784 } 16785 } 16786 } 16787 16788 /** 16789 * Dispatch setSelected to all of this View's children. 16790 * 16791 * @see #setSelected(boolean) 16792 * 16793 * @param selected The new selected state 16794 */ 16795 protected void dispatchSetSelected(boolean selected) { 16796 } 16797 16798 /** 16799 * Indicates the selection state of this view. 16800 * 16801 * @return true if the view is selected, false otherwise 16802 */ 16803 @ViewDebug.ExportedProperty 16804 public boolean isSelected() { 16805 return (mPrivateFlags & PFLAG_SELECTED) != 0; 16806 } 16807 16808 /** 16809 * Changes the activated state of this view. A view can be activated or not. 16810 * Note that activation is not the same as selection. Selection is 16811 * a transient property, representing the view (hierarchy) the user is 16812 * currently interacting with. Activation is a longer-term state that the 16813 * user can move views in and out of. For example, in a list view with 16814 * single or multiple selection enabled, the views in the current selection 16815 * set are activated. (Um, yeah, we are deeply sorry about the terminology 16816 * here.) The activated state is propagated down to children of the view it 16817 * is set on. 16818 * 16819 * @param activated true if the view must be activated, false otherwise 16820 */ 16821 public void setActivated(boolean activated) { 16822 //noinspection DoubleNegation 16823 if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) { 16824 mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0); 16825 invalidate(true); 16826 refreshDrawableState(); 16827 dispatchSetActivated(activated); 16828 } 16829 } 16830 16831 /** 16832 * Dispatch setActivated to all of this View's children. 16833 * 16834 * @see #setActivated(boolean) 16835 * 16836 * @param activated The new activated state 16837 */ 16838 protected void dispatchSetActivated(boolean activated) { 16839 } 16840 16841 /** 16842 * Indicates the activation state of this view. 16843 * 16844 * @return true if the view is activated, false otherwise 16845 */ 16846 @ViewDebug.ExportedProperty 16847 public boolean isActivated() { 16848 return (mPrivateFlags & PFLAG_ACTIVATED) != 0; 16849 } 16850 16851 /** 16852 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 16853 * observer can be used to get notifications when global events, like 16854 * layout, happen. 16855 * 16856 * The returned ViewTreeObserver observer is not guaranteed to remain 16857 * valid for the lifetime of this View. If the caller of this method keeps 16858 * a long-lived reference to ViewTreeObserver, it should always check for 16859 * the return value of {@link ViewTreeObserver#isAlive()}. 16860 * 16861 * @return The ViewTreeObserver for this view's hierarchy. 16862 */ 16863 public ViewTreeObserver getViewTreeObserver() { 16864 if (mAttachInfo != null) { 16865 return mAttachInfo.mTreeObserver; 16866 } 16867 if (mFloatingTreeObserver == null) { 16868 mFloatingTreeObserver = new ViewTreeObserver(); 16869 } 16870 return mFloatingTreeObserver; 16871 } 16872 16873 /** 16874 * <p>Finds the topmost view in the current view hierarchy.</p> 16875 * 16876 * @return the topmost view containing this view 16877 */ 16878 public View getRootView() { 16879 if (mAttachInfo != null) { 16880 final View v = mAttachInfo.mRootView; 16881 if (v != null) { 16882 return v; 16883 } 16884 } 16885 16886 View parent = this; 16887 16888 while (parent.mParent != null && parent.mParent instanceof View) { 16889 parent = (View) parent.mParent; 16890 } 16891 16892 return parent; 16893 } 16894 16895 /** 16896 * Transforms a motion event from view-local coordinates to on-screen 16897 * coordinates. 16898 * 16899 * @param ev the view-local motion event 16900 * @return false if the transformation could not be applied 16901 * @hide 16902 */ 16903 public boolean toGlobalMotionEvent(MotionEvent ev) { 16904 final AttachInfo info = mAttachInfo; 16905 if (info == null) { 16906 return false; 16907 } 16908 16909 final Matrix m = info.mTmpMatrix; 16910 m.set(Matrix.IDENTITY_MATRIX); 16911 transformMatrixToGlobal(m); 16912 ev.transform(m); 16913 return true; 16914 } 16915 16916 /** 16917 * Transforms a motion event from on-screen coordinates to view-local 16918 * coordinates. 16919 * 16920 * @param ev the on-screen motion event 16921 * @return false if the transformation could not be applied 16922 * @hide 16923 */ 16924 public boolean toLocalMotionEvent(MotionEvent ev) { 16925 final AttachInfo info = mAttachInfo; 16926 if (info == null) { 16927 return false; 16928 } 16929 16930 final Matrix m = info.mTmpMatrix; 16931 m.set(Matrix.IDENTITY_MATRIX); 16932 transformMatrixToLocal(m); 16933 ev.transform(m); 16934 return true; 16935 } 16936 16937 /** 16938 * Modifies the input matrix such that it maps view-local coordinates to 16939 * on-screen coordinates. 16940 * 16941 * @param m input matrix to modify 16942 * @hide 16943 */ 16944 public void transformMatrixToGlobal(Matrix m) { 16945 final ViewParent parent = mParent; 16946 if (parent instanceof View) { 16947 final View vp = (View) parent; 16948 vp.transformMatrixToGlobal(m); 16949 m.preTranslate(-vp.mScrollX, -vp.mScrollY); 16950 } else if (parent instanceof ViewRootImpl) { 16951 final ViewRootImpl vr = (ViewRootImpl) parent; 16952 vr.transformMatrixToGlobal(m); 16953 m.preTranslate(0, -vr.mCurScrollY); 16954 } 16955 16956 m.preTranslate(mLeft, mTop); 16957 16958 if (!hasIdentityMatrix()) { 16959 m.preConcat(getMatrix()); 16960 } 16961 } 16962 16963 /** 16964 * Modifies the input matrix such that it maps on-screen coordinates to 16965 * view-local coordinates. 16966 * 16967 * @param m input matrix to modify 16968 * @hide 16969 */ 16970 public void transformMatrixToLocal(Matrix m) { 16971 final ViewParent parent = mParent; 16972 if (parent instanceof View) { 16973 final View vp = (View) parent; 16974 vp.transformMatrixToLocal(m); 16975 m.postTranslate(vp.mScrollX, vp.mScrollY); 16976 } else if (parent instanceof ViewRootImpl) { 16977 final ViewRootImpl vr = (ViewRootImpl) parent; 16978 vr.transformMatrixToLocal(m); 16979 m.postTranslate(0, vr.mCurScrollY); 16980 } 16981 16982 m.postTranslate(-mLeft, -mTop); 16983 16984 if (!hasIdentityMatrix()) { 16985 m.postConcat(getInverseMatrix()); 16986 } 16987 } 16988 16989 /** 16990 * @hide 16991 */ 16992 @ViewDebug.ExportedProperty(category = "layout", indexMapping = { 16993 @ViewDebug.IntToString(from = 0, to = "x"), 16994 @ViewDebug.IntToString(from = 1, to = "y") 16995 }) 16996 public int[] getLocationOnScreen() { 16997 int[] location = new int[2]; 16998 getLocationOnScreen(location); 16999 return location; 17000 } 17001 17002 /** 17003 * <p>Computes the coordinates of this view on the screen. The argument 17004 * must be an array of two integers. After the method returns, the array 17005 * contains the x and y location in that order.</p> 17006 * 17007 * @param location an array of two integers in which to hold the coordinates 17008 */ 17009 public void getLocationOnScreen(int[] location) { 17010 getLocationInWindow(location); 17011 17012 final AttachInfo info = mAttachInfo; 17013 if (info != null) { 17014 location[0] += info.mWindowLeft; 17015 location[1] += info.mWindowTop; 17016 } 17017 } 17018 17019 /** 17020 * <p>Computes the coordinates of this view in its window. The argument 17021 * must be an array of two integers. After the method returns, the array 17022 * contains the x and y location in that order.</p> 17023 * 17024 * @param location an array of two integers in which to hold the coordinates 17025 */ 17026 public void getLocationInWindow(int[] location) { 17027 if (location == null || location.length < 2) { 17028 throw new IllegalArgumentException("location must be an array of two integers"); 17029 } 17030 17031 if (mAttachInfo == null) { 17032 // When the view is not attached to a window, this method does not make sense 17033 location[0] = location[1] = 0; 17034 return; 17035 } 17036 17037 float[] position = mAttachInfo.mTmpTransformLocation; 17038 position[0] = position[1] = 0.0f; 17039 17040 if (!hasIdentityMatrix()) { 17041 getMatrix().mapPoints(position); 17042 } 17043 17044 position[0] += mLeft; 17045 position[1] += mTop; 17046 17047 ViewParent viewParent = mParent; 17048 while (viewParent instanceof View) { 17049 final View view = (View) viewParent; 17050 17051 position[0] -= view.mScrollX; 17052 position[1] -= view.mScrollY; 17053 17054 if (!view.hasIdentityMatrix()) { 17055 view.getMatrix().mapPoints(position); 17056 } 17057 17058 position[0] += view.mLeft; 17059 position[1] += view.mTop; 17060 17061 viewParent = view.mParent; 17062 } 17063 17064 if (viewParent instanceof ViewRootImpl) { 17065 // *cough* 17066 final ViewRootImpl vr = (ViewRootImpl) viewParent; 17067 position[1] -= vr.mCurScrollY; 17068 } 17069 17070 location[0] = (int) (position[0] + 0.5f); 17071 location[1] = (int) (position[1] + 0.5f); 17072 } 17073 17074 /** 17075 * {@hide} 17076 * @param id the id of the view to be found 17077 * @return the view of the specified id, null if cannot be found 17078 */ 17079 protected View findViewTraversal(int id) { 17080 if (id == mID) { 17081 return this; 17082 } 17083 return null; 17084 } 17085 17086 /** 17087 * {@hide} 17088 * @param tag the tag of the view to be found 17089 * @return the view of specified tag, null if cannot be found 17090 */ 17091 protected View findViewWithTagTraversal(Object tag) { 17092 if (tag != null && tag.equals(mTag)) { 17093 return this; 17094 } 17095 return null; 17096 } 17097 17098 /** 17099 * {@hide} 17100 * @param predicate The predicate to evaluate. 17101 * @param childToSkip If not null, ignores this child during the recursive traversal. 17102 * @return The first view that matches the predicate or null. 17103 */ 17104 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 17105 if (predicate.apply(this)) { 17106 return this; 17107 } 17108 return null; 17109 } 17110 17111 /** 17112 * Look for a child view with the given id. If this view has the given 17113 * id, return this view. 17114 * 17115 * @param id The id to search for. 17116 * @return The view that has the given id in the hierarchy or null 17117 */ 17118 public final View findViewById(int id) { 17119 if (id < 0) { 17120 return null; 17121 } 17122 return findViewTraversal(id); 17123 } 17124 17125 /** 17126 * Finds a view by its unuque and stable accessibility id. 17127 * 17128 * @param accessibilityId The searched accessibility id. 17129 * @return The found view. 17130 */ 17131 final View findViewByAccessibilityId(int accessibilityId) { 17132 if (accessibilityId < 0) { 17133 return null; 17134 } 17135 return findViewByAccessibilityIdTraversal(accessibilityId); 17136 } 17137 17138 /** 17139 * Performs the traversal to find a view by its unuque and stable accessibility id. 17140 * 17141 * <strong>Note:</strong>This method does not stop at the root namespace 17142 * boundary since the user can touch the screen at an arbitrary location 17143 * potentially crossing the root namespace bounday which will send an 17144 * accessibility event to accessibility services and they should be able 17145 * to obtain the event source. Also accessibility ids are guaranteed to be 17146 * unique in the window. 17147 * 17148 * @param accessibilityId The accessibility id. 17149 * @return The found view. 17150 * 17151 * @hide 17152 */ 17153 public View findViewByAccessibilityIdTraversal(int accessibilityId) { 17154 if (getAccessibilityViewId() == accessibilityId) { 17155 return this; 17156 } 17157 return null; 17158 } 17159 17160 /** 17161 * Look for a child view with the given tag. If this view has the given 17162 * tag, return this view. 17163 * 17164 * @param tag The tag to search for, using "tag.equals(getTag())". 17165 * @return The View that has the given tag in the hierarchy or null 17166 */ 17167 public final View findViewWithTag(Object tag) { 17168 if (tag == null) { 17169 return null; 17170 } 17171 return findViewWithTagTraversal(tag); 17172 } 17173 17174 /** 17175 * {@hide} 17176 * Look for a child view that matches the specified predicate. 17177 * If this view matches the predicate, return this view. 17178 * 17179 * @param predicate The predicate to evaluate. 17180 * @return The first view that matches the predicate or null. 17181 */ 17182 public final View findViewByPredicate(Predicate<View> predicate) { 17183 return findViewByPredicateTraversal(predicate, null); 17184 } 17185 17186 /** 17187 * {@hide} 17188 * Look for a child view that matches the specified predicate, 17189 * starting with the specified view and its descendents and then 17190 * recusively searching the ancestors and siblings of that view 17191 * until this view is reached. 17192 * 17193 * This method is useful in cases where the predicate does not match 17194 * a single unique view (perhaps multiple views use the same id) 17195 * and we are trying to find the view that is "closest" in scope to the 17196 * starting view. 17197 * 17198 * @param start The view to start from. 17199 * @param predicate The predicate to evaluate. 17200 * @return The first view that matches the predicate or null. 17201 */ 17202 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 17203 View childToSkip = null; 17204 for (;;) { 17205 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 17206 if (view != null || start == this) { 17207 return view; 17208 } 17209 17210 ViewParent parent = start.getParent(); 17211 if (parent == null || !(parent instanceof View)) { 17212 return null; 17213 } 17214 17215 childToSkip = start; 17216 start = (View) parent; 17217 } 17218 } 17219 17220 /** 17221 * Sets the identifier for this view. The identifier does not have to be 17222 * unique in this view's hierarchy. The identifier should be a positive 17223 * number. 17224 * 17225 * @see #NO_ID 17226 * @see #getId() 17227 * @see #findViewById(int) 17228 * 17229 * @param id a number used to identify the view 17230 * 17231 * @attr ref android.R.styleable#View_id 17232 */ 17233 public void setId(int id) { 17234 mID = id; 17235 if (mID == View.NO_ID && mLabelForId != View.NO_ID) { 17236 mID = generateViewId(); 17237 } 17238 } 17239 17240 /** 17241 * {@hide} 17242 * 17243 * @param isRoot true if the view belongs to the root namespace, false 17244 * otherwise 17245 */ 17246 public void setIsRootNamespace(boolean isRoot) { 17247 if (isRoot) { 17248 mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE; 17249 } else { 17250 mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE; 17251 } 17252 } 17253 17254 /** 17255 * {@hide} 17256 * 17257 * @return true if the view belongs to the root namespace, false otherwise 17258 */ 17259 public boolean isRootNamespace() { 17260 return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0; 17261 } 17262 17263 /** 17264 * Returns this view's identifier. 17265 * 17266 * @return a positive integer used to identify the view or {@link #NO_ID} 17267 * if the view has no ID 17268 * 17269 * @see #setId(int) 17270 * @see #findViewById(int) 17271 * @attr ref android.R.styleable#View_id 17272 */ 17273 @ViewDebug.CapturedViewProperty 17274 public int getId() { 17275 return mID; 17276 } 17277 17278 /** 17279 * Returns this view's tag. 17280 * 17281 * @return the Object stored in this view as a tag, or {@code null} if not 17282 * set 17283 * 17284 * @see #setTag(Object) 17285 * @see #getTag(int) 17286 */ 17287 @ViewDebug.ExportedProperty 17288 public Object getTag() { 17289 return mTag; 17290 } 17291 17292 /** 17293 * Sets the tag associated with this view. A tag can be used to mark 17294 * a view in its hierarchy and does not have to be unique within the 17295 * hierarchy. Tags can also be used to store data within a view without 17296 * resorting to another data structure. 17297 * 17298 * @param tag an Object to tag the view with 17299 * 17300 * @see #getTag() 17301 * @see #setTag(int, Object) 17302 */ 17303 public void setTag(final Object tag) { 17304 mTag = tag; 17305 } 17306 17307 /** 17308 * Returns the tag associated with this view and the specified key. 17309 * 17310 * @param key The key identifying the tag 17311 * 17312 * @return the Object stored in this view as a tag, or {@code null} if not 17313 * set 17314 * 17315 * @see #setTag(int, Object) 17316 * @see #getTag() 17317 */ 17318 public Object getTag(int key) { 17319 if (mKeyedTags != null) return mKeyedTags.get(key); 17320 return null; 17321 } 17322 17323 /** 17324 * Sets a tag associated with this view and a key. A tag can be used 17325 * to mark a view in its hierarchy and does not have to be unique within 17326 * the hierarchy. Tags can also be used to store data within a view 17327 * without resorting to another data structure. 17328 * 17329 * The specified key should be an id declared in the resources of the 17330 * application to ensure it is unique (see the <a 17331 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 17332 * Keys identified as belonging to 17333 * the Android framework or not associated with any package will cause 17334 * an {@link IllegalArgumentException} to be thrown. 17335 * 17336 * @param key The key identifying the tag 17337 * @param tag An Object to tag the view with 17338 * 17339 * @throws IllegalArgumentException If they specified key is not valid 17340 * 17341 * @see #setTag(Object) 17342 * @see #getTag(int) 17343 */ 17344 public void setTag(int key, final Object tag) { 17345 // If the package id is 0x00 or 0x01, it's either an undefined package 17346 // or a framework id 17347 if ((key >>> 24) < 2) { 17348 throw new IllegalArgumentException("The key must be an application-specific " 17349 + "resource id."); 17350 } 17351 17352 setKeyedTag(key, tag); 17353 } 17354 17355 /** 17356 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 17357 * framework id. 17358 * 17359 * @hide 17360 */ 17361 public void setTagInternal(int key, Object tag) { 17362 if ((key >>> 24) != 0x1) { 17363 throw new IllegalArgumentException("The key must be a framework-specific " 17364 + "resource id."); 17365 } 17366 17367 setKeyedTag(key, tag); 17368 } 17369 17370 private void setKeyedTag(int key, Object tag) { 17371 if (mKeyedTags == null) { 17372 mKeyedTags = new SparseArray<Object>(2); 17373 } 17374 17375 mKeyedTags.put(key, tag); 17376 } 17377 17378 /** 17379 * Prints information about this view in the log output, with the tag 17380 * {@link #VIEW_LOG_TAG}. 17381 * 17382 * @hide 17383 */ 17384 public void debug() { 17385 debug(0); 17386 } 17387 17388 /** 17389 * Prints information about this view in the log output, with the tag 17390 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 17391 * indentation defined by the <code>depth</code>. 17392 * 17393 * @param depth the indentation level 17394 * 17395 * @hide 17396 */ 17397 protected void debug(int depth) { 17398 String output = debugIndent(depth - 1); 17399 17400 output += "+ " + this; 17401 int id = getId(); 17402 if (id != -1) { 17403 output += " (id=" + id + ")"; 17404 } 17405 Object tag = getTag(); 17406 if (tag != null) { 17407 output += " (tag=" + tag + ")"; 17408 } 17409 Log.d(VIEW_LOG_TAG, output); 17410 17411 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 17412 output = debugIndent(depth) + " FOCUSED"; 17413 Log.d(VIEW_LOG_TAG, output); 17414 } 17415 17416 output = debugIndent(depth); 17417 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 17418 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 17419 + "} "; 17420 Log.d(VIEW_LOG_TAG, output); 17421 17422 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 17423 || mPaddingBottom != 0) { 17424 output = debugIndent(depth); 17425 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 17426 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 17427 Log.d(VIEW_LOG_TAG, output); 17428 } 17429 17430 output = debugIndent(depth); 17431 output += "mMeasureWidth=" + mMeasuredWidth + 17432 " mMeasureHeight=" + mMeasuredHeight; 17433 Log.d(VIEW_LOG_TAG, output); 17434 17435 output = debugIndent(depth); 17436 if (mLayoutParams == null) { 17437 output += "BAD! no layout params"; 17438 } else { 17439 output = mLayoutParams.debug(output); 17440 } 17441 Log.d(VIEW_LOG_TAG, output); 17442 17443 output = debugIndent(depth); 17444 output += "flags={"; 17445 output += View.printFlags(mViewFlags); 17446 output += "}"; 17447 Log.d(VIEW_LOG_TAG, output); 17448 17449 output = debugIndent(depth); 17450 output += "privateFlags={"; 17451 output += View.printPrivateFlags(mPrivateFlags); 17452 output += "}"; 17453 Log.d(VIEW_LOG_TAG, output); 17454 } 17455 17456 /** 17457 * Creates a string of whitespaces used for indentation. 17458 * 17459 * @param depth the indentation level 17460 * @return a String containing (depth * 2 + 3) * 2 white spaces 17461 * 17462 * @hide 17463 */ 17464 protected static String debugIndent(int depth) { 17465 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 17466 for (int i = 0; i < (depth * 2) + 3; i++) { 17467 spaces.append(' ').append(' '); 17468 } 17469 return spaces.toString(); 17470 } 17471 17472 /** 17473 * <p>Return the offset of the widget's text baseline from the widget's top 17474 * boundary. If this widget does not support baseline alignment, this 17475 * method returns -1. </p> 17476 * 17477 * @return the offset of the baseline within the widget's bounds or -1 17478 * if baseline alignment is not supported 17479 */ 17480 @ViewDebug.ExportedProperty(category = "layout") 17481 public int getBaseline() { 17482 return -1; 17483 } 17484 17485 /** 17486 * Returns whether the view hierarchy is currently undergoing a layout pass. This 17487 * information is useful to avoid situations such as calling {@link #requestLayout()} during 17488 * a layout pass. 17489 * 17490 * @return whether the view hierarchy is currently undergoing a layout pass 17491 */ 17492 public boolean isInLayout() { 17493 ViewRootImpl viewRoot = getViewRootImpl(); 17494 return (viewRoot != null && viewRoot.isInLayout()); 17495 } 17496 17497 /** 17498 * Call this when something has changed which has invalidated the 17499 * layout of this view. This will schedule a layout pass of the view 17500 * tree. This should not be called while the view hierarchy is currently in a layout 17501 * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the 17502 * end of the current layout pass (and then layout will run again) or after the current 17503 * frame is drawn and the next layout occurs. 17504 * 17505 * <p>Subclasses which override this method should call the superclass method to 17506 * handle possible request-during-layout errors correctly.</p> 17507 */ 17508 public void requestLayout() { 17509 if (mMeasureCache != null) mMeasureCache.clear(); 17510 17511 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) { 17512 // Only trigger request-during-layout logic if this is the view requesting it, 17513 // not the views in its parent hierarchy 17514 ViewRootImpl viewRoot = getViewRootImpl(); 17515 if (viewRoot != null && viewRoot.isInLayout()) { 17516 if (!viewRoot.requestLayoutDuringLayout(this)) { 17517 return; 17518 } 17519 } 17520 mAttachInfo.mViewRequestingLayout = this; 17521 } 17522 17523 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 17524 mPrivateFlags |= PFLAG_INVALIDATED; 17525 17526 if (mParent != null && !mParent.isLayoutRequested()) { 17527 mParent.requestLayout(); 17528 } 17529 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) { 17530 mAttachInfo.mViewRequestingLayout = null; 17531 } 17532 } 17533 17534 /** 17535 * Forces this view to be laid out during the next layout pass. 17536 * This method does not call requestLayout() or forceLayout() 17537 * on the parent. 17538 */ 17539 public void forceLayout() { 17540 if (mMeasureCache != null) mMeasureCache.clear(); 17541 17542 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 17543 mPrivateFlags |= PFLAG_INVALIDATED; 17544 } 17545 17546 /** 17547 * <p> 17548 * This is called to find out how big a view should be. The parent 17549 * supplies constraint information in the width and height parameters. 17550 * </p> 17551 * 17552 * <p> 17553 * The actual measurement work of a view is performed in 17554 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 17555 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 17556 * </p> 17557 * 17558 * 17559 * @param widthMeasureSpec Horizontal space requirements as imposed by the 17560 * parent 17561 * @param heightMeasureSpec Vertical space requirements as imposed by the 17562 * parent 17563 * 17564 * @see #onMeasure(int, int) 17565 */ 17566 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 17567 boolean optical = isLayoutModeOptical(this); 17568 if (optical != isLayoutModeOptical(mParent)) { 17569 Insets insets = getOpticalInsets(); 17570 int oWidth = insets.left + insets.right; 17571 int oHeight = insets.top + insets.bottom; 17572 widthMeasureSpec = MeasureSpec.adjust(widthMeasureSpec, optical ? -oWidth : oWidth); 17573 heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight); 17574 } 17575 17576 // Suppress sign extension for the low bytes 17577 long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL; 17578 if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2); 17579 17580 final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 17581 final boolean isExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY && 17582 MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY; 17583 final boolean matchingSize = isExactly && 17584 getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec) && 17585 getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec); 17586 if (forceLayout || !matchingSize && 17587 (widthMeasureSpec != mOldWidthMeasureSpec || 17588 heightMeasureSpec != mOldHeightMeasureSpec)) { 17589 17590 // first clears the measured dimension flag 17591 mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET; 17592 17593 resolveRtlPropertiesIfNeeded(); 17594 17595 int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key); 17596 if (cacheIndex < 0 || sIgnoreMeasureCache) { 17597 // measure ourselves, this should set the measured dimension flag back 17598 onMeasure(widthMeasureSpec, heightMeasureSpec); 17599 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 17600 } else { 17601 long value = mMeasureCache.valueAt(cacheIndex); 17602 // Casting a long to int drops the high 32 bits, no mask needed 17603 setMeasuredDimensionRaw((int) (value >> 32), (int) value); 17604 mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 17605 } 17606 17607 // flag not set, setMeasuredDimension() was not invoked, we raise 17608 // an exception to warn the developer 17609 if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) { 17610 throw new IllegalStateException("onMeasure() did not set the" 17611 + " measured dimension by calling" 17612 + " setMeasuredDimension()"); 17613 } 17614 17615 mPrivateFlags |= PFLAG_LAYOUT_REQUIRED; 17616 } 17617 17618 mOldWidthMeasureSpec = widthMeasureSpec; 17619 mOldHeightMeasureSpec = heightMeasureSpec; 17620 17621 mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 | 17622 (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension 17623 } 17624 17625 /** 17626 * <p> 17627 * Measure the view and its content to determine the measured width and the 17628 * measured height. This method is invoked by {@link #measure(int, int)} and 17629 * should be overriden by subclasses to provide accurate and efficient 17630 * measurement of their contents. 17631 * </p> 17632 * 17633 * <p> 17634 * <strong>CONTRACT:</strong> When overriding this method, you 17635 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 17636 * measured width and height of this view. Failure to do so will trigger an 17637 * <code>IllegalStateException</code>, thrown by 17638 * {@link #measure(int, int)}. Calling the superclass' 17639 * {@link #onMeasure(int, int)} is a valid use. 17640 * </p> 17641 * 17642 * <p> 17643 * The base class implementation of measure defaults to the background size, 17644 * unless a larger size is allowed by the MeasureSpec. Subclasses should 17645 * override {@link #onMeasure(int, int)} to provide better measurements of 17646 * their content. 17647 * </p> 17648 * 17649 * <p> 17650 * If this method is overridden, it is the subclass's responsibility to make 17651 * sure the measured height and width are at least the view's minimum height 17652 * and width ({@link #getSuggestedMinimumHeight()} and 17653 * {@link #getSuggestedMinimumWidth()}). 17654 * </p> 17655 * 17656 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 17657 * The requirements are encoded with 17658 * {@link android.view.View.MeasureSpec}. 17659 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 17660 * The requirements are encoded with 17661 * {@link android.view.View.MeasureSpec}. 17662 * 17663 * @see #getMeasuredWidth() 17664 * @see #getMeasuredHeight() 17665 * @see #setMeasuredDimension(int, int) 17666 * @see #getSuggestedMinimumHeight() 17667 * @see #getSuggestedMinimumWidth() 17668 * @see android.view.View.MeasureSpec#getMode(int) 17669 * @see android.view.View.MeasureSpec#getSize(int) 17670 */ 17671 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 17672 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 17673 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 17674 } 17675 17676 /** 17677 * <p>This method must be called by {@link #onMeasure(int, int)} to store the 17678 * measured width and measured height. Failing to do so will trigger an 17679 * exception at measurement time.</p> 17680 * 17681 * @param measuredWidth The measured width of this view. May be a complex 17682 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17683 * {@link #MEASURED_STATE_TOO_SMALL}. 17684 * @param measuredHeight The measured height of this view. May be a complex 17685 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17686 * {@link #MEASURED_STATE_TOO_SMALL}. 17687 */ 17688 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 17689 boolean optical = isLayoutModeOptical(this); 17690 if (optical != isLayoutModeOptical(mParent)) { 17691 Insets insets = getOpticalInsets(); 17692 int opticalWidth = insets.left + insets.right; 17693 int opticalHeight = insets.top + insets.bottom; 17694 17695 measuredWidth += optical ? opticalWidth : -opticalWidth; 17696 measuredHeight += optical ? opticalHeight : -opticalHeight; 17697 } 17698 setMeasuredDimensionRaw(measuredWidth, measuredHeight); 17699 } 17700 17701 /** 17702 * Sets the measured dimension without extra processing for things like optical bounds. 17703 * Useful for reapplying consistent values that have already been cooked with adjustments 17704 * for optical bounds, etc. such as those from the measurement cache. 17705 * 17706 * @param measuredWidth The measured width of this view. May be a complex 17707 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17708 * {@link #MEASURED_STATE_TOO_SMALL}. 17709 * @param measuredHeight The measured height of this view. May be a complex 17710 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17711 * {@link #MEASURED_STATE_TOO_SMALL}. 17712 */ 17713 private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) { 17714 mMeasuredWidth = measuredWidth; 17715 mMeasuredHeight = measuredHeight; 17716 17717 mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET; 17718 } 17719 17720 /** 17721 * Merge two states as returned by {@link #getMeasuredState()}. 17722 * @param curState The current state as returned from a view or the result 17723 * of combining multiple views. 17724 * @param newState The new view state to combine. 17725 * @return Returns a new integer reflecting the combination of the two 17726 * states. 17727 */ 17728 public static int combineMeasuredStates(int curState, int newState) { 17729 return curState | newState; 17730 } 17731 17732 /** 17733 * Version of {@link #resolveSizeAndState(int, int, int)} 17734 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 17735 */ 17736 public static int resolveSize(int size, int measureSpec) { 17737 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 17738 } 17739 17740 /** 17741 * Utility to reconcile a desired size and state, with constraints imposed 17742 * by a MeasureSpec. Will take the desired size, unless a different size 17743 * is imposed by the constraints. The returned value is a compound integer, 17744 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 17745 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting 17746 * size is smaller than the size the view wants to be. 17747 * 17748 * @param size How big the view wants to be 17749 * @param measureSpec Constraints imposed by the parent 17750 * @return Size information bit mask as defined by 17751 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 17752 */ 17753 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 17754 int result = size; 17755 int specMode = MeasureSpec.getMode(measureSpec); 17756 int specSize = MeasureSpec.getSize(measureSpec); 17757 switch (specMode) { 17758 case MeasureSpec.UNSPECIFIED: 17759 result = size; 17760 break; 17761 case MeasureSpec.AT_MOST: 17762 if (specSize < size) { 17763 result = specSize | MEASURED_STATE_TOO_SMALL; 17764 } else { 17765 result = size; 17766 } 17767 break; 17768 case MeasureSpec.EXACTLY: 17769 result = specSize; 17770 break; 17771 } 17772 return result | (childMeasuredState&MEASURED_STATE_MASK); 17773 } 17774 17775 /** 17776 * Utility to return a default size. Uses the supplied size if the 17777 * MeasureSpec imposed no constraints. Will get larger if allowed 17778 * by the MeasureSpec. 17779 * 17780 * @param size Default size for this view 17781 * @param measureSpec Constraints imposed by the parent 17782 * @return The size this view should be. 17783 */ 17784 public static int getDefaultSize(int size, int measureSpec) { 17785 int result = size; 17786 int specMode = MeasureSpec.getMode(measureSpec); 17787 int specSize = MeasureSpec.getSize(measureSpec); 17788 17789 switch (specMode) { 17790 case MeasureSpec.UNSPECIFIED: 17791 result = size; 17792 break; 17793 case MeasureSpec.AT_MOST: 17794 case MeasureSpec.EXACTLY: 17795 result = specSize; 17796 break; 17797 } 17798 return result; 17799 } 17800 17801 /** 17802 * Returns the suggested minimum height that the view should use. This 17803 * returns the maximum of the view's minimum height 17804 * and the background's minimum height 17805 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 17806 * <p> 17807 * When being used in {@link #onMeasure(int, int)}, the caller should still 17808 * ensure the returned height is within the requirements of the parent. 17809 * 17810 * @return The suggested minimum height of the view. 17811 */ 17812 protected int getSuggestedMinimumHeight() { 17813 return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight()); 17814 17815 } 17816 17817 /** 17818 * Returns the suggested minimum width that the view should use. This 17819 * returns the maximum of the view's minimum width) 17820 * and the background's minimum width 17821 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 17822 * <p> 17823 * When being used in {@link #onMeasure(int, int)}, the caller should still 17824 * ensure the returned width is within the requirements of the parent. 17825 * 17826 * @return The suggested minimum width of the view. 17827 */ 17828 protected int getSuggestedMinimumWidth() { 17829 return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); 17830 } 17831 17832 /** 17833 * Returns the minimum height of the view. 17834 * 17835 * @return the minimum height the view will try to be. 17836 * 17837 * @see #setMinimumHeight(int) 17838 * 17839 * @attr ref android.R.styleable#View_minHeight 17840 */ 17841 public int getMinimumHeight() { 17842 return mMinHeight; 17843 } 17844 17845 /** 17846 * Sets the minimum height of the view. It is not guaranteed the view will 17847 * be able to achieve this minimum height (for example, if its parent layout 17848 * constrains it with less available height). 17849 * 17850 * @param minHeight The minimum height the view will try to be. 17851 * 17852 * @see #getMinimumHeight() 17853 * 17854 * @attr ref android.R.styleable#View_minHeight 17855 */ 17856 public void setMinimumHeight(int minHeight) { 17857 mMinHeight = minHeight; 17858 requestLayout(); 17859 } 17860 17861 /** 17862 * Returns the minimum width of the view. 17863 * 17864 * @return the minimum width the view will try to be. 17865 * 17866 * @see #setMinimumWidth(int) 17867 * 17868 * @attr ref android.R.styleable#View_minWidth 17869 */ 17870 public int getMinimumWidth() { 17871 return mMinWidth; 17872 } 17873 17874 /** 17875 * Sets the minimum width of the view. It is not guaranteed the view will 17876 * be able to achieve this minimum width (for example, if its parent layout 17877 * constrains it with less available width). 17878 * 17879 * @param minWidth The minimum width the view will try to be. 17880 * 17881 * @see #getMinimumWidth() 17882 * 17883 * @attr ref android.R.styleable#View_minWidth 17884 */ 17885 public void setMinimumWidth(int minWidth) { 17886 mMinWidth = minWidth; 17887 requestLayout(); 17888 17889 } 17890 17891 /** 17892 * Get the animation currently associated with this view. 17893 * 17894 * @return The animation that is currently playing or 17895 * scheduled to play for this view. 17896 */ 17897 public Animation getAnimation() { 17898 return mCurrentAnimation; 17899 } 17900 17901 /** 17902 * Start the specified animation now. 17903 * 17904 * @param animation the animation to start now 17905 */ 17906 public void startAnimation(Animation animation) { 17907 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 17908 setAnimation(animation); 17909 invalidateParentCaches(); 17910 invalidate(true); 17911 } 17912 17913 /** 17914 * Cancels any animations for this view. 17915 */ 17916 public void clearAnimation() { 17917 if (mCurrentAnimation != null) { 17918 mCurrentAnimation.detach(); 17919 } 17920 mCurrentAnimation = null; 17921 invalidateParentIfNeeded(); 17922 } 17923 17924 /** 17925 * Sets the next animation to play for this view. 17926 * If you want the animation to play immediately, use 17927 * {@link #startAnimation(android.view.animation.Animation)} instead. 17928 * This method provides allows fine-grained 17929 * control over the start time and invalidation, but you 17930 * must make sure that 1) the animation has a start time set, and 17931 * 2) the view's parent (which controls animations on its children) 17932 * will be invalidated when the animation is supposed to 17933 * start. 17934 * 17935 * @param animation The next animation, or null. 17936 */ 17937 public void setAnimation(Animation animation) { 17938 mCurrentAnimation = animation; 17939 17940 if (animation != null) { 17941 // If the screen is off assume the animation start time is now instead of 17942 // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time 17943 // would cause the animation to start when the screen turns back on 17944 if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF 17945 && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) { 17946 animation.setStartTime(AnimationUtils.currentAnimationTimeMillis()); 17947 } 17948 animation.reset(); 17949 } 17950 } 17951 17952 /** 17953 * Invoked by a parent ViewGroup to notify the start of the animation 17954 * currently associated with this view. If you override this method, 17955 * always call super.onAnimationStart(); 17956 * 17957 * @see #setAnimation(android.view.animation.Animation) 17958 * @see #getAnimation() 17959 */ 17960 protected void onAnimationStart() { 17961 mPrivateFlags |= PFLAG_ANIMATION_STARTED; 17962 } 17963 17964 /** 17965 * Invoked by a parent ViewGroup to notify the end of the animation 17966 * currently associated with this view. If you override this method, 17967 * always call super.onAnimationEnd(); 17968 * 17969 * @see #setAnimation(android.view.animation.Animation) 17970 * @see #getAnimation() 17971 */ 17972 protected void onAnimationEnd() { 17973 mPrivateFlags &= ~PFLAG_ANIMATION_STARTED; 17974 } 17975 17976 /** 17977 * Invoked if there is a Transform that involves alpha. Subclass that can 17978 * draw themselves with the specified alpha should return true, and then 17979 * respect that alpha when their onDraw() is called. If this returns false 17980 * then the view may be redirected to draw into an offscreen buffer to 17981 * fulfill the request, which will look fine, but may be slower than if the 17982 * subclass handles it internally. The default implementation returns false. 17983 * 17984 * @param alpha The alpha (0..255) to apply to the view's drawing 17985 * @return true if the view can draw with the specified alpha. 17986 */ 17987 protected boolean onSetAlpha(int alpha) { 17988 return false; 17989 } 17990 17991 /** 17992 * This is used by the RootView to perform an optimization when 17993 * the view hierarchy contains one or several SurfaceView. 17994 * SurfaceView is always considered transparent, but its children are not, 17995 * therefore all View objects remove themselves from the global transparent 17996 * region (passed as a parameter to this function). 17997 * 17998 * @param region The transparent region for this ViewAncestor (window). 17999 * 18000 * @return Returns true if the effective visibility of the view at this 18001 * point is opaque, regardless of the transparent region; returns false 18002 * if it is possible for underlying windows to be seen behind the view. 18003 * 18004 * {@hide} 18005 */ 18006 public boolean gatherTransparentRegion(Region region) { 18007 final AttachInfo attachInfo = mAttachInfo; 18008 if (region != null && attachInfo != null) { 18009 final int pflags = mPrivateFlags; 18010 if ((pflags & PFLAG_SKIP_DRAW) == 0) { 18011 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 18012 // remove it from the transparent region. 18013 final int[] location = attachInfo.mTransparentLocation; 18014 getLocationInWindow(location); 18015 region.op(location[0], location[1], location[0] + mRight - mLeft, 18016 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 18017 } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null && 18018 mBackground.getOpacity() != PixelFormat.TRANSPARENT) { 18019 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 18020 // exists, so we remove the background drawable's non-transparent 18021 // parts from this transparent region. 18022 applyDrawableToTransparentRegion(mBackground, region); 18023 } 18024 } 18025 return true; 18026 } 18027 18028 /** 18029 * Play a sound effect for this view. 18030 * 18031 * <p>The framework will play sound effects for some built in actions, such as 18032 * clicking, but you may wish to play these effects in your widget, 18033 * for instance, for internal navigation. 18034 * 18035 * <p>The sound effect will only be played if sound effects are enabled by the user, and 18036 * {@link #isSoundEffectsEnabled()} is true. 18037 * 18038 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 18039 */ 18040 public void playSoundEffect(int soundConstant) { 18041 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 18042 return; 18043 } 18044 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 18045 } 18046 18047 /** 18048 * BZZZTT!!1! 18049 * 18050 * <p>Provide haptic feedback to the user for this view. 18051 * 18052 * <p>The framework will provide haptic feedback for some built in actions, 18053 * such as long presses, but you may wish to provide feedback for your 18054 * own widget. 18055 * 18056 * <p>The feedback will only be performed if 18057 * {@link #isHapticFeedbackEnabled()} is true. 18058 * 18059 * @param feedbackConstant One of the constants defined in 18060 * {@link HapticFeedbackConstants} 18061 */ 18062 public boolean performHapticFeedback(int feedbackConstant) { 18063 return performHapticFeedback(feedbackConstant, 0); 18064 } 18065 18066 /** 18067 * BZZZTT!!1! 18068 * 18069 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 18070 * 18071 * @param feedbackConstant One of the constants defined in 18072 * {@link HapticFeedbackConstants} 18073 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 18074 */ 18075 public boolean performHapticFeedback(int feedbackConstant, int flags) { 18076 if (mAttachInfo == null) { 18077 return false; 18078 } 18079 //noinspection SimplifiableIfStatement 18080 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 18081 && !isHapticFeedbackEnabled()) { 18082 return false; 18083 } 18084 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 18085 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 18086 } 18087 18088 /** 18089 * Request that the visibility of the status bar or other screen/window 18090 * decorations be changed. 18091 * 18092 * <p>This method is used to put the over device UI into temporary modes 18093 * where the user's attention is focused more on the application content, 18094 * by dimming or hiding surrounding system affordances. This is typically 18095 * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY 18096 * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content 18097 * to be placed behind the action bar (and with these flags other system 18098 * affordances) so that smooth transitions between hiding and showing them 18099 * can be done. 18100 * 18101 * <p>Two representative examples of the use of system UI visibility is 18102 * implementing a content browsing application (like a magazine reader) 18103 * and a video playing application. 18104 * 18105 * <p>The first code shows a typical implementation of a View in a content 18106 * browsing application. In this implementation, the application goes 18107 * into a content-oriented mode by hiding the status bar and action bar, 18108 * and putting the navigation elements into lights out mode. The user can 18109 * then interact with content while in this mode. Such an application should 18110 * provide an easy way for the user to toggle out of the mode (such as to 18111 * check information in the status bar or access notifications). In the 18112 * implementation here, this is done simply by tapping on the content. 18113 * 18114 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java 18115 * content} 18116 * 18117 * <p>This second code sample shows a typical implementation of a View 18118 * in a video playing application. In this situation, while the video is 18119 * playing the application would like to go into a complete full-screen mode, 18120 * to use as much of the display as possible for the video. When in this state 18121 * the user can not interact with the application; the system intercepts 18122 * touching on the screen to pop the UI out of full screen mode. See 18123 * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code. 18124 * 18125 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java 18126 * content} 18127 * 18128 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 18129 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 18130 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 18131 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 18132 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 18133 */ 18134 public void setSystemUiVisibility(int visibility) { 18135 if (visibility != mSystemUiVisibility) { 18136 mSystemUiVisibility = visibility; 18137 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 18138 mParent.recomputeViewAttributes(this); 18139 } 18140 } 18141 } 18142 18143 /** 18144 * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested. 18145 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 18146 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 18147 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 18148 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 18149 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 18150 */ 18151 public int getSystemUiVisibility() { 18152 return mSystemUiVisibility; 18153 } 18154 18155 /** 18156 * Returns the current system UI visibility that is currently set for 18157 * the entire window. This is the combination of the 18158 * {@link #setSystemUiVisibility(int)} values supplied by all of the 18159 * views in the window. 18160 */ 18161 public int getWindowSystemUiVisibility() { 18162 return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0; 18163 } 18164 18165 /** 18166 * Override to find out when the window's requested system UI visibility 18167 * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}. 18168 * This is different from the callbacks received through 18169 * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)} 18170 * in that this is only telling you about the local request of the window, 18171 * not the actual values applied by the system. 18172 */ 18173 public void onWindowSystemUiVisibilityChanged(int visible) { 18174 } 18175 18176 /** 18177 * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down 18178 * the view hierarchy. 18179 */ 18180 public void dispatchWindowSystemUiVisiblityChanged(int visible) { 18181 onWindowSystemUiVisibilityChanged(visible); 18182 } 18183 18184 /** 18185 * Set a listener to receive callbacks when the visibility of the system bar changes. 18186 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 18187 */ 18188 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 18189 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 18190 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 18191 mParent.recomputeViewAttributes(this); 18192 } 18193 } 18194 18195 /** 18196 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 18197 * the view hierarchy. 18198 */ 18199 public void dispatchSystemUiVisibilityChanged(int visibility) { 18200 ListenerInfo li = mListenerInfo; 18201 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 18202 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 18203 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 18204 } 18205 } 18206 18207 boolean updateLocalSystemUiVisibility(int localValue, int localChanges) { 18208 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 18209 if (val != mSystemUiVisibility) { 18210 setSystemUiVisibility(val); 18211 return true; 18212 } 18213 return false; 18214 } 18215 18216 /** @hide */ 18217 public void setDisabledSystemUiVisibility(int flags) { 18218 if (mAttachInfo != null) { 18219 if (mAttachInfo.mDisabledSystemUiVisibility != flags) { 18220 mAttachInfo.mDisabledSystemUiVisibility = flags; 18221 if (mParent != null) { 18222 mParent.recomputeViewAttributes(this); 18223 } 18224 } 18225 } 18226 } 18227 18228 /** 18229 * Creates an image that the system displays during the drag and drop 18230 * operation. This is called a "drag shadow". The default implementation 18231 * for a DragShadowBuilder based on a View returns an image that has exactly the same 18232 * appearance as the given View. The default also positions the center of the drag shadow 18233 * directly under the touch point. If no View is provided (the constructor with no parameters 18234 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 18235 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the 18236 * default is an invisible drag shadow. 18237 * <p> 18238 * You are not required to use the View you provide to the constructor as the basis of the 18239 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 18240 * anything you want as the drag shadow. 18241 * </p> 18242 * <p> 18243 * You pass a DragShadowBuilder object to the system when you start the drag. The system 18244 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 18245 * size and position of the drag shadow. It uses this data to construct a 18246 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 18247 * so that your application can draw the shadow image in the Canvas. 18248 * </p> 18249 * 18250 * <div class="special reference"> 18251 * <h3>Developer Guides</h3> 18252 * <p>For a guide to implementing drag and drop features, read the 18253 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 18254 * </div> 18255 */ 18256 public static class DragShadowBuilder { 18257 private final WeakReference<View> mView; 18258 18259 /** 18260 * Constructs a shadow image builder based on a View. By default, the resulting drag 18261 * shadow will have the same appearance and dimensions as the View, with the touch point 18262 * over the center of the View. 18263 * @param view A View. Any View in scope can be used. 18264 */ 18265 public DragShadowBuilder(View view) { 18266 mView = new WeakReference<View>(view); 18267 } 18268 18269 /** 18270 * Construct a shadow builder object with no associated View. This 18271 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 18272 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 18273 * to supply the drag shadow's dimensions and appearance without 18274 * reference to any View object. If they are not overridden, then the result is an 18275 * invisible drag shadow. 18276 */ 18277 public DragShadowBuilder() { 18278 mView = new WeakReference<View>(null); 18279 } 18280 18281 /** 18282 * Returns the View object that had been passed to the 18283 * {@link #View.DragShadowBuilder(View)} 18284 * constructor. If that View parameter was {@code null} or if the 18285 * {@link #View.DragShadowBuilder()} 18286 * constructor was used to instantiate the builder object, this method will return 18287 * null. 18288 * 18289 * @return The View object associate with this builder object. 18290 */ 18291 @SuppressWarnings({"JavadocReference"}) 18292 final public View getView() { 18293 return mView.get(); 18294 } 18295 18296 /** 18297 * Provides the metrics for the shadow image. These include the dimensions of 18298 * the shadow image, and the point within that shadow that should 18299 * be centered under the touch location while dragging. 18300 * <p> 18301 * The default implementation sets the dimensions of the shadow to be the 18302 * same as the dimensions of the View itself and centers the shadow under 18303 * the touch point. 18304 * </p> 18305 * 18306 * @param shadowSize A {@link android.graphics.Point} containing the width and height 18307 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 18308 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 18309 * image. 18310 * 18311 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 18312 * shadow image that should be underneath the touch point during the drag and drop 18313 * operation. Your application must set {@link android.graphics.Point#x} to the 18314 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 18315 */ 18316 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 18317 final View view = mView.get(); 18318 if (view != null) { 18319 shadowSize.set(view.getWidth(), view.getHeight()); 18320 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 18321 } else { 18322 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 18323 } 18324 } 18325 18326 /** 18327 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 18328 * based on the dimensions it received from the 18329 * {@link #onProvideShadowMetrics(Point, Point)} callback. 18330 * 18331 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 18332 */ 18333 public void onDrawShadow(Canvas canvas) { 18334 final View view = mView.get(); 18335 if (view != null) { 18336 view.draw(canvas); 18337 } else { 18338 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 18339 } 18340 } 18341 } 18342 18343 /** 18344 * Starts a drag and drop operation. When your application calls this method, it passes a 18345 * {@link android.view.View.DragShadowBuilder} object to the system. The 18346 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 18347 * to get metrics for the drag shadow, and then calls the object's 18348 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 18349 * <p> 18350 * Once the system has the drag shadow, it begins the drag and drop operation by sending 18351 * drag events to all the View objects in your application that are currently visible. It does 18352 * this either by calling the View object's drag listener (an implementation of 18353 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 18354 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 18355 * Both are passed a {@link android.view.DragEvent} object that has a 18356 * {@link android.view.DragEvent#getAction()} value of 18357 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 18358 * </p> 18359 * <p> 18360 * Your application can invoke startDrag() on any attached View object. The View object does not 18361 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to 18362 * be related to the View the user selected for dragging. 18363 * </p> 18364 * @param data A {@link android.content.ClipData} object pointing to the data to be 18365 * transferred by the drag and drop operation. 18366 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 18367 * drag shadow. 18368 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 18369 * drop operation. This Object is put into every DragEvent object sent by the system during the 18370 * current drag. 18371 * <p> 18372 * myLocalState is a lightweight mechanism for the sending information from the dragged View 18373 * to the target Views. For example, it can contain flags that differentiate between a 18374 * a copy operation and a move operation. 18375 * </p> 18376 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 18377 * so the parameter should be set to 0. 18378 * @return {@code true} if the method completes successfully, or 18379 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 18380 * do a drag, and so no drag operation is in progress. 18381 */ 18382 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 18383 Object myLocalState, int flags) { 18384 if (ViewDebug.DEBUG_DRAG) { 18385 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 18386 } 18387 boolean okay = false; 18388 18389 Point shadowSize = new Point(); 18390 Point shadowTouchPoint = new Point(); 18391 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 18392 18393 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 18394 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 18395 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 18396 } 18397 18398 if (ViewDebug.DEBUG_DRAG) { 18399 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 18400 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 18401 } 18402 Surface surface = new Surface(); 18403 try { 18404 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 18405 flags, shadowSize.x, shadowSize.y, surface); 18406 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 18407 + " surface=" + surface); 18408 if (token != null) { 18409 Canvas canvas = surface.lockCanvas(null); 18410 try { 18411 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 18412 shadowBuilder.onDrawShadow(canvas); 18413 } finally { 18414 surface.unlockCanvasAndPost(canvas); 18415 } 18416 18417 final ViewRootImpl root = getViewRootImpl(); 18418 18419 // Cache the local state object for delivery with DragEvents 18420 root.setLocalDragState(myLocalState); 18421 18422 // repurpose 'shadowSize' for the last touch point 18423 root.getLastTouchPoint(shadowSize); 18424 18425 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 18426 shadowSize.x, shadowSize.y, 18427 shadowTouchPoint.x, shadowTouchPoint.y, data); 18428 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 18429 18430 // Off and running! Release our local surface instance; the drag 18431 // shadow surface is now managed by the system process. 18432 surface.release(); 18433 } 18434 } catch (Exception e) { 18435 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 18436 surface.destroy(); 18437 } 18438 18439 return okay; 18440 } 18441 18442 /** 18443 * Handles drag events sent by the system following a call to 18444 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}. 18445 *<p> 18446 * When the system calls this method, it passes a 18447 * {@link android.view.DragEvent} object. A call to 18448 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 18449 * in DragEvent. The method uses these to determine what is happening in the drag and drop 18450 * operation. 18451 * @param event The {@link android.view.DragEvent} sent by the system. 18452 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 18453 * in DragEvent, indicating the type of drag event represented by this object. 18454 * @return {@code true} if the method was successful, otherwise {@code false}. 18455 * <p> 18456 * The method should return {@code true} in response to an action type of 18457 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 18458 * operation. 18459 * </p> 18460 * <p> 18461 * The method should also return {@code true} in response to an action type of 18462 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 18463 * {@code false} if it didn't. 18464 * </p> 18465 */ 18466 public boolean onDragEvent(DragEvent event) { 18467 return false; 18468 } 18469 18470 /** 18471 * Detects if this View is enabled and has a drag event listener. 18472 * If both are true, then it calls the drag event listener with the 18473 * {@link android.view.DragEvent} it received. If the drag event listener returns 18474 * {@code true}, then dispatchDragEvent() returns {@code true}. 18475 * <p> 18476 * For all other cases, the method calls the 18477 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 18478 * method and returns its result. 18479 * </p> 18480 * <p> 18481 * This ensures that a drag event is always consumed, even if the View does not have a drag 18482 * event listener. However, if the View has a listener and the listener returns true, then 18483 * onDragEvent() is not called. 18484 * </p> 18485 */ 18486 public boolean dispatchDragEvent(DragEvent event) { 18487 ListenerInfo li = mListenerInfo; 18488 //noinspection SimplifiableIfStatement 18489 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 18490 && li.mOnDragListener.onDrag(this, event)) { 18491 return true; 18492 } 18493 return onDragEvent(event); 18494 } 18495 18496 boolean canAcceptDrag() { 18497 return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0; 18498 } 18499 18500 /** 18501 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 18502 * it is ever exposed at all. 18503 * @hide 18504 */ 18505 public void onCloseSystemDialogs(String reason) { 18506 } 18507 18508 /** 18509 * Given a Drawable whose bounds have been set to draw into this view, 18510 * update a Region being computed for 18511 * {@link #gatherTransparentRegion(android.graphics.Region)} so 18512 * that any non-transparent parts of the Drawable are removed from the 18513 * given transparent region. 18514 * 18515 * @param dr The Drawable whose transparency is to be applied to the region. 18516 * @param region A Region holding the current transparency information, 18517 * where any parts of the region that are set are considered to be 18518 * transparent. On return, this region will be modified to have the 18519 * transparency information reduced by the corresponding parts of the 18520 * Drawable that are not transparent. 18521 * {@hide} 18522 */ 18523 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 18524 if (DBG) { 18525 Log.i("View", "Getting transparent region for: " + this); 18526 } 18527 final Region r = dr.getTransparentRegion(); 18528 final Rect db = dr.getBounds(); 18529 final AttachInfo attachInfo = mAttachInfo; 18530 if (r != null && attachInfo != null) { 18531 final int w = getRight()-getLeft(); 18532 final int h = getBottom()-getTop(); 18533 if (db.left > 0) { 18534 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 18535 r.op(0, 0, db.left, h, Region.Op.UNION); 18536 } 18537 if (db.right < w) { 18538 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 18539 r.op(db.right, 0, w, h, Region.Op.UNION); 18540 } 18541 if (db.top > 0) { 18542 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 18543 r.op(0, 0, w, db.top, Region.Op.UNION); 18544 } 18545 if (db.bottom < h) { 18546 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 18547 r.op(0, db.bottom, w, h, Region.Op.UNION); 18548 } 18549 final int[] location = attachInfo.mTransparentLocation; 18550 getLocationInWindow(location); 18551 r.translate(location[0], location[1]); 18552 region.op(r, Region.Op.INTERSECT); 18553 } else { 18554 region.op(db, Region.Op.DIFFERENCE); 18555 } 18556 } 18557 18558 private void checkForLongClick(int delayOffset) { 18559 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 18560 mHasPerformedLongPress = false; 18561 18562 if (mPendingCheckForLongPress == null) { 18563 mPendingCheckForLongPress = new CheckForLongPress(); 18564 } 18565 mPendingCheckForLongPress.rememberWindowAttachCount(); 18566 postDelayed(mPendingCheckForLongPress, 18567 ViewConfiguration.getLongPressTimeout() - delayOffset); 18568 } 18569 } 18570 18571 /** 18572 * Inflate a view from an XML resource. This convenience method wraps the {@link 18573 * LayoutInflater} class, which provides a full range of options for view inflation. 18574 * 18575 * @param context The Context object for your activity or application. 18576 * @param resource The resource ID to inflate 18577 * @param root A view group that will be the parent. Used to properly inflate the 18578 * layout_* parameters. 18579 * @see LayoutInflater 18580 */ 18581 public static View inflate(Context context, int resource, ViewGroup root) { 18582 LayoutInflater factory = LayoutInflater.from(context); 18583 return factory.inflate(resource, root); 18584 } 18585 18586 /** 18587 * Scroll the view with standard behavior for scrolling beyond the normal 18588 * content boundaries. Views that call this method should override 18589 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 18590 * results of an over-scroll operation. 18591 * 18592 * Views can use this method to handle any touch or fling-based scrolling. 18593 * 18594 * @param deltaX Change in X in pixels 18595 * @param deltaY Change in Y in pixels 18596 * @param scrollX Current X scroll value in pixels before applying deltaX 18597 * @param scrollY Current Y scroll value in pixels before applying deltaY 18598 * @param scrollRangeX Maximum content scroll range along the X axis 18599 * @param scrollRangeY Maximum content scroll range along the Y axis 18600 * @param maxOverScrollX Number of pixels to overscroll by in either direction 18601 * along the X axis. 18602 * @param maxOverScrollY Number of pixels to overscroll by in either direction 18603 * along the Y axis. 18604 * @param isTouchEvent true if this scroll operation is the result of a touch event. 18605 * @return true if scrolling was clamped to an over-scroll boundary along either 18606 * axis, false otherwise. 18607 */ 18608 @SuppressWarnings({"UnusedParameters"}) 18609 protected boolean overScrollBy(int deltaX, int deltaY, 18610 int scrollX, int scrollY, 18611 int scrollRangeX, int scrollRangeY, 18612 int maxOverScrollX, int maxOverScrollY, 18613 boolean isTouchEvent) { 18614 final int overScrollMode = mOverScrollMode; 18615 final boolean canScrollHorizontal = 18616 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 18617 final boolean canScrollVertical = 18618 computeVerticalScrollRange() > computeVerticalScrollExtent(); 18619 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 18620 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 18621 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 18622 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 18623 18624 int newScrollX = scrollX + deltaX; 18625 if (!overScrollHorizontal) { 18626 maxOverScrollX = 0; 18627 } 18628 18629 int newScrollY = scrollY + deltaY; 18630 if (!overScrollVertical) { 18631 maxOverScrollY = 0; 18632 } 18633 18634 // Clamp values if at the limits and record 18635 final int left = -maxOverScrollX; 18636 final int right = maxOverScrollX + scrollRangeX; 18637 final int top = -maxOverScrollY; 18638 final int bottom = maxOverScrollY + scrollRangeY; 18639 18640 boolean clampedX = false; 18641 if (newScrollX > right) { 18642 newScrollX = right; 18643 clampedX = true; 18644 } else if (newScrollX < left) { 18645 newScrollX = left; 18646 clampedX = true; 18647 } 18648 18649 boolean clampedY = false; 18650 if (newScrollY > bottom) { 18651 newScrollY = bottom; 18652 clampedY = true; 18653 } else if (newScrollY < top) { 18654 newScrollY = top; 18655 clampedY = true; 18656 } 18657 18658 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 18659 18660 return clampedX || clampedY; 18661 } 18662 18663 /** 18664 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 18665 * respond to the results of an over-scroll operation. 18666 * 18667 * @param scrollX New X scroll value in pixels 18668 * @param scrollY New Y scroll value in pixels 18669 * @param clampedX True if scrollX was clamped to an over-scroll boundary 18670 * @param clampedY True if scrollY was clamped to an over-scroll boundary 18671 */ 18672 protected void onOverScrolled(int scrollX, int scrollY, 18673 boolean clampedX, boolean clampedY) { 18674 // Intentionally empty. 18675 } 18676 18677 /** 18678 * Returns the over-scroll mode for this view. The result will be 18679 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 18680 * (allow over-scrolling only if the view content is larger than the container), 18681 * or {@link #OVER_SCROLL_NEVER}. 18682 * 18683 * @return This view's over-scroll mode. 18684 */ 18685 public int getOverScrollMode() { 18686 return mOverScrollMode; 18687 } 18688 18689 /** 18690 * Set the over-scroll mode for this view. Valid over-scroll modes are 18691 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 18692 * (allow over-scrolling only if the view content is larger than the container), 18693 * or {@link #OVER_SCROLL_NEVER}. 18694 * 18695 * Setting the over-scroll mode of a view will have an effect only if the 18696 * view is capable of scrolling. 18697 * 18698 * @param overScrollMode The new over-scroll mode for this view. 18699 */ 18700 public void setOverScrollMode(int overScrollMode) { 18701 if (overScrollMode != OVER_SCROLL_ALWAYS && 18702 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 18703 overScrollMode != OVER_SCROLL_NEVER) { 18704 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 18705 } 18706 mOverScrollMode = overScrollMode; 18707 } 18708 18709 /** 18710 * Enable or disable nested scrolling for this view. 18711 * 18712 * <p>If this property is set to true the view will be permitted to initiate nested 18713 * scrolling operations with a compatible parent view in the current hierarchy. If this 18714 * view does not implement nested scrolling this will have no effect. Disabling nested scrolling 18715 * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping} 18716 * the nested scroll.</p> 18717 * 18718 * @param enabled true to enable nested scrolling, false to disable 18719 * 18720 * @see #isNestedScrollingEnabled() 18721 */ 18722 public void setNestedScrollingEnabled(boolean enabled) { 18723 if (enabled) { 18724 mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED; 18725 } else { 18726 stopNestedScroll(); 18727 mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED; 18728 } 18729 } 18730 18731 /** 18732 * Returns true if nested scrolling is enabled for this view. 18733 * 18734 * <p>If nested scrolling is enabled and this View class implementation supports it, 18735 * this view will act as a nested scrolling child view when applicable, forwarding data 18736 * about the scroll operation in progress to a compatible and cooperating nested scrolling 18737 * parent.</p> 18738 * 18739 * @return true if nested scrolling is enabled 18740 * 18741 * @see #setNestedScrollingEnabled(boolean) 18742 */ 18743 public boolean isNestedScrollingEnabled() { 18744 return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) == 18745 PFLAG3_NESTED_SCROLLING_ENABLED; 18746 } 18747 18748 /** 18749 * Begin a nestable scroll operation along the given axes. 18750 * 18751 * <p>A view starting a nested scroll promises to abide by the following contract:</p> 18752 * 18753 * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case 18754 * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}. 18755 * In the case of touch scrolling the nested scroll will be terminated automatically in 18756 * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}. 18757 * In the event of programmatic scrolling the caller must explicitly call 18758 * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p> 18759 * 18760 * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found. 18761 * If it returns false the caller may ignore the rest of this contract until the next scroll. 18762 * Calling startNestedScroll while a nested scroll is already in progress will return true.</p> 18763 * 18764 * <p>At each incremental step of the scroll the caller should invoke 18765 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} 18766 * once it has calculated the requested scrolling delta. If it returns true the nested scrolling 18767 * parent at least partially consumed the scroll and the caller should adjust the amount it 18768 * scrolls by.</p> 18769 * 18770 * <p>After applying the remainder of the scroll delta the caller should invoke 18771 * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing 18772 * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat 18773 * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}. 18774 * </p> 18775 * 18776 * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or 18777 * {@link #SCROLL_AXIS_VERTICAL}. 18778 * @return true if a cooperative parent was found and nested scrolling has been enabled for 18779 * the current gesture. 18780 * 18781 * @see #stopNestedScroll() 18782 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 18783 * @see #dispatchNestedScroll(int, int, int, int, int[]) 18784 */ 18785 public boolean startNestedScroll(int axes) { 18786 if (hasNestedScrollingParent()) { 18787 // Already in progress 18788 return true; 18789 } 18790 if (isNestedScrollingEnabled()) { 18791 ViewParent p = getParent(); 18792 View child = this; 18793 while (p != null) { 18794 try { 18795 if (p.onStartNestedScroll(child, this, axes)) { 18796 mNestedScrollingParent = p; 18797 p.onNestedScrollAccepted(child, this, axes); 18798 return true; 18799 } 18800 } catch (AbstractMethodError e) { 18801 Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " + 18802 "method onStartNestedScroll", e); 18803 // Allow the search upward to continue 18804 } 18805 if (p instanceof View) { 18806 child = (View) p; 18807 } 18808 p = p.getParent(); 18809 } 18810 } 18811 return false; 18812 } 18813 18814 /** 18815 * Stop a nested scroll in progress. 18816 * 18817 * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p> 18818 * 18819 * @see #startNestedScroll(int) 18820 */ 18821 public void stopNestedScroll() { 18822 if (mNestedScrollingParent != null) { 18823 mNestedScrollingParent.onStopNestedScroll(this); 18824 mNestedScrollingParent = null; 18825 } 18826 } 18827 18828 /** 18829 * Returns true if this view has a nested scrolling parent. 18830 * 18831 * <p>The presence of a nested scrolling parent indicates that this view has initiated 18832 * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p> 18833 * 18834 * @return whether this view has a nested scrolling parent 18835 */ 18836 public boolean hasNestedScrollingParent() { 18837 return mNestedScrollingParent != null; 18838 } 18839 18840 /** 18841 * Dispatch one step of a nested scroll in progress. 18842 * 18843 * <p>Implementations of views that support nested scrolling should call this to report 18844 * info about a scroll in progress to the current nested scrolling parent. If a nested scroll 18845 * is not currently in progress or nested scrolling is not 18846 * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p> 18847 * 18848 * <p>Compatible View implementations should also call 18849 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before 18850 * consuming a component of the scroll event themselves.</p> 18851 * 18852 * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step 18853 * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step 18854 * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view 18855 * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view 18856 * @param offsetInWindow Optional. If not null, on return this will contain the offset 18857 * in local view coordinates of this view from before this operation 18858 * to after it completes. View implementations may use this to adjust 18859 * expected input coordinate tracking. 18860 * @return true if the event was dispatched, false if it could not be dispatched. 18861 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 18862 */ 18863 public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, 18864 int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow) { 18865 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18866 if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) { 18867 int startX = 0; 18868 int startY = 0; 18869 if (offsetInWindow != null) { 18870 getLocationInWindow(offsetInWindow); 18871 startX = offsetInWindow[0]; 18872 startY = offsetInWindow[1]; 18873 } 18874 18875 mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed, 18876 dxUnconsumed, dyUnconsumed); 18877 18878 if (offsetInWindow != null) { 18879 getLocationInWindow(offsetInWindow); 18880 offsetInWindow[0] -= startX; 18881 offsetInWindow[1] -= startY; 18882 } 18883 return true; 18884 } else if (offsetInWindow != null) { 18885 // No motion, no dispatch. Keep offsetInWindow up to date. 18886 offsetInWindow[0] = 0; 18887 offsetInWindow[1] = 0; 18888 } 18889 } 18890 return false; 18891 } 18892 18893 /** 18894 * Dispatch one step of a nested scroll in progress before this view consumes any portion of it. 18895 * 18896 * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch. 18897 * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested 18898 * scrolling operation to consume some or all of the scroll operation before the child view 18899 * consumes it.</p> 18900 * 18901 * @param dx Horizontal scroll distance in pixels 18902 * @param dy Vertical scroll distance in pixels 18903 * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx 18904 * and consumed[1] the consumed dy. 18905 * @param offsetInWindow Optional. If not null, on return this will contain the offset 18906 * in local view coordinates of this view from before this operation 18907 * to after it completes. View implementations may use this to adjust 18908 * expected input coordinate tracking. 18909 * @return true if the parent consumed some or all of the scroll delta 18910 * @see #dispatchNestedScroll(int, int, int, int, int[]) 18911 */ 18912 public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) { 18913 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18914 if (dx != 0 || dy != 0) { 18915 int startX = 0; 18916 int startY = 0; 18917 if (offsetInWindow != null) { 18918 getLocationInWindow(offsetInWindow); 18919 startX = offsetInWindow[0]; 18920 startY = offsetInWindow[1]; 18921 } 18922 18923 if (consumed == null) { 18924 if (mTempNestedScrollConsumed == null) { 18925 mTempNestedScrollConsumed = new int[2]; 18926 } 18927 consumed = mTempNestedScrollConsumed; 18928 } 18929 consumed[0] = 0; 18930 consumed[1] = 0; 18931 mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed); 18932 18933 if (offsetInWindow != null) { 18934 getLocationInWindow(offsetInWindow); 18935 offsetInWindow[0] -= startX; 18936 offsetInWindow[1] -= startY; 18937 } 18938 return consumed[0] != 0 || consumed[1] != 0; 18939 } else if (offsetInWindow != null) { 18940 offsetInWindow[0] = 0; 18941 offsetInWindow[1] = 0; 18942 } 18943 } 18944 return false; 18945 } 18946 18947 /** 18948 * Dispatch a fling to a nested scrolling parent. 18949 * 18950 * <p>This method should be used to indicate that a nested scrolling child has detected 18951 * suitable conditions for a fling. Generally this means that a touch scroll has ended with a 18952 * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds 18953 * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity} 18954 * along a scrollable axis.</p> 18955 * 18956 * <p>If a nested scrolling child view would normally fling but it is at the edge of 18957 * its own content, it can use this method to delegate the fling to its nested scrolling 18958 * parent instead. The parent may optionally consume the fling or observe a child fling.</p> 18959 * 18960 * @param velocityX Horizontal fling velocity in pixels per second 18961 * @param velocityY Vertical fling velocity in pixels per second 18962 * @param consumed true if the child consumed the fling, false otherwise 18963 * @return true if the nested scrolling parent consumed or otherwise reacted to the fling 18964 */ 18965 public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) { 18966 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18967 return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed); 18968 } 18969 return false; 18970 } 18971 18972 /** 18973 * Dispatch a fling to a nested scrolling parent before it is processed by this view. 18974 * 18975 * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch 18976 * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code> 18977 * offsets an opportunity for the parent view in a nested fling to fully consume the fling 18978 * before the child view consumes it. If this method returns <code>true</code>, a nested 18979 * parent view consumed the fling and this view should not scroll as a result.</p> 18980 * 18981 * <p>For a better user experience, only one view in a nested scrolling chain should consume 18982 * the fling at a time. If a parent view consumed the fling this method will return false. 18983 * Custom view implementations should account for this in two ways:</p> 18984 * 18985 * <ul> 18986 * <li>If a custom view is paged and needs to settle to a fixed page-point, do not 18987 * call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid 18988 * position regardless.</li> 18989 * <li>If a nested parent does consume the fling, this view should not scroll at all, 18990 * even to settle back to a valid idle position.</li> 18991 * </ul> 18992 * 18993 * <p>Views should also not offer fling velocities to nested parent views along an axis 18994 * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView} 18995 * should not offer a horizontal fling velocity to its parents since scrolling along that 18996 * axis is not permitted and carrying velocity along that motion does not make sense.</p> 18997 * 18998 * @param velocityX Horizontal fling velocity in pixels per second 18999 * @param velocityY Vertical fling velocity in pixels per second 19000 * @return true if a nested scrolling parent consumed the fling 19001 */ 19002 public boolean dispatchNestedPreFling(float velocityX, float velocityY) { 19003 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 19004 return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY); 19005 } 19006 return false; 19007 } 19008 19009 /** 19010 * Gets a scale factor that determines the distance the view should scroll 19011 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 19012 * @return The vertical scroll scale factor. 19013 * @hide 19014 */ 19015 protected float getVerticalScrollFactor() { 19016 if (mVerticalScrollFactor == 0) { 19017 TypedValue outValue = new TypedValue(); 19018 if (!mContext.getTheme().resolveAttribute( 19019 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 19020 throw new IllegalStateException( 19021 "Expected theme to define listPreferredItemHeight."); 19022 } 19023 mVerticalScrollFactor = outValue.getDimension( 19024 mContext.getResources().getDisplayMetrics()); 19025 } 19026 return mVerticalScrollFactor; 19027 } 19028 19029 /** 19030 * Gets a scale factor that determines the distance the view should scroll 19031 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 19032 * @return The horizontal scroll scale factor. 19033 * @hide 19034 */ 19035 protected float getHorizontalScrollFactor() { 19036 // TODO: Should use something else. 19037 return getVerticalScrollFactor(); 19038 } 19039 19040 /** 19041 * Return the value specifying the text direction or policy that was set with 19042 * {@link #setTextDirection(int)}. 19043 * 19044 * @return the defined text direction. It can be one of: 19045 * 19046 * {@link #TEXT_DIRECTION_INHERIT}, 19047 * {@link #TEXT_DIRECTION_FIRST_STRONG} 19048 * {@link #TEXT_DIRECTION_ANY_RTL}, 19049 * {@link #TEXT_DIRECTION_LTR}, 19050 * {@link #TEXT_DIRECTION_RTL}, 19051 * {@link #TEXT_DIRECTION_LOCALE} 19052 * 19053 * @attr ref android.R.styleable#View_textDirection 19054 * 19055 * @hide 19056 */ 19057 @ViewDebug.ExportedProperty(category = "text", mapping = { 19058 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 19059 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 19060 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 19061 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 19062 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 19063 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 19064 }) 19065 public int getRawTextDirection() { 19066 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 19067 } 19068 19069 /** 19070 * Set the text direction. 19071 * 19072 * @param textDirection the direction to set. Should be one of: 19073 * 19074 * {@link #TEXT_DIRECTION_INHERIT}, 19075 * {@link #TEXT_DIRECTION_FIRST_STRONG} 19076 * {@link #TEXT_DIRECTION_ANY_RTL}, 19077 * {@link #TEXT_DIRECTION_LTR}, 19078 * {@link #TEXT_DIRECTION_RTL}, 19079 * {@link #TEXT_DIRECTION_LOCALE} 19080 * 19081 * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution 19082 * proceeds up the parent chain of the view to get the value. If there is no parent, then it will 19083 * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}. 19084 * 19085 * @attr ref android.R.styleable#View_textDirection 19086 */ 19087 public void setTextDirection(int textDirection) { 19088 if (getRawTextDirection() != textDirection) { 19089 // Reset the current text direction and the resolved one 19090 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 19091 resetResolvedTextDirection(); 19092 // Set the new text direction 19093 mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK); 19094 // Do resolution 19095 resolveTextDirection(); 19096 // Notify change 19097 onRtlPropertiesChanged(getLayoutDirection()); 19098 // Refresh 19099 requestLayout(); 19100 invalidate(true); 19101 } 19102 } 19103 19104 /** 19105 * Return the resolved text direction. 19106 * 19107 * @return the resolved text direction. Returns one of: 19108 * 19109 * {@link #TEXT_DIRECTION_FIRST_STRONG} 19110 * {@link #TEXT_DIRECTION_ANY_RTL}, 19111 * {@link #TEXT_DIRECTION_LTR}, 19112 * {@link #TEXT_DIRECTION_RTL}, 19113 * {@link #TEXT_DIRECTION_LOCALE} 19114 * 19115 * @attr ref android.R.styleable#View_textDirection 19116 */ 19117 @ViewDebug.ExportedProperty(category = "text", mapping = { 19118 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 19119 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 19120 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 19121 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 19122 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 19123 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 19124 }) 19125 public int getTextDirection() { 19126 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 19127 } 19128 19129 /** 19130 * Resolve the text direction. 19131 * 19132 * @return true if resolution has been done, false otherwise. 19133 * 19134 * @hide 19135 */ 19136 public boolean resolveTextDirection() { 19137 // Reset any previous text direction resolution 19138 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 19139 19140 if (hasRtlSupport()) { 19141 // Set resolved text direction flag depending on text direction flag 19142 final int textDirection = getRawTextDirection(); 19143 switch(textDirection) { 19144 case TEXT_DIRECTION_INHERIT: 19145 if (!canResolveTextDirection()) { 19146 // We cannot do the resolution if there is no parent, so use the default one 19147 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 19148 // Resolution will need to happen again later 19149 return false; 19150 } 19151 19152 // Parent has not yet resolved, so we still return the default 19153 try { 19154 if (!mParent.isTextDirectionResolved()) { 19155 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 19156 // Resolution will need to happen again later 19157 return false; 19158 } 19159 } catch (AbstractMethodError e) { 19160 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 19161 " does not fully implement ViewParent", e); 19162 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED | 19163 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 19164 return true; 19165 } 19166 19167 // Set current resolved direction to the same value as the parent's one 19168 int parentResolvedDirection; 19169 try { 19170 parentResolvedDirection = mParent.getTextDirection(); 19171 } catch (AbstractMethodError e) { 19172 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 19173 " does not fully implement ViewParent", e); 19174 parentResolvedDirection = TEXT_DIRECTION_LTR; 19175 } 19176 switch (parentResolvedDirection) { 19177 case TEXT_DIRECTION_FIRST_STRONG: 19178 case TEXT_DIRECTION_ANY_RTL: 19179 case TEXT_DIRECTION_LTR: 19180 case TEXT_DIRECTION_RTL: 19181 case TEXT_DIRECTION_LOCALE: 19182 mPrivateFlags2 |= 19183 (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 19184 break; 19185 default: 19186 // Default resolved direction is "first strong" heuristic 19187 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 19188 } 19189 break; 19190 case TEXT_DIRECTION_FIRST_STRONG: 19191 case TEXT_DIRECTION_ANY_RTL: 19192 case TEXT_DIRECTION_LTR: 19193 case TEXT_DIRECTION_RTL: 19194 case TEXT_DIRECTION_LOCALE: 19195 // Resolved direction is the same as text direction 19196 mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 19197 break; 19198 default: 19199 // Default resolved direction is "first strong" heuristic 19200 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 19201 } 19202 } else { 19203 // Default resolved direction is "first strong" heuristic 19204 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 19205 } 19206 19207 // Set to resolved 19208 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED; 19209 return true; 19210 } 19211 19212 /** 19213 * Check if text direction resolution can be done. 19214 * 19215 * @return true if text direction resolution can be done otherwise return false. 19216 */ 19217 public boolean canResolveTextDirection() { 19218 switch (getRawTextDirection()) { 19219 case TEXT_DIRECTION_INHERIT: 19220 if (mParent != null) { 19221 try { 19222 return mParent.canResolveTextDirection(); 19223 } catch (AbstractMethodError e) { 19224 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 19225 " does not fully implement ViewParent", e); 19226 } 19227 } 19228 return false; 19229 19230 default: 19231 return true; 19232 } 19233 } 19234 19235 /** 19236 * Reset resolved text direction. Text direction will be resolved during a call to 19237 * {@link #onMeasure(int, int)}. 19238 * 19239 * @hide 19240 */ 19241 public void resetResolvedTextDirection() { 19242 // Reset any previous text direction resolution 19243 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 19244 // Set to default value 19245 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 19246 } 19247 19248 /** 19249 * @return true if text direction is inherited. 19250 * 19251 * @hide 19252 */ 19253 public boolean isTextDirectionInherited() { 19254 return (getRawTextDirection() == TEXT_DIRECTION_INHERIT); 19255 } 19256 19257 /** 19258 * @return true if text direction is resolved. 19259 */ 19260 public boolean isTextDirectionResolved() { 19261 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED; 19262 } 19263 19264 /** 19265 * Return the value specifying the text alignment or policy that was set with 19266 * {@link #setTextAlignment(int)}. 19267 * 19268 * @return the defined text alignment. It can be one of: 19269 * 19270 * {@link #TEXT_ALIGNMENT_INHERIT}, 19271 * {@link #TEXT_ALIGNMENT_GRAVITY}, 19272 * {@link #TEXT_ALIGNMENT_CENTER}, 19273 * {@link #TEXT_ALIGNMENT_TEXT_START}, 19274 * {@link #TEXT_ALIGNMENT_TEXT_END}, 19275 * {@link #TEXT_ALIGNMENT_VIEW_START}, 19276 * {@link #TEXT_ALIGNMENT_VIEW_END} 19277 * 19278 * @attr ref android.R.styleable#View_textAlignment 19279 * 19280 * @hide 19281 */ 19282 @ViewDebug.ExportedProperty(category = "text", mapping = { 19283 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 19284 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 19285 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 19286 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 19287 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 19288 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 19289 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 19290 }) 19291 @TextAlignment 19292 public int getRawTextAlignment() { 19293 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 19294 } 19295 19296 /** 19297 * Set the text alignment. 19298 * 19299 * @param textAlignment The text alignment to set. Should be one of 19300 * 19301 * {@link #TEXT_ALIGNMENT_INHERIT}, 19302 * {@link #TEXT_ALIGNMENT_GRAVITY}, 19303 * {@link #TEXT_ALIGNMENT_CENTER}, 19304 * {@link #TEXT_ALIGNMENT_TEXT_START}, 19305 * {@link #TEXT_ALIGNMENT_TEXT_END}, 19306 * {@link #TEXT_ALIGNMENT_VIEW_START}, 19307 * {@link #TEXT_ALIGNMENT_VIEW_END} 19308 * 19309 * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution 19310 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 19311 * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}. 19312 * 19313 * @attr ref android.R.styleable#View_textAlignment 19314 */ 19315 public void setTextAlignment(@TextAlignment int textAlignment) { 19316 if (textAlignment != getRawTextAlignment()) { 19317 // Reset the current and resolved text alignment 19318 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 19319 resetResolvedTextAlignment(); 19320 // Set the new text alignment 19321 mPrivateFlags2 |= 19322 ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK); 19323 // Do resolution 19324 resolveTextAlignment(); 19325 // Notify change 19326 onRtlPropertiesChanged(getLayoutDirection()); 19327 // Refresh 19328 requestLayout(); 19329 invalidate(true); 19330 } 19331 } 19332 19333 /** 19334 * Return the resolved text alignment. 19335 * 19336 * @return the resolved text alignment. Returns one of: 19337 * 19338 * {@link #TEXT_ALIGNMENT_GRAVITY}, 19339 * {@link #TEXT_ALIGNMENT_CENTER}, 19340 * {@link #TEXT_ALIGNMENT_TEXT_START}, 19341 * {@link #TEXT_ALIGNMENT_TEXT_END}, 19342 * {@link #TEXT_ALIGNMENT_VIEW_START}, 19343 * {@link #TEXT_ALIGNMENT_VIEW_END} 19344 * 19345 * @attr ref android.R.styleable#View_textAlignment 19346 */ 19347 @ViewDebug.ExportedProperty(category = "text", mapping = { 19348 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 19349 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 19350 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 19351 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 19352 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 19353 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 19354 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 19355 }) 19356 @TextAlignment 19357 public int getTextAlignment() { 19358 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >> 19359 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 19360 } 19361 19362 /** 19363 * Resolve the text alignment. 19364 * 19365 * @return true if resolution has been done, false otherwise. 19366 * 19367 * @hide 19368 */ 19369 public boolean resolveTextAlignment() { 19370 // Reset any previous text alignment resolution 19371 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 19372 19373 if (hasRtlSupport()) { 19374 // Set resolved text alignment flag depending on text alignment flag 19375 final int textAlignment = getRawTextAlignment(); 19376 switch (textAlignment) { 19377 case TEXT_ALIGNMENT_INHERIT: 19378 // Check if we can resolve the text alignment 19379 if (!canResolveTextAlignment()) { 19380 // We cannot do the resolution if there is no parent so use the default 19381 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 19382 // Resolution will need to happen again later 19383 return false; 19384 } 19385 19386 // Parent has not yet resolved, so we still return the default 19387 try { 19388 if (!mParent.isTextAlignmentResolved()) { 19389 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 19390 // Resolution will need to happen again later 19391 return false; 19392 } 19393 } catch (AbstractMethodError e) { 19394 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 19395 " does not fully implement ViewParent", e); 19396 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED | 19397 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 19398 return true; 19399 } 19400 19401 int parentResolvedTextAlignment; 19402 try { 19403 parentResolvedTextAlignment = mParent.getTextAlignment(); 19404 } catch (AbstractMethodError e) { 19405 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 19406 " does not fully implement ViewParent", e); 19407 parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY; 19408 } 19409 switch (parentResolvedTextAlignment) { 19410 case TEXT_ALIGNMENT_GRAVITY: 19411 case TEXT_ALIGNMENT_TEXT_START: 19412 case TEXT_ALIGNMENT_TEXT_END: 19413 case TEXT_ALIGNMENT_CENTER: 19414 case TEXT_ALIGNMENT_VIEW_START: 19415 case TEXT_ALIGNMENT_VIEW_END: 19416 // Resolved text alignment is the same as the parent resolved 19417 // text alignment 19418 mPrivateFlags2 |= 19419 (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 19420 break; 19421 default: 19422 // Use default resolved text alignment 19423 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 19424 } 19425 break; 19426 case TEXT_ALIGNMENT_GRAVITY: 19427 case TEXT_ALIGNMENT_TEXT_START: 19428 case TEXT_ALIGNMENT_TEXT_END: 19429 case TEXT_ALIGNMENT_CENTER: 19430 case TEXT_ALIGNMENT_VIEW_START: 19431 case TEXT_ALIGNMENT_VIEW_END: 19432 // Resolved text alignment is the same as text alignment 19433 mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 19434 break; 19435 default: 19436 // Use default resolved text alignment 19437 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 19438 } 19439 } else { 19440 // Use default resolved text alignment 19441 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 19442 } 19443 19444 // Set the resolved 19445 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED; 19446 return true; 19447 } 19448 19449 /** 19450 * Check if text alignment resolution can be done. 19451 * 19452 * @return true if text alignment resolution can be done otherwise return false. 19453 */ 19454 public boolean canResolveTextAlignment() { 19455 switch (getRawTextAlignment()) { 19456 case TEXT_DIRECTION_INHERIT: 19457 if (mParent != null) { 19458 try { 19459 return mParent.canResolveTextAlignment(); 19460 } catch (AbstractMethodError e) { 19461 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 19462 " does not fully implement ViewParent", e); 19463 } 19464 } 19465 return false; 19466 19467 default: 19468 return true; 19469 } 19470 } 19471 19472 /** 19473 * Reset resolved text alignment. Text alignment will be resolved during a call to 19474 * {@link #onMeasure(int, int)}. 19475 * 19476 * @hide 19477 */ 19478 public void resetResolvedTextAlignment() { 19479 // Reset any previous text alignment resolution 19480 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 19481 // Set to default 19482 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 19483 } 19484 19485 /** 19486 * @return true if text alignment is inherited. 19487 * 19488 * @hide 19489 */ 19490 public boolean isTextAlignmentInherited() { 19491 return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT); 19492 } 19493 19494 /** 19495 * @return true if text alignment is resolved. 19496 */ 19497 public boolean isTextAlignmentResolved() { 19498 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED; 19499 } 19500 19501 /** 19502 * Generate a value suitable for use in {@link #setId(int)}. 19503 * This value will not collide with ID values generated at build time by aapt for R.id. 19504 * 19505 * @return a generated ID value 19506 */ 19507 public static int generateViewId() { 19508 for (;;) { 19509 final int result = sNextGeneratedId.get(); 19510 // aapt-generated IDs have the high byte nonzero; clamp to the range under that. 19511 int newValue = result + 1; 19512 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. 19513 if (sNextGeneratedId.compareAndSet(result, newValue)) { 19514 return result; 19515 } 19516 } 19517 } 19518 19519 /** 19520 * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions. 19521 * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and 19522 * a normal View or a ViewGroup with 19523 * {@link android.view.ViewGroup#isTransitionGroup()} true. 19524 * @hide 19525 */ 19526 public void captureTransitioningViews(List<View> transitioningViews) { 19527 if (getVisibility() == View.VISIBLE) { 19528 transitioningViews.add(this); 19529 } 19530 } 19531 19532 /** 19533 * Adds all Views that have {@link #getTransitionName()} non-null to namedElements. 19534 * @param namedElements Will contain all Views in the hierarchy having a transitionName. 19535 * @hide 19536 */ 19537 public void findNamedViews(Map<String, View> namedElements) { 19538 if (getVisibility() == VISIBLE || mGhostView != null) { 19539 String transitionName = getTransitionName(); 19540 if (transitionName != null) { 19541 namedElements.put(transitionName, this); 19542 } 19543 } 19544 } 19545 19546 // 19547 // Properties 19548 // 19549 /** 19550 * A Property wrapper around the <code>alpha</code> functionality handled by the 19551 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 19552 */ 19553 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 19554 @Override 19555 public void setValue(View object, float value) { 19556 object.setAlpha(value); 19557 } 19558 19559 @Override 19560 public Float get(View object) { 19561 return object.getAlpha(); 19562 } 19563 }; 19564 19565 /** 19566 * A Property wrapper around the <code>translationX</code> functionality handled by the 19567 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 19568 */ 19569 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 19570 @Override 19571 public void setValue(View object, float value) { 19572 object.setTranslationX(value); 19573 } 19574 19575 @Override 19576 public Float get(View object) { 19577 return object.getTranslationX(); 19578 } 19579 }; 19580 19581 /** 19582 * A Property wrapper around the <code>translationY</code> functionality handled by the 19583 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 19584 */ 19585 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 19586 @Override 19587 public void setValue(View object, float value) { 19588 object.setTranslationY(value); 19589 } 19590 19591 @Override 19592 public Float get(View object) { 19593 return object.getTranslationY(); 19594 } 19595 }; 19596 19597 /** 19598 * A Property wrapper around the <code>translationZ</code> functionality handled by the 19599 * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods. 19600 */ 19601 public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") { 19602 @Override 19603 public void setValue(View object, float value) { 19604 object.setTranslationZ(value); 19605 } 19606 19607 @Override 19608 public Float get(View object) { 19609 return object.getTranslationZ(); 19610 } 19611 }; 19612 19613 /** 19614 * A Property wrapper around the <code>x</code> functionality handled by the 19615 * {@link View#setX(float)} and {@link View#getX()} methods. 19616 */ 19617 public static final Property<View, Float> X = new FloatProperty<View>("x") { 19618 @Override 19619 public void setValue(View object, float value) { 19620 object.setX(value); 19621 } 19622 19623 @Override 19624 public Float get(View object) { 19625 return object.getX(); 19626 } 19627 }; 19628 19629 /** 19630 * A Property wrapper around the <code>y</code> functionality handled by the 19631 * {@link View#setY(float)} and {@link View#getY()} methods. 19632 */ 19633 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 19634 @Override 19635 public void setValue(View object, float value) { 19636 object.setY(value); 19637 } 19638 19639 @Override 19640 public Float get(View object) { 19641 return object.getY(); 19642 } 19643 }; 19644 19645 /** 19646 * A Property wrapper around the <code>z</code> functionality handled by the 19647 * {@link View#setZ(float)} and {@link View#getZ()} methods. 19648 */ 19649 public static final Property<View, Float> Z = new FloatProperty<View>("z") { 19650 @Override 19651 public void setValue(View object, float value) { 19652 object.setZ(value); 19653 } 19654 19655 @Override 19656 public Float get(View object) { 19657 return object.getZ(); 19658 } 19659 }; 19660 19661 /** 19662 * A Property wrapper around the <code>rotation</code> functionality handled by the 19663 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 19664 */ 19665 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 19666 @Override 19667 public void setValue(View object, float value) { 19668 object.setRotation(value); 19669 } 19670 19671 @Override 19672 public Float get(View object) { 19673 return object.getRotation(); 19674 } 19675 }; 19676 19677 /** 19678 * A Property wrapper around the <code>rotationX</code> functionality handled by the 19679 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 19680 */ 19681 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 19682 @Override 19683 public void setValue(View object, float value) { 19684 object.setRotationX(value); 19685 } 19686 19687 @Override 19688 public Float get(View object) { 19689 return object.getRotationX(); 19690 } 19691 }; 19692 19693 /** 19694 * A Property wrapper around the <code>rotationY</code> functionality handled by the 19695 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 19696 */ 19697 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 19698 @Override 19699 public void setValue(View object, float value) { 19700 object.setRotationY(value); 19701 } 19702 19703 @Override 19704 public Float get(View object) { 19705 return object.getRotationY(); 19706 } 19707 }; 19708 19709 /** 19710 * A Property wrapper around the <code>scaleX</code> functionality handled by the 19711 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 19712 */ 19713 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 19714 @Override 19715 public void setValue(View object, float value) { 19716 object.setScaleX(value); 19717 } 19718 19719 @Override 19720 public Float get(View object) { 19721 return object.getScaleX(); 19722 } 19723 }; 19724 19725 /** 19726 * A Property wrapper around the <code>scaleY</code> functionality handled by the 19727 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 19728 */ 19729 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 19730 @Override 19731 public void setValue(View object, float value) { 19732 object.setScaleY(value); 19733 } 19734 19735 @Override 19736 public Float get(View object) { 19737 return object.getScaleY(); 19738 } 19739 }; 19740 19741 /** 19742 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 19743 * Each MeasureSpec represents a requirement for either the width or the height. 19744 * A MeasureSpec is comprised of a size and a mode. There are three possible 19745 * modes: 19746 * <dl> 19747 * <dt>UNSPECIFIED</dt> 19748 * <dd> 19749 * The parent has not imposed any constraint on the child. It can be whatever size 19750 * it wants. 19751 * </dd> 19752 * 19753 * <dt>EXACTLY</dt> 19754 * <dd> 19755 * The parent has determined an exact size for the child. The child is going to be 19756 * given those bounds regardless of how big it wants to be. 19757 * </dd> 19758 * 19759 * <dt>AT_MOST</dt> 19760 * <dd> 19761 * The child can be as large as it wants up to the specified size. 19762 * </dd> 19763 * </dl> 19764 * 19765 * MeasureSpecs are implemented as ints to reduce object allocation. This class 19766 * is provided to pack and unpack the <size, mode> tuple into the int. 19767 */ 19768 public static class MeasureSpec { 19769 private static final int MODE_SHIFT = 30; 19770 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 19771 19772 /** 19773 * Measure specification mode: The parent has not imposed any constraint 19774 * on the child. It can be whatever size it wants. 19775 */ 19776 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 19777 19778 /** 19779 * Measure specification mode: The parent has determined an exact size 19780 * for the child. The child is going to be given those bounds regardless 19781 * of how big it wants to be. 19782 */ 19783 public static final int EXACTLY = 1 << MODE_SHIFT; 19784 19785 /** 19786 * Measure specification mode: The child can be as large as it wants up 19787 * to the specified size. 19788 */ 19789 public static final int AT_MOST = 2 << MODE_SHIFT; 19790 19791 /** 19792 * Creates a measure specification based on the supplied size and mode. 19793 * 19794 * The mode must always be one of the following: 19795 * <ul> 19796 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 19797 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 19798 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 19799 * </ul> 19800 * 19801 * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's 19802 * implementation was such that the order of arguments did not matter 19803 * and overflow in either value could impact the resulting MeasureSpec. 19804 * {@link android.widget.RelativeLayout} was affected by this bug. 19805 * Apps targeting API levels greater than 17 will get the fixed, more strict 19806 * behavior.</p> 19807 * 19808 * @param size the size of the measure specification 19809 * @param mode the mode of the measure specification 19810 * @return the measure specification based on size and mode 19811 */ 19812 public static int makeMeasureSpec(int size, int mode) { 19813 if (sUseBrokenMakeMeasureSpec) { 19814 return size + mode; 19815 } else { 19816 return (size & ~MODE_MASK) | (mode & MODE_MASK); 19817 } 19818 } 19819 19820 /** 19821 * Extracts the mode from the supplied measure specification. 19822 * 19823 * @param measureSpec the measure specification to extract the mode from 19824 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 19825 * {@link android.view.View.MeasureSpec#AT_MOST} or 19826 * {@link android.view.View.MeasureSpec#EXACTLY} 19827 */ 19828 public static int getMode(int measureSpec) { 19829 return (measureSpec & MODE_MASK); 19830 } 19831 19832 /** 19833 * Extracts the size from the supplied measure specification. 19834 * 19835 * @param measureSpec the measure specification to extract the size from 19836 * @return the size in pixels defined in the supplied measure specification 19837 */ 19838 public static int getSize(int measureSpec) { 19839 return (measureSpec & ~MODE_MASK); 19840 } 19841 19842 static int adjust(int measureSpec, int delta) { 19843 final int mode = getMode(measureSpec); 19844 if (mode == UNSPECIFIED) { 19845 // No need to adjust size for UNSPECIFIED mode. 19846 return makeMeasureSpec(0, UNSPECIFIED); 19847 } 19848 int size = getSize(measureSpec) + delta; 19849 if (size < 0) { 19850 Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size + 19851 ") spec: " + toString(measureSpec) + " delta: " + delta); 19852 size = 0; 19853 } 19854 return makeMeasureSpec(size, mode); 19855 } 19856 19857 /** 19858 * Returns a String representation of the specified measure 19859 * specification. 19860 * 19861 * @param measureSpec the measure specification to convert to a String 19862 * @return a String with the following format: "MeasureSpec: MODE SIZE" 19863 */ 19864 public static String toString(int measureSpec) { 19865 int mode = getMode(measureSpec); 19866 int size = getSize(measureSpec); 19867 19868 StringBuilder sb = new StringBuilder("MeasureSpec: "); 19869 19870 if (mode == UNSPECIFIED) 19871 sb.append("UNSPECIFIED "); 19872 else if (mode == EXACTLY) 19873 sb.append("EXACTLY "); 19874 else if (mode == AT_MOST) 19875 sb.append("AT_MOST "); 19876 else 19877 sb.append(mode).append(" "); 19878 19879 sb.append(size); 19880 return sb.toString(); 19881 } 19882 } 19883 19884 private final class CheckForLongPress implements Runnable { 19885 private int mOriginalWindowAttachCount; 19886 19887 @Override 19888 public void run() { 19889 if (isPressed() && (mParent != null) 19890 && mOriginalWindowAttachCount == mWindowAttachCount) { 19891 if (performLongClick()) { 19892 mHasPerformedLongPress = true; 19893 } 19894 } 19895 } 19896 19897 public void rememberWindowAttachCount() { 19898 mOriginalWindowAttachCount = mWindowAttachCount; 19899 } 19900 } 19901 19902 private final class CheckForTap implements Runnable { 19903 public float x; 19904 public float y; 19905 19906 @Override 19907 public void run() { 19908 mPrivateFlags &= ~PFLAG_PREPRESSED; 19909 setPressed(true, x, y); 19910 checkForLongClick(ViewConfiguration.getTapTimeout()); 19911 } 19912 } 19913 19914 private final class PerformClick implements Runnable { 19915 @Override 19916 public void run() { 19917 performClick(); 19918 } 19919 } 19920 19921 /** @hide */ 19922 public void hackTurnOffWindowResizeAnim(boolean off) { 19923 mAttachInfo.mTurnOffWindowResizeAnim = off; 19924 } 19925 19926 /** 19927 * This method returns a ViewPropertyAnimator object, which can be used to animate 19928 * specific properties on this View. 19929 * 19930 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 19931 */ 19932 public ViewPropertyAnimator animate() { 19933 if (mAnimator == null) { 19934 mAnimator = new ViewPropertyAnimator(this); 19935 } 19936 return mAnimator; 19937 } 19938 19939 /** 19940 * Sets the name of the View to be used to identify Views in Transitions. 19941 * Names should be unique in the View hierarchy. 19942 * 19943 * @param transitionName The name of the View to uniquely identify it for Transitions. 19944 */ 19945 public final void setTransitionName(String transitionName) { 19946 mTransitionName = transitionName; 19947 } 19948 19949 /** 19950 * Returns the name of the View to be used to identify Views in Transitions. 19951 * Names should be unique in the View hierarchy. 19952 * 19953 * <p>This returns null if the View has not been given a name.</p> 19954 * 19955 * @return The name used of the View to be used to identify Views in Transitions or null 19956 * if no name has been given. 19957 */ 19958 @ViewDebug.ExportedProperty 19959 public String getTransitionName() { 19960 return mTransitionName; 19961 } 19962 19963 /** 19964 * Interface definition for a callback to be invoked when a hardware key event is 19965 * dispatched to this view. The callback will be invoked before the key event is 19966 * given to the view. This is only useful for hardware keyboards; a software input 19967 * method has no obligation to trigger this listener. 19968 */ 19969 public interface OnKeyListener { 19970 /** 19971 * Called when a hardware key is dispatched to a view. This allows listeners to 19972 * get a chance to respond before the target view. 19973 * <p>Key presses in software keyboards will generally NOT trigger this method, 19974 * although some may elect to do so in some situations. Do not assume a 19975 * software input method has to be key-based; even if it is, it may use key presses 19976 * in a different way than you expect, so there is no way to reliably catch soft 19977 * input key presses. 19978 * 19979 * @param v The view the key has been dispatched to. 19980 * @param keyCode The code for the physical key that was pressed 19981 * @param event The KeyEvent object containing full information about 19982 * the event. 19983 * @return True if the listener has consumed the event, false otherwise. 19984 */ 19985 boolean onKey(View v, int keyCode, KeyEvent event); 19986 } 19987 19988 /** 19989 * Interface definition for a callback to be invoked when a touch event is 19990 * dispatched to this view. The callback will be invoked before the touch 19991 * event is given to the view. 19992 */ 19993 public interface OnTouchListener { 19994 /** 19995 * Called when a touch event is dispatched to a view. This allows listeners to 19996 * get a chance to respond before the target view. 19997 * 19998 * @param v The view the touch event has been dispatched to. 19999 * @param event The MotionEvent object containing full information about 20000 * the event. 20001 * @return True if the listener has consumed the event, false otherwise. 20002 */ 20003 boolean onTouch(View v, MotionEvent event); 20004 } 20005 20006 /** 20007 * Interface definition for a callback to be invoked when a hover event is 20008 * dispatched to this view. The callback will be invoked before the hover 20009 * event is given to the view. 20010 */ 20011 public interface OnHoverListener { 20012 /** 20013 * Called when a hover event is dispatched to a view. This allows listeners to 20014 * get a chance to respond before the target view. 20015 * 20016 * @param v The view the hover event has been dispatched to. 20017 * @param event The MotionEvent object containing full information about 20018 * the event. 20019 * @return True if the listener has consumed the event, false otherwise. 20020 */ 20021 boolean onHover(View v, MotionEvent event); 20022 } 20023 20024 /** 20025 * Interface definition for a callback to be invoked when a generic motion event is 20026 * dispatched to this view. The callback will be invoked before the generic motion 20027 * event is given to the view. 20028 */ 20029 public interface OnGenericMotionListener { 20030 /** 20031 * Called when a generic motion event is dispatched to a view. This allows listeners to 20032 * get a chance to respond before the target view. 20033 * 20034 * @param v The view the generic motion event has been dispatched to. 20035 * @param event The MotionEvent object containing full information about 20036 * the event. 20037 * @return True if the listener has consumed the event, false otherwise. 20038 */ 20039 boolean onGenericMotion(View v, MotionEvent event); 20040 } 20041 20042 /** 20043 * Interface definition for a callback to be invoked when a view has been clicked and held. 20044 */ 20045 public interface OnLongClickListener { 20046 /** 20047 * Called when a view has been clicked and held. 20048 * 20049 * @param v The view that was clicked and held. 20050 * 20051 * @return true if the callback consumed the long click, false otherwise. 20052 */ 20053 boolean onLongClick(View v); 20054 } 20055 20056 /** 20057 * Interface definition for a callback to be invoked when a drag is being dispatched 20058 * to this view. The callback will be invoked before the hosting view's own 20059 * onDrag(event) method. If the listener wants to fall back to the hosting view's 20060 * onDrag(event) behavior, it should return 'false' from this callback. 20061 * 20062 * <div class="special reference"> 20063 * <h3>Developer Guides</h3> 20064 * <p>For a guide to implementing drag and drop features, read the 20065 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 20066 * </div> 20067 */ 20068 public interface OnDragListener { 20069 /** 20070 * Called when a drag event is dispatched to a view. This allows listeners 20071 * to get a chance to override base View behavior. 20072 * 20073 * @param v The View that received the drag event. 20074 * @param event The {@link android.view.DragEvent} object for the drag event. 20075 * @return {@code true} if the drag event was handled successfully, or {@code false} 20076 * if the drag event was not handled. Note that {@code false} will trigger the View 20077 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 20078 */ 20079 boolean onDrag(View v, DragEvent event); 20080 } 20081 20082 /** 20083 * Interface definition for a callback to be invoked when the focus state of 20084 * a view changed. 20085 */ 20086 public interface OnFocusChangeListener { 20087 /** 20088 * Called when the focus state of a view has changed. 20089 * 20090 * @param v The view whose state has changed. 20091 * @param hasFocus The new focus state of v. 20092 */ 20093 void onFocusChange(View v, boolean hasFocus); 20094 } 20095 20096 /** 20097 * Interface definition for a callback to be invoked when a view is clicked. 20098 */ 20099 public interface OnClickListener { 20100 /** 20101 * Called when a view has been clicked. 20102 * 20103 * @param v The view that was clicked. 20104 */ 20105 void onClick(View v); 20106 } 20107 20108 /** 20109 * Interface definition for a callback to be invoked when the context menu 20110 * for this view is being built. 20111 */ 20112 public interface OnCreateContextMenuListener { 20113 /** 20114 * Called when the context menu for this view is being built. It is not 20115 * safe to hold onto the menu after this method returns. 20116 * 20117 * @param menu The context menu that is being built 20118 * @param v The view for which the context menu is being built 20119 * @param menuInfo Extra information about the item for which the 20120 * context menu should be shown. This information will vary 20121 * depending on the class of v. 20122 */ 20123 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 20124 } 20125 20126 /** 20127 * Interface definition for a callback to be invoked when the status bar changes 20128 * visibility. This reports <strong>global</strong> changes to the system UI 20129 * state, not what the application is requesting. 20130 * 20131 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 20132 */ 20133 public interface OnSystemUiVisibilityChangeListener { 20134 /** 20135 * Called when the status bar changes visibility because of a call to 20136 * {@link View#setSystemUiVisibility(int)}. 20137 * 20138 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 20139 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}. 20140 * This tells you the <strong>global</strong> state of these UI visibility 20141 * flags, not what your app is currently applying. 20142 */ 20143 public void onSystemUiVisibilityChange(int visibility); 20144 } 20145 20146 /** 20147 * Interface definition for a callback to be invoked when this view is attached 20148 * or detached from its window. 20149 */ 20150 public interface OnAttachStateChangeListener { 20151 /** 20152 * Called when the view is attached to a window. 20153 * @param v The view that was attached 20154 */ 20155 public void onViewAttachedToWindow(View v); 20156 /** 20157 * Called when the view is detached from a window. 20158 * @param v The view that was detached 20159 */ 20160 public void onViewDetachedFromWindow(View v); 20161 } 20162 20163 /** 20164 * Listener for applying window insets on a view in a custom way. 20165 * 20166 * <p>Apps may choose to implement this interface if they want to apply custom policy 20167 * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener 20168 * is set, its 20169 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 20170 * method will be called instead of the View's own 20171 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener 20172 * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply 20173 * the View's normal behavior as part of its own.</p> 20174 */ 20175 public interface OnApplyWindowInsetsListener { 20176 /** 20177 * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set} 20178 * on a View, this listener method will be called instead of the view's own 20179 * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 20180 * 20181 * @param v The view applying window insets 20182 * @param insets The insets to apply 20183 * @return The insets supplied, minus any insets that were consumed 20184 */ 20185 public WindowInsets onApplyWindowInsets(View v, WindowInsets insets); 20186 } 20187 20188 private final class UnsetPressedState implements Runnable { 20189 @Override 20190 public void run() { 20191 setPressed(false); 20192 } 20193 } 20194 20195 /** 20196 * Base class for derived classes that want to save and restore their own 20197 * state in {@link android.view.View#onSaveInstanceState()}. 20198 */ 20199 public static class BaseSavedState extends AbsSavedState { 20200 /** 20201 * Constructor used when reading from a parcel. Reads the state of the superclass. 20202 * 20203 * @param source 20204 */ 20205 public BaseSavedState(Parcel source) { 20206 super(source); 20207 } 20208 20209 /** 20210 * Constructor called by derived classes when creating their SavedState objects 20211 * 20212 * @param superState The state of the superclass of this view 20213 */ 20214 public BaseSavedState(Parcelable superState) { 20215 super(superState); 20216 } 20217 20218 public static final Parcelable.Creator<BaseSavedState> CREATOR = 20219 new Parcelable.Creator<BaseSavedState>() { 20220 public BaseSavedState createFromParcel(Parcel in) { 20221 return new BaseSavedState(in); 20222 } 20223 20224 public BaseSavedState[] newArray(int size) { 20225 return new BaseSavedState[size]; 20226 } 20227 }; 20228 } 20229 20230 /** 20231 * A set of information given to a view when it is attached to its parent 20232 * window. 20233 */ 20234 final static class AttachInfo { 20235 interface Callbacks { 20236 void playSoundEffect(int effectId); 20237 boolean performHapticFeedback(int effectId, boolean always); 20238 } 20239 20240 /** 20241 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 20242 * to a Handler. This class contains the target (View) to invalidate and 20243 * the coordinates of the dirty rectangle. 20244 * 20245 * For performance purposes, this class also implements a pool of up to 20246 * POOL_LIMIT objects that get reused. This reduces memory allocations 20247 * whenever possible. 20248 */ 20249 static class InvalidateInfo { 20250 private static final int POOL_LIMIT = 10; 20251 20252 private static final SynchronizedPool<InvalidateInfo> sPool = 20253 new SynchronizedPool<InvalidateInfo>(POOL_LIMIT); 20254 20255 View target; 20256 20257 int left; 20258 int top; 20259 int right; 20260 int bottom; 20261 20262 public static InvalidateInfo obtain() { 20263 InvalidateInfo instance = sPool.acquire(); 20264 return (instance != null) ? instance : new InvalidateInfo(); 20265 } 20266 20267 public void recycle() { 20268 target = null; 20269 sPool.release(this); 20270 } 20271 } 20272 20273 final IWindowSession mSession; 20274 20275 final IWindow mWindow; 20276 20277 final IBinder mWindowToken; 20278 20279 final Display mDisplay; 20280 20281 final Callbacks mRootCallbacks; 20282 20283 IWindowId mIWindowId; 20284 WindowId mWindowId; 20285 20286 /** 20287 * The top view of the hierarchy. 20288 */ 20289 View mRootView; 20290 20291 IBinder mPanelParentWindowToken; 20292 20293 boolean mHardwareAccelerated; 20294 boolean mHardwareAccelerationRequested; 20295 HardwareRenderer mHardwareRenderer; 20296 List<RenderNode> mPendingAnimatingRenderNodes; 20297 20298 /** 20299 * The state of the display to which the window is attached, as reported 20300 * by {@link Display#getState()}. Note that the display state constants 20301 * declared by {@link Display} do not exactly line up with the screen state 20302 * constants declared by {@link View} (there are more display states than 20303 * screen states). 20304 */ 20305 int mDisplayState = Display.STATE_UNKNOWN; 20306 20307 /** 20308 * Scale factor used by the compatibility mode 20309 */ 20310 float mApplicationScale; 20311 20312 /** 20313 * Indicates whether the application is in compatibility mode 20314 */ 20315 boolean mScalingRequired; 20316 20317 /** 20318 * If set, ViewRootImpl doesn't use its lame animation for when the window resizes. 20319 */ 20320 boolean mTurnOffWindowResizeAnim; 20321 20322 /** 20323 * Left position of this view's window 20324 */ 20325 int mWindowLeft; 20326 20327 /** 20328 * Top position of this view's window 20329 */ 20330 int mWindowTop; 20331 20332 /** 20333 * Indicates whether views need to use 32-bit drawing caches 20334 */ 20335 boolean mUse32BitDrawingCache; 20336 20337 /** 20338 * For windows that are full-screen but using insets to layout inside 20339 * of the screen areas, these are the current insets to appear inside 20340 * the overscan area of the display. 20341 */ 20342 final Rect mOverscanInsets = new Rect(); 20343 20344 /** 20345 * For windows that are full-screen but using insets to layout inside 20346 * of the screen decorations, these are the current insets for the 20347 * content of the window. 20348 */ 20349 final Rect mContentInsets = new Rect(); 20350 20351 /** 20352 * For windows that are full-screen but using insets to layout inside 20353 * of the screen decorations, these are the current insets for the 20354 * actual visible parts of the window. 20355 */ 20356 final Rect mVisibleInsets = new Rect(); 20357 20358 /** 20359 * For windows that are full-screen but using insets to layout inside 20360 * of the screen decorations, these are the current insets for the 20361 * stable system windows. 20362 */ 20363 final Rect mStableInsets = new Rect(); 20364 20365 /** 20366 * The internal insets given by this window. This value is 20367 * supplied by the client (through 20368 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 20369 * be given to the window manager when changed to be used in laying 20370 * out windows behind it. 20371 */ 20372 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 20373 = new ViewTreeObserver.InternalInsetsInfo(); 20374 20375 /** 20376 * Set to true when mGivenInternalInsets is non-empty. 20377 */ 20378 boolean mHasNonEmptyGivenInternalInsets; 20379 20380 /** 20381 * All views in the window's hierarchy that serve as scroll containers, 20382 * used to determine if the window can be resized or must be panned 20383 * to adjust for a soft input area. 20384 */ 20385 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 20386 20387 final KeyEvent.DispatcherState mKeyDispatchState 20388 = new KeyEvent.DispatcherState(); 20389 20390 /** 20391 * Indicates whether the view's window currently has the focus. 20392 */ 20393 boolean mHasWindowFocus; 20394 20395 /** 20396 * The current visibility of the window. 20397 */ 20398 int mWindowVisibility; 20399 20400 /** 20401 * Indicates the time at which drawing started to occur. 20402 */ 20403 long mDrawingTime; 20404 20405 /** 20406 * Indicates whether or not ignoring the DIRTY_MASK flags. 20407 */ 20408 boolean mIgnoreDirtyState; 20409 20410 /** 20411 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 20412 * to avoid clearing that flag prematurely. 20413 */ 20414 boolean mSetIgnoreDirtyState = false; 20415 20416 /** 20417 * Indicates whether the view's window is currently in touch mode. 20418 */ 20419 boolean mInTouchMode; 20420 20421 /** 20422 * Indicates whether the view has requested unbuffered input dispatching for the current 20423 * event stream. 20424 */ 20425 boolean mUnbufferedDispatchRequested; 20426 20427 /** 20428 * Indicates that ViewAncestor should trigger a global layout change 20429 * the next time it performs a traversal 20430 */ 20431 boolean mRecomputeGlobalAttributes; 20432 20433 /** 20434 * Always report new attributes at next traversal. 20435 */ 20436 boolean mForceReportNewAttributes; 20437 20438 /** 20439 * Set during a traveral if any views want to keep the screen on. 20440 */ 20441 boolean mKeepScreenOn; 20442 20443 /** 20444 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 20445 */ 20446 int mSystemUiVisibility; 20447 20448 /** 20449 * Hack to force certain system UI visibility flags to be cleared. 20450 */ 20451 int mDisabledSystemUiVisibility; 20452 20453 /** 20454 * Last global system UI visibility reported by the window manager. 20455 */ 20456 int mGlobalSystemUiVisibility; 20457 20458 /** 20459 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 20460 * attached. 20461 */ 20462 boolean mHasSystemUiListeners; 20463 20464 /** 20465 * Set if the window has requested to extend into the overscan region 20466 * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN. 20467 */ 20468 boolean mOverscanRequested; 20469 20470 /** 20471 * Set if the visibility of any views has changed. 20472 */ 20473 boolean mViewVisibilityChanged; 20474 20475 /** 20476 * Set to true if a view has been scrolled. 20477 */ 20478 boolean mViewScrollChanged; 20479 20480 /** 20481 * Set to true if high contrast mode enabled 20482 */ 20483 boolean mHighContrastText; 20484 20485 /** 20486 * Global to the view hierarchy used as a temporary for dealing with 20487 * x/y points in the transparent region computations. 20488 */ 20489 final int[] mTransparentLocation = new int[2]; 20490 20491 /** 20492 * Global to the view hierarchy used as a temporary for dealing with 20493 * x/y points in the ViewGroup.invalidateChild implementation. 20494 */ 20495 final int[] mInvalidateChildLocation = new int[2]; 20496 20497 /** 20498 * Global to the view hierarchy used as a temporary for dealng with 20499 * computing absolute on-screen location. 20500 */ 20501 final int[] mTmpLocation = new int[2]; 20502 20503 /** 20504 * Global to the view hierarchy used as a temporary for dealing with 20505 * x/y location when view is transformed. 20506 */ 20507 final float[] mTmpTransformLocation = new float[2]; 20508 20509 /** 20510 * The view tree observer used to dispatch global events like 20511 * layout, pre-draw, touch mode change, etc. 20512 */ 20513 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 20514 20515 /** 20516 * A Canvas used by the view hierarchy to perform bitmap caching. 20517 */ 20518 Canvas mCanvas; 20519 20520 /** 20521 * The view root impl. 20522 */ 20523 final ViewRootImpl mViewRootImpl; 20524 20525 /** 20526 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 20527 * handler can be used to pump events in the UI events queue. 20528 */ 20529 final Handler mHandler; 20530 20531 /** 20532 * Temporary for use in computing invalidate rectangles while 20533 * calling up the hierarchy. 20534 */ 20535 final Rect mTmpInvalRect = new Rect(); 20536 20537 /** 20538 * Temporary for use in computing hit areas with transformed views 20539 */ 20540 final RectF mTmpTransformRect = new RectF(); 20541 20542 /** 20543 * Temporary for use in computing hit areas with transformed views 20544 */ 20545 final RectF mTmpTransformRect1 = new RectF(); 20546 20547 /** 20548 * Temporary list of rectanges. 20549 */ 20550 final List<RectF> mTmpRectList = new ArrayList<>(); 20551 20552 /** 20553 * Temporary for use in transforming invalidation rect 20554 */ 20555 final Matrix mTmpMatrix = new Matrix(); 20556 20557 /** 20558 * Temporary for use in transforming invalidation rect 20559 */ 20560 final Transformation mTmpTransformation = new Transformation(); 20561 20562 /** 20563 * Temporary for use in querying outlines from OutlineProviders 20564 */ 20565 final Outline mTmpOutline = new Outline(); 20566 20567 /** 20568 * Temporary list for use in collecting focusable descendents of a view. 20569 */ 20570 final ArrayList<View> mTempArrayList = new ArrayList<View>(24); 20571 20572 /** 20573 * The id of the window for accessibility purposes. 20574 */ 20575 int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 20576 20577 /** 20578 * Flags related to accessibility processing. 20579 * 20580 * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS 20581 * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS 20582 */ 20583 int mAccessibilityFetchFlags; 20584 20585 /** 20586 * The drawable for highlighting accessibility focus. 20587 */ 20588 Drawable mAccessibilityFocusDrawable; 20589 20590 /** 20591 * Show where the margins, bounds and layout bounds are for each view. 20592 */ 20593 boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false); 20594 20595 /** 20596 * Point used to compute visible regions. 20597 */ 20598 final Point mPoint = new Point(); 20599 20600 /** 20601 * Used to track which View originated a requestLayout() call, used when 20602 * requestLayout() is called during layout. 20603 */ 20604 View mViewRequestingLayout; 20605 20606 /** 20607 * Creates a new set of attachment information with the specified 20608 * events handler and thread. 20609 * 20610 * @param handler the events handler the view must use 20611 */ 20612 AttachInfo(IWindowSession session, IWindow window, Display display, 20613 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) { 20614 mSession = session; 20615 mWindow = window; 20616 mWindowToken = window.asBinder(); 20617 mDisplay = display; 20618 mViewRootImpl = viewRootImpl; 20619 mHandler = handler; 20620 mRootCallbacks = effectPlayer; 20621 } 20622 } 20623 20624 /** 20625 * <p>ScrollabilityCache holds various fields used by a View when scrolling 20626 * is supported. This avoids keeping too many unused fields in most 20627 * instances of View.</p> 20628 */ 20629 private static class ScrollabilityCache implements Runnable { 20630 20631 /** 20632 * Scrollbars are not visible 20633 */ 20634 public static final int OFF = 0; 20635 20636 /** 20637 * Scrollbars are visible 20638 */ 20639 public static final int ON = 1; 20640 20641 /** 20642 * Scrollbars are fading away 20643 */ 20644 public static final int FADING = 2; 20645 20646 public boolean fadeScrollBars; 20647 20648 public int fadingEdgeLength; 20649 public int scrollBarDefaultDelayBeforeFade; 20650 public int scrollBarFadeDuration; 20651 20652 public int scrollBarSize; 20653 public ScrollBarDrawable scrollBar; 20654 public float[] interpolatorValues; 20655 public View host; 20656 20657 public final Paint paint; 20658 public final Matrix matrix; 20659 public Shader shader; 20660 20661 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 20662 20663 private static final float[] OPAQUE = { 255 }; 20664 private static final float[] TRANSPARENT = { 0.0f }; 20665 20666 /** 20667 * When fading should start. This time moves into the future every time 20668 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 20669 */ 20670 public long fadeStartTime; 20671 20672 20673 /** 20674 * The current state of the scrollbars: ON, OFF, or FADING 20675 */ 20676 public int state = OFF; 20677 20678 private int mLastColor; 20679 20680 public ScrollabilityCache(ViewConfiguration configuration, View host) { 20681 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 20682 scrollBarSize = configuration.getScaledScrollBarSize(); 20683 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 20684 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 20685 20686 paint = new Paint(); 20687 matrix = new Matrix(); 20688 // use use a height of 1, and then wack the matrix each time we 20689 // actually use it. 20690 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 20691 paint.setShader(shader); 20692 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 20693 20694 this.host = host; 20695 } 20696 20697 public void setFadeColor(int color) { 20698 if (color != mLastColor) { 20699 mLastColor = color; 20700 20701 if (color != 0) { 20702 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 20703 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 20704 paint.setShader(shader); 20705 // Restore the default transfer mode (src_over) 20706 paint.setXfermode(null); 20707 } else { 20708 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 20709 paint.setShader(shader); 20710 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 20711 } 20712 } 20713 } 20714 20715 public void run() { 20716 long now = AnimationUtils.currentAnimationTimeMillis(); 20717 if (now >= fadeStartTime) { 20718 20719 // the animation fades the scrollbars out by changing 20720 // the opacity (alpha) from fully opaque to fully 20721 // transparent 20722 int nextFrame = (int) now; 20723 int framesCount = 0; 20724 20725 Interpolator interpolator = scrollBarInterpolator; 20726 20727 // Start opaque 20728 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 20729 20730 // End transparent 20731 nextFrame += scrollBarFadeDuration; 20732 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 20733 20734 state = FADING; 20735 20736 // Kick off the fade animation 20737 host.invalidate(true); 20738 } 20739 } 20740 } 20741 20742 /** 20743 * Resuable callback for sending 20744 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 20745 */ 20746 private class SendViewScrolledAccessibilityEvent implements Runnable { 20747 public volatile boolean mIsPending; 20748 20749 public void run() { 20750 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 20751 mIsPending = false; 20752 } 20753 } 20754 20755 /** 20756 * <p> 20757 * This class represents a delegate that can be registered in a {@link View} 20758 * to enhance accessibility support via composition rather via inheritance. 20759 * It is specifically targeted to widget developers that extend basic View 20760 * classes i.e. classes in package android.view, that would like their 20761 * applications to be backwards compatible. 20762 * </p> 20763 * <div class="special reference"> 20764 * <h3>Developer Guides</h3> 20765 * <p>For more information about making applications accessible, read the 20766 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a> 20767 * developer guide.</p> 20768 * </div> 20769 * <p> 20770 * A scenario in which a developer would like to use an accessibility delegate 20771 * is overriding a method introduced in a later API version then the minimal API 20772 * version supported by the application. For example, the method 20773 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 20774 * in API version 4 when the accessibility APIs were first introduced. If a 20775 * developer would like his application to run on API version 4 devices (assuming 20776 * all other APIs used by the application are version 4 or lower) and take advantage 20777 * of this method, instead of overriding the method which would break the application's 20778 * backwards compatibility, he can override the corresponding method in this 20779 * delegate and register the delegate in the target View if the API version of 20780 * the system is high enough i.e. the API version is same or higher to the API 20781 * version that introduced 20782 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 20783 * </p> 20784 * <p> 20785 * Here is an example implementation: 20786 * </p> 20787 * <code><pre><p> 20788 * if (Build.VERSION.SDK_INT >= 14) { 20789 * // If the API version is equal of higher than the version in 20790 * // which onInitializeAccessibilityNodeInfo was introduced we 20791 * // register a delegate with a customized implementation. 20792 * View view = findViewById(R.id.view_id); 20793 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 20794 * public void onInitializeAccessibilityNodeInfo(View host, 20795 * AccessibilityNodeInfo info) { 20796 * // Let the default implementation populate the info. 20797 * super.onInitializeAccessibilityNodeInfo(host, info); 20798 * // Set some other information. 20799 * info.setEnabled(host.isEnabled()); 20800 * } 20801 * }); 20802 * } 20803 * </code></pre></p> 20804 * <p> 20805 * This delegate contains methods that correspond to the accessibility methods 20806 * in View. If a delegate has been specified the implementation in View hands 20807 * off handling to the corresponding method in this delegate. The default 20808 * implementation the delegate methods behaves exactly as the corresponding 20809 * method in View for the case of no accessibility delegate been set. Hence, 20810 * to customize the behavior of a View method, clients can override only the 20811 * corresponding delegate method without altering the behavior of the rest 20812 * accessibility related methods of the host view. 20813 * </p> 20814 */ 20815 public static class AccessibilityDelegate { 20816 20817 /** 20818 * Sends an accessibility event of the given type. If accessibility is not 20819 * enabled this method has no effect. 20820 * <p> 20821 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 20822 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 20823 * been set. 20824 * </p> 20825 * 20826 * @param host The View hosting the delegate. 20827 * @param eventType The type of the event to send. 20828 * 20829 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 20830 */ 20831 public void sendAccessibilityEvent(View host, int eventType) { 20832 host.sendAccessibilityEventInternal(eventType); 20833 } 20834 20835 /** 20836 * Performs the specified accessibility action on the view. For 20837 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 20838 * <p> 20839 * The default implementation behaves as 20840 * {@link View#performAccessibilityAction(int, Bundle) 20841 * View#performAccessibilityAction(int, Bundle)} for the case of 20842 * no accessibility delegate been set. 20843 * </p> 20844 * 20845 * @param action The action to perform. 20846 * @return Whether the action was performed. 20847 * 20848 * @see View#performAccessibilityAction(int, Bundle) 20849 * View#performAccessibilityAction(int, Bundle) 20850 */ 20851 public boolean performAccessibilityAction(View host, int action, Bundle args) { 20852 return host.performAccessibilityActionInternal(action, args); 20853 } 20854 20855 /** 20856 * Sends an accessibility event. This method behaves exactly as 20857 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 20858 * empty {@link AccessibilityEvent} and does not perform a check whether 20859 * accessibility is enabled. 20860 * <p> 20861 * The default implementation behaves as 20862 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20863 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 20864 * the case of no accessibility delegate been set. 20865 * </p> 20866 * 20867 * @param host The View hosting the delegate. 20868 * @param event The event to send. 20869 * 20870 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20871 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20872 */ 20873 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 20874 host.sendAccessibilityEventUncheckedInternal(event); 20875 } 20876 20877 /** 20878 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 20879 * to its children for adding their text content to the event. 20880 * <p> 20881 * The default implementation behaves as 20882 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20883 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 20884 * the case of no accessibility delegate been set. 20885 * </p> 20886 * 20887 * @param host The View hosting the delegate. 20888 * @param event The event. 20889 * @return True if the event population was completed. 20890 * 20891 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20892 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20893 */ 20894 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 20895 return host.dispatchPopulateAccessibilityEventInternal(event); 20896 } 20897 20898 /** 20899 * Gives a chance to the host View to populate the accessibility event with its 20900 * text content. 20901 * <p> 20902 * The default implementation behaves as 20903 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 20904 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 20905 * the case of no accessibility delegate been set. 20906 * </p> 20907 * 20908 * @param host The View hosting the delegate. 20909 * @param event The accessibility event which to populate. 20910 * 20911 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 20912 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 20913 */ 20914 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 20915 host.onPopulateAccessibilityEventInternal(event); 20916 } 20917 20918 /** 20919 * Initializes an {@link AccessibilityEvent} with information about the 20920 * the host View which is the event source. 20921 * <p> 20922 * The default implementation behaves as 20923 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 20924 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 20925 * the case of no accessibility delegate been set. 20926 * </p> 20927 * 20928 * @param host The View hosting the delegate. 20929 * @param event The event to initialize. 20930 * 20931 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 20932 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 20933 */ 20934 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 20935 host.onInitializeAccessibilityEventInternal(event); 20936 } 20937 20938 /** 20939 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 20940 * <p> 20941 * The default implementation behaves as 20942 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20943 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 20944 * the case of no accessibility delegate been set. 20945 * </p> 20946 * 20947 * @param host The View hosting the delegate. 20948 * @param info The instance to initialize. 20949 * 20950 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20951 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20952 */ 20953 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 20954 host.onInitializeAccessibilityNodeInfoInternal(info); 20955 } 20956 20957 /** 20958 * Called when a child of the host View has requested sending an 20959 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 20960 * to augment the event. 20961 * <p> 20962 * The default implementation behaves as 20963 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20964 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 20965 * the case of no accessibility delegate been set. 20966 * </p> 20967 * 20968 * @param host The View hosting the delegate. 20969 * @param child The child which requests sending the event. 20970 * @param event The event to be sent. 20971 * @return True if the event should be sent 20972 * 20973 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20974 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20975 */ 20976 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 20977 AccessibilityEvent event) { 20978 return host.onRequestSendAccessibilityEventInternal(child, event); 20979 } 20980 20981 /** 20982 * Gets the provider for managing a virtual view hierarchy rooted at this View 20983 * and reported to {@link android.accessibilityservice.AccessibilityService}s 20984 * that explore the window content. 20985 * <p> 20986 * The default implementation behaves as 20987 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 20988 * the case of no accessibility delegate been set. 20989 * </p> 20990 * 20991 * @return The provider. 20992 * 20993 * @see AccessibilityNodeProvider 20994 */ 20995 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 20996 return null; 20997 } 20998 20999 /** 21000 * Returns an {@link AccessibilityNodeInfo} representing the host view from the 21001 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 21002 * This method is responsible for obtaining an accessibility node info from a 21003 * pool of reusable instances and calling 21004 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host 21005 * view to initialize the former. 21006 * <p> 21007 * <strong>Note:</strong> The client is responsible for recycling the obtained 21008 * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object 21009 * creation. 21010 * </p> 21011 * <p> 21012 * The default implementation behaves as 21013 * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for 21014 * the case of no accessibility delegate been set. 21015 * </p> 21016 * @return A populated {@link AccessibilityNodeInfo}. 21017 * 21018 * @see AccessibilityNodeInfo 21019 * 21020 * @hide 21021 */ 21022 public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) { 21023 return host.createAccessibilityNodeInfoInternal(); 21024 } 21025 } 21026 21027 private class MatchIdPredicate implements Predicate<View> { 21028 public int mId; 21029 21030 @Override 21031 public boolean apply(View view) { 21032 return (view.mID == mId); 21033 } 21034 } 21035 21036 private class MatchLabelForPredicate implements Predicate<View> { 21037 private int mLabeledId; 21038 21039 @Override 21040 public boolean apply(View view) { 21041 return (view.mLabelForId == mLabeledId); 21042 } 21043 } 21044 21045 private class SendViewStateChangedAccessibilityEvent implements Runnable { 21046 private int mChangeTypes = 0; 21047 private boolean mPosted; 21048 private boolean mPostedWithDelay; 21049 private long mLastEventTimeMillis; 21050 21051 @Override 21052 public void run() { 21053 mPosted = false; 21054 mPostedWithDelay = false; 21055 mLastEventTimeMillis = SystemClock.uptimeMillis(); 21056 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 21057 final AccessibilityEvent event = AccessibilityEvent.obtain(); 21058 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 21059 event.setContentChangeTypes(mChangeTypes); 21060 sendAccessibilityEventUnchecked(event); 21061 } 21062 mChangeTypes = 0; 21063 } 21064 21065 public void runOrPost(int changeType) { 21066 mChangeTypes |= changeType; 21067 21068 // If this is a live region or the child of a live region, collect 21069 // all events from this frame and send them on the next frame. 21070 if (inLiveRegion()) { 21071 // If we're already posted with a delay, remove that. 21072 if (mPostedWithDelay) { 21073 removeCallbacks(this); 21074 mPostedWithDelay = false; 21075 } 21076 // Only post if we're not already posted. 21077 if (!mPosted) { 21078 post(this); 21079 mPosted = true; 21080 } 21081 return; 21082 } 21083 21084 if (mPosted) { 21085 return; 21086 } 21087 21088 final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis; 21089 final long minEventIntevalMillis = 21090 ViewConfiguration.getSendRecurringAccessibilityEventsInterval(); 21091 if (timeSinceLastMillis >= minEventIntevalMillis) { 21092 removeCallbacks(this); 21093 run(); 21094 } else { 21095 postDelayed(this, minEventIntevalMillis - timeSinceLastMillis); 21096 mPostedWithDelay = true; 21097 } 21098 } 21099 } 21100 21101 private boolean inLiveRegion() { 21102 if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) { 21103 return true; 21104 } 21105 21106 ViewParent parent = getParent(); 21107 while (parent instanceof View) { 21108 if (((View) parent).getAccessibilityLiveRegion() 21109 != View.ACCESSIBILITY_LIVE_REGION_NONE) { 21110 return true; 21111 } 21112 parent = parent.getParent(); 21113 } 21114 21115 return false; 21116 } 21117 21118 /** 21119 * Dump all private flags in readable format, useful for documentation and 21120 * sanity checking. 21121 */ 21122 private static void dumpFlags() { 21123 final HashMap<String, String> found = Maps.newHashMap(); 21124 try { 21125 for (Field field : View.class.getDeclaredFields()) { 21126 final int modifiers = field.getModifiers(); 21127 if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { 21128 if (field.getType().equals(int.class)) { 21129 final int value = field.getInt(null); 21130 dumpFlag(found, field.getName(), value); 21131 } else if (field.getType().equals(int[].class)) { 21132 final int[] values = (int[]) field.get(null); 21133 for (int i = 0; i < values.length; i++) { 21134 dumpFlag(found, field.getName() + "[" + i + "]", values[i]); 21135 } 21136 } 21137 } 21138 } 21139 } catch (IllegalAccessException e) { 21140 throw new RuntimeException(e); 21141 } 21142 21143 final ArrayList<String> keys = Lists.newArrayList(); 21144 keys.addAll(found.keySet()); 21145 Collections.sort(keys); 21146 for (String key : keys) { 21147 Log.d(VIEW_LOG_TAG, found.get(key)); 21148 } 21149 } 21150 21151 private static void dumpFlag(HashMap<String, String> found, String name, int value) { 21152 // Sort flags by prefix, then by bits, always keeping unique keys 21153 final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' '); 21154 final int prefix = name.indexOf('_'); 21155 final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name; 21156 final String output = bits + " " + name; 21157 found.put(key, output); 21158 } 21159} 21160