View.java revision 7068c39526459c18a020e29c1ebfa6aed54e2d0f
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.view; 18 19import android.animation.AnimatorInflater; 20import android.animation.RevealAnimator; 21import android.animation.StateListAnimator; 22import android.animation.ValueAnimator; 23import android.annotation.IntDef; 24import android.annotation.NonNull; 25import android.annotation.Nullable; 26import android.content.ClipData; 27import android.content.Context; 28import android.content.res.ColorStateList; 29import android.content.res.Configuration; 30import android.content.res.Resources; 31import android.content.res.TypedArray; 32import android.graphics.Bitmap; 33import android.graphics.Canvas; 34import android.graphics.Insets; 35import android.graphics.Interpolator; 36import android.graphics.LinearGradient; 37import android.graphics.Matrix; 38import android.graphics.Outline; 39import android.graphics.Paint; 40import android.graphics.PixelFormat; 41import android.graphics.Point; 42import android.graphics.PorterDuff; 43import android.graphics.PorterDuffXfermode; 44import android.graphics.Rect; 45import android.graphics.RectF; 46import android.graphics.Region; 47import android.graphics.Shader; 48import android.graphics.drawable.ColorDrawable; 49import android.graphics.drawable.Drawable; 50import android.hardware.display.DisplayManagerGlobal; 51import android.os.Bundle; 52import android.os.Handler; 53import android.os.IBinder; 54import android.os.Parcel; 55import android.os.Parcelable; 56import android.os.RemoteException; 57import android.os.SystemClock; 58import android.os.SystemProperties; 59import android.text.TextUtils; 60import android.util.AttributeSet; 61import android.util.FloatProperty; 62import android.util.LayoutDirection; 63import android.util.Log; 64import android.util.LongSparseLongArray; 65import android.util.Pools.SynchronizedPool; 66import android.util.Property; 67import android.util.SparseArray; 68import android.util.SuperNotCalledException; 69import android.util.TypedValue; 70import android.view.ContextMenu.ContextMenuInfo; 71import android.view.AccessibilityIterators.TextSegmentIterator; 72import android.view.AccessibilityIterators.CharacterTextSegmentIterator; 73import android.view.AccessibilityIterators.WordTextSegmentIterator; 74import android.view.AccessibilityIterators.ParagraphTextSegmentIterator; 75import android.view.accessibility.AccessibilityEvent; 76import android.view.accessibility.AccessibilityEventSource; 77import android.view.accessibility.AccessibilityManager; 78import android.view.accessibility.AccessibilityNodeInfo; 79import android.view.accessibility.AccessibilityNodeProvider; 80import android.view.animation.Animation; 81import android.view.animation.AnimationUtils; 82import android.view.animation.Transformation; 83import android.view.inputmethod.EditorInfo; 84import android.view.inputmethod.InputConnection; 85import android.view.inputmethod.InputMethodManager; 86import android.widget.ScrollBarDrawable; 87 88import static android.os.Build.VERSION_CODES.*; 89import static java.lang.Math.max; 90 91import com.android.internal.R; 92import com.android.internal.util.Predicate; 93import com.android.internal.view.menu.MenuBuilder; 94 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 rendering each view that 451 * intersects the invalid region. Because the tree is traversed in-order, 452 * this means that parents will draw before (i.e., behind) their children, with 453 * siblings drawn in the order they appear in the tree. 454 * If you set a background drawable for a View, then the View will draw it for you 455 * before calling back to its <code>onDraw()</code> method. 456 * </p> 457 * 458 * <p> 459 * Note that the framework will not draw views that are not in the invalid region. 460 * </p> 461 * 462 * <p> 463 * To force a view to draw, call {@link #invalidate()}. 464 * </p> 465 * 466 * <a name="EventHandlingThreading"></a> 467 * <h3>Event Handling and Threading</h3> 468 * <p> 469 * The basic cycle of a view is as follows: 470 * <ol> 471 * <li>An event comes in and is dispatched to the appropriate view. The view 472 * handles the event and notifies any listeners.</li> 473 * <li>If in the course of processing the event, the view's bounds may need 474 * to be changed, the view will call {@link #requestLayout()}.</li> 475 * <li>Similarly, if in the course of processing the event the view's appearance 476 * may need to be changed, the view will call {@link #invalidate()}.</li> 477 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 478 * the framework will take care of measuring, laying out, and drawing the tree 479 * as appropriate.</li> 480 * </ol> 481 * </p> 482 * 483 * <p><em>Note: The entire view tree is single threaded. You must always be on 484 * the UI thread when calling any method on any view.</em> 485 * If you are doing work on other threads and want to update the state of a view 486 * from that thread, you should use a {@link Handler}. 487 * </p> 488 * 489 * <a name="FocusHandling"></a> 490 * <h3>Focus Handling</h3> 491 * <p> 492 * The framework will handle routine focus movement in response to user input. 493 * This includes changing the focus as views are removed or hidden, or as new 494 * views become available. Views indicate their willingness to take focus 495 * through the {@link #isFocusable} method. To change whether a view can take 496 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 497 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 498 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 499 * </p> 500 * <p> 501 * Focus movement is based on an algorithm which finds the nearest neighbor in a 502 * given direction. In rare cases, the default algorithm may not match the 503 * intended behavior of the developer. In these situations, you can provide 504 * explicit overrides by using these XML attributes in the layout file: 505 * <pre> 506 * nextFocusDown 507 * nextFocusLeft 508 * nextFocusRight 509 * nextFocusUp 510 * </pre> 511 * </p> 512 * 513 * 514 * <p> 515 * To get a particular view to take focus, call {@link #requestFocus()}. 516 * </p> 517 * 518 * <a name="TouchMode"></a> 519 * <h3>Touch Mode</h3> 520 * <p> 521 * When a user is navigating a user interface via directional keys such as a D-pad, it is 522 * necessary to give focus to actionable items such as buttons so the user can see 523 * what will take input. If the device has touch capabilities, however, and the user 524 * begins interacting with the interface by touching it, it is no longer necessary to 525 * always highlight, or give focus to, a particular view. This motivates a mode 526 * for interaction named 'touch mode'. 527 * </p> 528 * <p> 529 * For a touch capable device, once the user touches the screen, the device 530 * will enter touch mode. From this point onward, only views for which 531 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 532 * Other views that are touchable, like buttons, will not take focus when touched; they will 533 * only fire the on click listeners. 534 * </p> 535 * <p> 536 * Any time a user hits a directional key, such as a D-pad direction, the view device will 537 * exit touch mode, and find a view to take focus, so that the user may resume interacting 538 * with the user interface without touching the screen again. 539 * </p> 540 * <p> 541 * The touch mode state is maintained across {@link android.app.Activity}s. Call 542 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 543 * </p> 544 * 545 * <a name="Scrolling"></a> 546 * <h3>Scrolling</h3> 547 * <p> 548 * The framework provides basic support for views that wish to internally 549 * scroll their content. This includes keeping track of the X and Y scroll 550 * offset as well as mechanisms for drawing scrollbars. See 551 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 552 * {@link #awakenScrollBars()} for more details. 553 * </p> 554 * 555 * <a name="Tags"></a> 556 * <h3>Tags</h3> 557 * <p> 558 * Unlike IDs, tags are not used to identify views. Tags are essentially an 559 * extra piece of information that can be associated with a view. They are most 560 * often used as a convenience to store data related to views in the views 561 * themselves rather than by putting them in a separate structure. 562 * </p> 563 * 564 * <a name="Properties"></a> 565 * <h3>Properties</h3> 566 * <p> 567 * The View class exposes an {@link #ALPHA} property, as well as several transform-related 568 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are 569 * available both in the {@link Property} form as well as in similarly-named setter/getter 570 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can 571 * be used to set persistent state associated with these rendering-related properties on the view. 572 * The properties and methods can also be used in conjunction with 573 * {@link android.animation.Animator Animator}-based animations, described more in the 574 * <a href="#Animation">Animation</a> section. 575 * </p> 576 * 577 * <a name="Animation"></a> 578 * <h3>Animation</h3> 579 * <p> 580 * Starting with Android 3.0, the preferred way of animating views is to use the 581 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based 582 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and 583 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0 584 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only 585 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class 586 * makes animating these View properties particularly easy and efficient. 587 * </p> 588 * <p> 589 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered. 590 * You can attach an {@link Animation} object to a view using 591 * {@link #setAnimation(Animation)} or 592 * {@link #startAnimation(Animation)}. The animation can alter the scale, 593 * rotation, translation and alpha of a view over time. If the animation is 594 * attached to a view that has children, the animation will affect the entire 595 * subtree rooted by that node. When an animation is started, the framework will 596 * take care of redrawing the appropriate views until the animation completes. 597 * </p> 598 * 599 * <a name="Security"></a> 600 * <h3>Security</h3> 601 * <p> 602 * Sometimes it is essential that an application be able to verify that an action 603 * is being performed with the full knowledge and consent of the user, such as 604 * granting a permission request, making a purchase or clicking on an advertisement. 605 * Unfortunately, a malicious application could try to spoof the user into 606 * performing these actions, unaware, by concealing the intended purpose of the view. 607 * As a remedy, the framework offers a touch filtering mechanism that can be used to 608 * improve the security of views that provide access to sensitive functionality. 609 * </p><p> 610 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 611 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 612 * will discard touches that are received whenever the view's window is obscured by 613 * another visible window. As a result, the view will not receive touches whenever a 614 * toast, dialog or other window appears above the view's window. 615 * </p><p> 616 * For more fine-grained control over security, consider overriding the 617 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 618 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 619 * </p> 620 * 621 * @attr ref android.R.styleable#View_alpha 622 * @attr ref android.R.styleable#View_background 623 * @attr ref android.R.styleable#View_clickable 624 * @attr ref android.R.styleable#View_contentDescription 625 * @attr ref android.R.styleable#View_drawingCacheQuality 626 * @attr ref android.R.styleable#View_duplicateParentState 627 * @attr ref android.R.styleable#View_id 628 * @attr ref android.R.styleable#View_requiresFadingEdge 629 * @attr ref android.R.styleable#View_fadeScrollbars 630 * @attr ref android.R.styleable#View_fadingEdgeLength 631 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 632 * @attr ref android.R.styleable#View_fitsSystemWindows 633 * @attr ref android.R.styleable#View_isScrollContainer 634 * @attr ref android.R.styleable#View_focusable 635 * @attr ref android.R.styleable#View_focusableInTouchMode 636 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 637 * @attr ref android.R.styleable#View_keepScreenOn 638 * @attr ref android.R.styleable#View_layerType 639 * @attr ref android.R.styleable#View_layoutDirection 640 * @attr ref android.R.styleable#View_longClickable 641 * @attr ref android.R.styleable#View_minHeight 642 * @attr ref android.R.styleable#View_minWidth 643 * @attr ref android.R.styleable#View_nextFocusDown 644 * @attr ref android.R.styleable#View_nextFocusLeft 645 * @attr ref android.R.styleable#View_nextFocusRight 646 * @attr ref android.R.styleable#View_nextFocusUp 647 * @attr ref android.R.styleable#View_onClick 648 * @attr ref android.R.styleable#View_padding 649 * @attr ref android.R.styleable#View_paddingBottom 650 * @attr ref android.R.styleable#View_paddingLeft 651 * @attr ref android.R.styleable#View_paddingRight 652 * @attr ref android.R.styleable#View_paddingTop 653 * @attr ref android.R.styleable#View_paddingStart 654 * @attr ref android.R.styleable#View_paddingEnd 655 * @attr ref android.R.styleable#View_saveEnabled 656 * @attr ref android.R.styleable#View_rotation 657 * @attr ref android.R.styleable#View_rotationX 658 * @attr ref android.R.styleable#View_rotationY 659 * @attr ref android.R.styleable#View_scaleX 660 * @attr ref android.R.styleable#View_scaleY 661 * @attr ref android.R.styleable#View_scrollX 662 * @attr ref android.R.styleable#View_scrollY 663 * @attr ref android.R.styleable#View_scrollbarSize 664 * @attr ref android.R.styleable#View_scrollbarStyle 665 * @attr ref android.R.styleable#View_scrollbars 666 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 667 * @attr ref android.R.styleable#View_scrollbarFadeDuration 668 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 669 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 670 * @attr ref android.R.styleable#View_scrollbarThumbVertical 671 * @attr ref android.R.styleable#View_scrollbarTrackVertical 672 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 673 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 674 * @attr ref android.R.styleable#View_stateListAnimator 675 * @attr ref android.R.styleable#View_transitionName 676 * @attr ref android.R.styleable#View_soundEffectsEnabled 677 * @attr ref android.R.styleable#View_tag 678 * @attr ref android.R.styleable#View_textAlignment 679 * @attr ref android.R.styleable#View_textDirection 680 * @attr ref android.R.styleable#View_transformPivotX 681 * @attr ref android.R.styleable#View_transformPivotY 682 * @attr ref android.R.styleable#View_translationX 683 * @attr ref android.R.styleable#View_translationY 684 * @attr ref android.R.styleable#View_translationZ 685 * @attr ref android.R.styleable#View_visibility 686 * 687 * @see android.view.ViewGroup 688 */ 689public class View implements Drawable.Callback, KeyEvent.Callback, 690 AccessibilityEventSource { 691 private static final boolean DBG = false; 692 693 /** 694 * The logging tag used by this class with android.util.Log. 695 */ 696 protected static final String VIEW_LOG_TAG = "View"; 697 698 /** 699 * When set to true, apps will draw debugging information about their layouts. 700 * 701 * @hide 702 */ 703 public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout"; 704 705 /** 706 * Used to mark a View that has no ID. 707 */ 708 public static final int NO_ID = -1; 709 710 /** 711 * Signals that compatibility booleans have been initialized according to 712 * target SDK versions. 713 */ 714 private static boolean sCompatibilityDone = false; 715 716 /** 717 * Use the old (broken) way of building MeasureSpecs. 718 */ 719 private static boolean sUseBrokenMakeMeasureSpec = false; 720 721 /** 722 * Ignore any optimizations using the measure cache. 723 */ 724 private static boolean sIgnoreMeasureCache = false; 725 726 /** 727 * Ignore the clipBounds of this view for the children. 728 */ 729 static boolean sIgnoreClipBoundsForChildren = false; 730 731 /** 732 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 733 * calling setFlags. 734 */ 735 private static final int NOT_FOCUSABLE = 0x00000000; 736 737 /** 738 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 739 * setFlags. 740 */ 741 private static final int FOCUSABLE = 0x00000001; 742 743 /** 744 * Mask for use with setFlags indicating bits used for focus. 745 */ 746 private static final int FOCUSABLE_MASK = 0x00000001; 747 748 /** 749 * This view will adjust its padding to fit sytem windows (e.g. status bar) 750 */ 751 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 752 753 /** @hide */ 754 @IntDef({VISIBLE, INVISIBLE, GONE}) 755 @Retention(RetentionPolicy.SOURCE) 756 public @interface Visibility {} 757 758 /** 759 * This view is visible. 760 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 761 * android:visibility}. 762 */ 763 public static final int VISIBLE = 0x00000000; 764 765 /** 766 * This view is invisible, but it still takes up space for layout purposes. 767 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 768 * android:visibility}. 769 */ 770 public static final int INVISIBLE = 0x00000004; 771 772 /** 773 * This view is invisible, and it doesn't take any space for layout 774 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 775 * android:visibility}. 776 */ 777 public static final int GONE = 0x00000008; 778 779 /** 780 * Mask for use with setFlags indicating bits used for visibility. 781 * {@hide} 782 */ 783 static final int VISIBILITY_MASK = 0x0000000C; 784 785 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 786 787 /** 788 * This view is enabled. Interpretation varies by subclass. 789 * Use with ENABLED_MASK when calling setFlags. 790 * {@hide} 791 */ 792 static final int ENABLED = 0x00000000; 793 794 /** 795 * This view is disabled. Interpretation varies by subclass. 796 * Use with ENABLED_MASK when calling setFlags. 797 * {@hide} 798 */ 799 static final int DISABLED = 0x00000020; 800 801 /** 802 * Mask for use with setFlags indicating bits used for indicating whether 803 * this view is enabled 804 * {@hide} 805 */ 806 static final int ENABLED_MASK = 0x00000020; 807 808 /** 809 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 810 * called and further optimizations will be performed. It is okay to have 811 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 812 * {@hide} 813 */ 814 static final int WILL_NOT_DRAW = 0x00000080; 815 816 /** 817 * Mask for use with setFlags indicating bits used for indicating whether 818 * this view is will draw 819 * {@hide} 820 */ 821 static final int DRAW_MASK = 0x00000080; 822 823 /** 824 * <p>This view doesn't show scrollbars.</p> 825 * {@hide} 826 */ 827 static final int SCROLLBARS_NONE = 0x00000000; 828 829 /** 830 * <p>This view shows horizontal scrollbars.</p> 831 * {@hide} 832 */ 833 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 834 835 /** 836 * <p>This view shows vertical scrollbars.</p> 837 * {@hide} 838 */ 839 static final int SCROLLBARS_VERTICAL = 0x00000200; 840 841 /** 842 * <p>Mask for use with setFlags indicating bits used for indicating which 843 * scrollbars are enabled.</p> 844 * {@hide} 845 */ 846 static final int SCROLLBARS_MASK = 0x00000300; 847 848 /** 849 * Indicates that the view should filter touches when its window is obscured. 850 * Refer to the class comments for more information about this security feature. 851 * {@hide} 852 */ 853 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 854 855 /** 856 * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate 857 * that they are optional and should be skipped if the window has 858 * requested system UI flags that ignore those insets for layout. 859 */ 860 static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800; 861 862 /** 863 * <p>This view doesn't show fading edges.</p> 864 * {@hide} 865 */ 866 static final int FADING_EDGE_NONE = 0x00000000; 867 868 /** 869 * <p>This view shows horizontal fading edges.</p> 870 * {@hide} 871 */ 872 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 873 874 /** 875 * <p>This view shows vertical fading edges.</p> 876 * {@hide} 877 */ 878 static final int FADING_EDGE_VERTICAL = 0x00002000; 879 880 /** 881 * <p>Mask for use with setFlags indicating bits used for indicating which 882 * fading edges are enabled.</p> 883 * {@hide} 884 */ 885 static final int FADING_EDGE_MASK = 0x00003000; 886 887 /** 888 * <p>Indicates this view can be clicked. When clickable, a View reacts 889 * to clicks by notifying the OnClickListener.<p> 890 * {@hide} 891 */ 892 static final int CLICKABLE = 0x00004000; 893 894 /** 895 * <p>Indicates this view is caching its drawing into a bitmap.</p> 896 * {@hide} 897 */ 898 static final int DRAWING_CACHE_ENABLED = 0x00008000; 899 900 /** 901 * <p>Indicates that no icicle should be saved for this view.<p> 902 * {@hide} 903 */ 904 static final int SAVE_DISABLED = 0x000010000; 905 906 /** 907 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 908 * property.</p> 909 * {@hide} 910 */ 911 static final int SAVE_DISABLED_MASK = 0x000010000; 912 913 /** 914 * <p>Indicates that no drawing cache should ever be created for this view.<p> 915 * {@hide} 916 */ 917 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 918 919 /** 920 * <p>Indicates this view can take / keep focus when int touch mode.</p> 921 * {@hide} 922 */ 923 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 924 925 /** @hide */ 926 @Retention(RetentionPolicy.SOURCE) 927 @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO}) 928 public @interface DrawingCacheQuality {} 929 930 /** 931 * <p>Enables low quality mode for the drawing cache.</p> 932 */ 933 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 934 935 /** 936 * <p>Enables high quality mode for the drawing cache.</p> 937 */ 938 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 939 940 /** 941 * <p>Enables automatic quality mode for the drawing cache.</p> 942 */ 943 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 944 945 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 946 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 947 }; 948 949 /** 950 * <p>Mask for use with setFlags indicating bits used for the cache 951 * quality property.</p> 952 * {@hide} 953 */ 954 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 955 956 /** 957 * <p> 958 * Indicates this view can be long clicked. When long clickable, a View 959 * reacts to long clicks by notifying the OnLongClickListener or showing a 960 * context menu. 961 * </p> 962 * {@hide} 963 */ 964 static final int LONG_CLICKABLE = 0x00200000; 965 966 /** 967 * <p>Indicates that this view gets its drawable states from its direct parent 968 * and ignores its original internal states.</p> 969 * 970 * @hide 971 */ 972 static final int DUPLICATE_PARENT_STATE = 0x00400000; 973 974 /** @hide */ 975 @IntDef({ 976 SCROLLBARS_INSIDE_OVERLAY, 977 SCROLLBARS_INSIDE_INSET, 978 SCROLLBARS_OUTSIDE_OVERLAY, 979 SCROLLBARS_OUTSIDE_INSET 980 }) 981 @Retention(RetentionPolicy.SOURCE) 982 public @interface ScrollBarStyle {} 983 984 /** 985 * The scrollbar style to display the scrollbars inside the content area, 986 * without increasing the padding. The scrollbars will be overlaid with 987 * translucency on the view's content. 988 */ 989 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 990 991 /** 992 * The scrollbar style to display the scrollbars inside the padded area, 993 * increasing the padding of the view. The scrollbars will not overlap the 994 * content area of the view. 995 */ 996 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 997 998 /** 999 * The scrollbar style to display the scrollbars at the edge of the view, 1000 * without increasing the padding. The scrollbars will be overlaid with 1001 * translucency. 1002 */ 1003 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 1004 1005 /** 1006 * The scrollbar style to display the scrollbars at the edge of the view, 1007 * increasing the padding of the view. The scrollbars will only overlap the 1008 * background, if any. 1009 */ 1010 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 1011 1012 /** 1013 * Mask to check if the scrollbar style is overlay or inset. 1014 * {@hide} 1015 */ 1016 static final int SCROLLBARS_INSET_MASK = 0x01000000; 1017 1018 /** 1019 * Mask to check if the scrollbar style is inside or outside. 1020 * {@hide} 1021 */ 1022 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 1023 1024 /** 1025 * Mask for scrollbar style. 1026 * {@hide} 1027 */ 1028 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 1029 1030 /** 1031 * View flag indicating that the screen should remain on while the 1032 * window containing this view is visible to the user. This effectively 1033 * takes care of automatically setting the WindowManager's 1034 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 1035 */ 1036 public static final int KEEP_SCREEN_ON = 0x04000000; 1037 1038 /** 1039 * View flag indicating whether this view should have sound effects enabled 1040 * for events such as clicking and touching. 1041 */ 1042 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 1043 1044 /** 1045 * View flag indicating whether this view should have haptic feedback 1046 * enabled for events such as long presses. 1047 */ 1048 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 1049 1050 /** 1051 * <p>Indicates that the view hierarchy should stop saving state when 1052 * it reaches this view. If state saving is initiated immediately at 1053 * the view, it will be allowed. 1054 * {@hide} 1055 */ 1056 static final int PARENT_SAVE_DISABLED = 0x20000000; 1057 1058 /** 1059 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 1060 * {@hide} 1061 */ 1062 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 1063 1064 /** @hide */ 1065 @IntDef(flag = true, 1066 value = { 1067 FOCUSABLES_ALL, 1068 FOCUSABLES_TOUCH_MODE 1069 }) 1070 @Retention(RetentionPolicy.SOURCE) 1071 public @interface FocusableMode {} 1072 1073 /** 1074 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1075 * should add all focusable Views regardless if they are focusable in touch mode. 1076 */ 1077 public static final int FOCUSABLES_ALL = 0x00000000; 1078 1079 /** 1080 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1081 * should add only Views focusable in touch mode. 1082 */ 1083 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 1084 1085 /** @hide */ 1086 @IntDef({ 1087 FOCUS_BACKWARD, 1088 FOCUS_FORWARD, 1089 FOCUS_LEFT, 1090 FOCUS_UP, 1091 FOCUS_RIGHT, 1092 FOCUS_DOWN 1093 }) 1094 @Retention(RetentionPolicy.SOURCE) 1095 public @interface FocusDirection {} 1096 1097 /** @hide */ 1098 @IntDef({ 1099 FOCUS_LEFT, 1100 FOCUS_UP, 1101 FOCUS_RIGHT, 1102 FOCUS_DOWN 1103 }) 1104 @Retention(RetentionPolicy.SOURCE) 1105 public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward 1106 1107 /** 1108 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 1109 * item. 1110 */ 1111 public static final int FOCUS_BACKWARD = 0x00000001; 1112 1113 /** 1114 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 1115 * item. 1116 */ 1117 public static final int FOCUS_FORWARD = 0x00000002; 1118 1119 /** 1120 * Use with {@link #focusSearch(int)}. Move focus to the left. 1121 */ 1122 public static final int FOCUS_LEFT = 0x00000011; 1123 1124 /** 1125 * Use with {@link #focusSearch(int)}. Move focus up. 1126 */ 1127 public static final int FOCUS_UP = 0x00000021; 1128 1129 /** 1130 * Use with {@link #focusSearch(int)}. Move focus to the right. 1131 */ 1132 public static final int FOCUS_RIGHT = 0x00000042; 1133 1134 /** 1135 * Use with {@link #focusSearch(int)}. Move focus down. 1136 */ 1137 public static final int FOCUS_DOWN = 0x00000082; 1138 1139 /** 1140 * Bits of {@link #getMeasuredWidthAndState()} and 1141 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1142 */ 1143 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1144 1145 /** 1146 * Bits of {@link #getMeasuredWidthAndState()} and 1147 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1148 */ 1149 public static final int MEASURED_STATE_MASK = 0xff000000; 1150 1151 /** 1152 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1153 * for functions that combine both width and height into a single int, 1154 * such as {@link #getMeasuredState()} and the childState argument of 1155 * {@link #resolveSizeAndState(int, int, int)}. 1156 */ 1157 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1158 1159 /** 1160 * Bit of {@link #getMeasuredWidthAndState()} and 1161 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1162 * is smaller that the space the view would like to have. 1163 */ 1164 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1165 1166 /** 1167 * Base View state sets 1168 */ 1169 // Singles 1170 /** 1171 * Indicates the view has no states set. States are used with 1172 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1173 * view depending on its state. 1174 * 1175 * @see android.graphics.drawable.Drawable 1176 * @see #getDrawableState() 1177 */ 1178 protected static final int[] EMPTY_STATE_SET; 1179 /** 1180 * Indicates the view is enabled. States are used with 1181 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1182 * view depending on its state. 1183 * 1184 * @see android.graphics.drawable.Drawable 1185 * @see #getDrawableState() 1186 */ 1187 protected static final int[] ENABLED_STATE_SET; 1188 /** 1189 * Indicates the view is focused. States are used with 1190 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1191 * view depending on its state. 1192 * 1193 * @see android.graphics.drawable.Drawable 1194 * @see #getDrawableState() 1195 */ 1196 protected static final int[] FOCUSED_STATE_SET; 1197 /** 1198 * Indicates the view is selected. States are used with 1199 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1200 * view depending on its state. 1201 * 1202 * @see android.graphics.drawable.Drawable 1203 * @see #getDrawableState() 1204 */ 1205 protected static final int[] SELECTED_STATE_SET; 1206 /** 1207 * Indicates the view is pressed. States are used with 1208 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1209 * view depending on its state. 1210 * 1211 * @see android.graphics.drawable.Drawable 1212 * @see #getDrawableState() 1213 */ 1214 protected static final int[] PRESSED_STATE_SET; 1215 /** 1216 * Indicates the view's window has focus. States are used with 1217 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1218 * view depending on its state. 1219 * 1220 * @see android.graphics.drawable.Drawable 1221 * @see #getDrawableState() 1222 */ 1223 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1224 // Doubles 1225 /** 1226 * Indicates the view is enabled and has the focus. 1227 * 1228 * @see #ENABLED_STATE_SET 1229 * @see #FOCUSED_STATE_SET 1230 */ 1231 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1232 /** 1233 * Indicates the view is enabled and selected. 1234 * 1235 * @see #ENABLED_STATE_SET 1236 * @see #SELECTED_STATE_SET 1237 */ 1238 protected static final int[] ENABLED_SELECTED_STATE_SET; 1239 /** 1240 * Indicates the view is enabled and that its window has focus. 1241 * 1242 * @see #ENABLED_STATE_SET 1243 * @see #WINDOW_FOCUSED_STATE_SET 1244 */ 1245 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1246 /** 1247 * Indicates the view is focused and selected. 1248 * 1249 * @see #FOCUSED_STATE_SET 1250 * @see #SELECTED_STATE_SET 1251 */ 1252 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1253 /** 1254 * Indicates the view has the focus and that its window has the focus. 1255 * 1256 * @see #FOCUSED_STATE_SET 1257 * @see #WINDOW_FOCUSED_STATE_SET 1258 */ 1259 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1260 /** 1261 * Indicates the view is selected and that its window has the focus. 1262 * 1263 * @see #SELECTED_STATE_SET 1264 * @see #WINDOW_FOCUSED_STATE_SET 1265 */ 1266 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1267 // Triples 1268 /** 1269 * Indicates the view is enabled, focused and selected. 1270 * 1271 * @see #ENABLED_STATE_SET 1272 * @see #FOCUSED_STATE_SET 1273 * @see #SELECTED_STATE_SET 1274 */ 1275 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1276 /** 1277 * Indicates the view is enabled, focused and its window has the focus. 1278 * 1279 * @see #ENABLED_STATE_SET 1280 * @see #FOCUSED_STATE_SET 1281 * @see #WINDOW_FOCUSED_STATE_SET 1282 */ 1283 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1284 /** 1285 * Indicates the view is enabled, selected and its window has the focus. 1286 * 1287 * @see #ENABLED_STATE_SET 1288 * @see #SELECTED_STATE_SET 1289 * @see #WINDOW_FOCUSED_STATE_SET 1290 */ 1291 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1292 /** 1293 * Indicates the view is focused, selected and its window has the focus. 1294 * 1295 * @see #FOCUSED_STATE_SET 1296 * @see #SELECTED_STATE_SET 1297 * @see #WINDOW_FOCUSED_STATE_SET 1298 */ 1299 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1300 /** 1301 * Indicates the view is enabled, focused, selected and its window 1302 * has the focus. 1303 * 1304 * @see #ENABLED_STATE_SET 1305 * @see #FOCUSED_STATE_SET 1306 * @see #SELECTED_STATE_SET 1307 * @see #WINDOW_FOCUSED_STATE_SET 1308 */ 1309 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1310 /** 1311 * Indicates the view is pressed and its window has the focus. 1312 * 1313 * @see #PRESSED_STATE_SET 1314 * @see #WINDOW_FOCUSED_STATE_SET 1315 */ 1316 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1317 /** 1318 * Indicates the view is pressed and selected. 1319 * 1320 * @see #PRESSED_STATE_SET 1321 * @see #SELECTED_STATE_SET 1322 */ 1323 protected static final int[] PRESSED_SELECTED_STATE_SET; 1324 /** 1325 * Indicates the view is pressed, selected and its window has the focus. 1326 * 1327 * @see #PRESSED_STATE_SET 1328 * @see #SELECTED_STATE_SET 1329 * @see #WINDOW_FOCUSED_STATE_SET 1330 */ 1331 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1332 /** 1333 * Indicates the view is pressed and focused. 1334 * 1335 * @see #PRESSED_STATE_SET 1336 * @see #FOCUSED_STATE_SET 1337 */ 1338 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1339 /** 1340 * Indicates the view is pressed, focused and its window has the focus. 1341 * 1342 * @see #PRESSED_STATE_SET 1343 * @see #FOCUSED_STATE_SET 1344 * @see #WINDOW_FOCUSED_STATE_SET 1345 */ 1346 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1347 /** 1348 * Indicates the view is pressed, focused and selected. 1349 * 1350 * @see #PRESSED_STATE_SET 1351 * @see #SELECTED_STATE_SET 1352 * @see #FOCUSED_STATE_SET 1353 */ 1354 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1355 /** 1356 * Indicates the view is pressed, focused, selected and its window has the focus. 1357 * 1358 * @see #PRESSED_STATE_SET 1359 * @see #FOCUSED_STATE_SET 1360 * @see #SELECTED_STATE_SET 1361 * @see #WINDOW_FOCUSED_STATE_SET 1362 */ 1363 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1364 /** 1365 * Indicates the view is pressed and enabled. 1366 * 1367 * @see #PRESSED_STATE_SET 1368 * @see #ENABLED_STATE_SET 1369 */ 1370 protected static final int[] PRESSED_ENABLED_STATE_SET; 1371 /** 1372 * Indicates the view is pressed, enabled and its window has the focus. 1373 * 1374 * @see #PRESSED_STATE_SET 1375 * @see #ENABLED_STATE_SET 1376 * @see #WINDOW_FOCUSED_STATE_SET 1377 */ 1378 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1379 /** 1380 * Indicates the view is pressed, enabled and selected. 1381 * 1382 * @see #PRESSED_STATE_SET 1383 * @see #ENABLED_STATE_SET 1384 * @see #SELECTED_STATE_SET 1385 */ 1386 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1387 /** 1388 * Indicates the view is pressed, enabled, selected and its window has the 1389 * focus. 1390 * 1391 * @see #PRESSED_STATE_SET 1392 * @see #ENABLED_STATE_SET 1393 * @see #SELECTED_STATE_SET 1394 * @see #WINDOW_FOCUSED_STATE_SET 1395 */ 1396 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1397 /** 1398 * Indicates the view is pressed, enabled and focused. 1399 * 1400 * @see #PRESSED_STATE_SET 1401 * @see #ENABLED_STATE_SET 1402 * @see #FOCUSED_STATE_SET 1403 */ 1404 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1405 /** 1406 * Indicates the view is pressed, enabled, focused and its window has the 1407 * focus. 1408 * 1409 * @see #PRESSED_STATE_SET 1410 * @see #ENABLED_STATE_SET 1411 * @see #FOCUSED_STATE_SET 1412 * @see #WINDOW_FOCUSED_STATE_SET 1413 */ 1414 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1415 /** 1416 * Indicates the view is pressed, enabled, focused and selected. 1417 * 1418 * @see #PRESSED_STATE_SET 1419 * @see #ENABLED_STATE_SET 1420 * @see #SELECTED_STATE_SET 1421 * @see #FOCUSED_STATE_SET 1422 */ 1423 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1424 /** 1425 * Indicates the view is pressed, enabled, focused, selected and its window 1426 * has the focus. 1427 * 1428 * @see #PRESSED_STATE_SET 1429 * @see #ENABLED_STATE_SET 1430 * @see #SELECTED_STATE_SET 1431 * @see #FOCUSED_STATE_SET 1432 * @see #WINDOW_FOCUSED_STATE_SET 1433 */ 1434 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1435 1436 /** 1437 * The order here is very important to {@link #getDrawableState()} 1438 */ 1439 private static final int[][] VIEW_STATE_SETS; 1440 1441 static final int VIEW_STATE_WINDOW_FOCUSED = 1; 1442 static final int VIEW_STATE_SELECTED = 1 << 1; 1443 static final int VIEW_STATE_FOCUSED = 1 << 2; 1444 static final int VIEW_STATE_ENABLED = 1 << 3; 1445 static final int VIEW_STATE_PRESSED = 1 << 4; 1446 static final int VIEW_STATE_ACTIVATED = 1 << 5; 1447 static final int VIEW_STATE_ACCELERATED = 1 << 6; 1448 static final int VIEW_STATE_HOVERED = 1 << 7; 1449 static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8; 1450 static final int VIEW_STATE_DRAG_HOVERED = 1 << 9; 1451 1452 static final int[] VIEW_STATE_IDS = new int[] { 1453 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED, 1454 R.attr.state_selected, VIEW_STATE_SELECTED, 1455 R.attr.state_focused, VIEW_STATE_FOCUSED, 1456 R.attr.state_enabled, VIEW_STATE_ENABLED, 1457 R.attr.state_pressed, VIEW_STATE_PRESSED, 1458 R.attr.state_activated, VIEW_STATE_ACTIVATED, 1459 R.attr.state_accelerated, VIEW_STATE_ACCELERATED, 1460 R.attr.state_hovered, VIEW_STATE_HOVERED, 1461 R.attr.state_drag_can_accept, VIEW_STATE_DRAG_CAN_ACCEPT, 1462 R.attr.state_drag_hovered, VIEW_STATE_DRAG_HOVERED 1463 }; 1464 1465 static { 1466 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) { 1467 throw new IllegalStateException( 1468 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array"); 1469 } 1470 int[] orderedIds = new int[VIEW_STATE_IDS.length]; 1471 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) { 1472 int viewState = R.styleable.ViewDrawableStates[i]; 1473 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) { 1474 if (VIEW_STATE_IDS[j] == viewState) { 1475 orderedIds[i * 2] = viewState; 1476 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1]; 1477 } 1478 } 1479 } 1480 final int NUM_BITS = VIEW_STATE_IDS.length / 2; 1481 VIEW_STATE_SETS = new int[1 << NUM_BITS][]; 1482 for (int i = 0; i < VIEW_STATE_SETS.length; i++) { 1483 int numBits = Integer.bitCount(i); 1484 int[] set = new int[numBits]; 1485 int pos = 0; 1486 for (int j = 0; j < orderedIds.length; j += 2) { 1487 if ((i & orderedIds[j+1]) != 0) { 1488 set[pos++] = orderedIds[j]; 1489 } 1490 } 1491 VIEW_STATE_SETS[i] = set; 1492 } 1493 1494 EMPTY_STATE_SET = VIEW_STATE_SETS[0]; 1495 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED]; 1496 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED]; 1497 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1498 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED]; 1499 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED]; 1500 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1501 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED]; 1502 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1503 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED]; 1504 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1505 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1506 | VIEW_STATE_FOCUSED]; 1507 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED]; 1508 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1509 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED]; 1510 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1511 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED]; 1512 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1513 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1514 | VIEW_STATE_ENABLED]; 1515 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1516 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED]; 1517 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1518 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1519 | VIEW_STATE_ENABLED]; 1520 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1521 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1522 | VIEW_STATE_ENABLED]; 1523 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1524 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1525 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED]; 1526 1527 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED]; 1528 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1529 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED]; 1530 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1531 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED]; 1532 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1533 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1534 | VIEW_STATE_PRESSED]; 1535 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1536 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1537 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1538 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1539 | VIEW_STATE_PRESSED]; 1540 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1541 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1542 | VIEW_STATE_PRESSED]; 1543 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1544 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1545 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1546 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[ 1547 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1548 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1549 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED 1550 | VIEW_STATE_PRESSED]; 1551 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1552 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED 1553 | VIEW_STATE_PRESSED]; 1554 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1555 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1556 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1557 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1558 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED 1559 | VIEW_STATE_PRESSED]; 1560 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1561 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1562 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1563 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1564 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1565 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1566 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1567 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1568 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED 1569 | VIEW_STATE_PRESSED]; 1570 } 1571 1572 /** 1573 * Accessibility event types that are dispatched for text population. 1574 */ 1575 private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES = 1576 AccessibilityEvent.TYPE_VIEW_CLICKED 1577 | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED 1578 | AccessibilityEvent.TYPE_VIEW_SELECTED 1579 | AccessibilityEvent.TYPE_VIEW_FOCUSED 1580 | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED 1581 | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER 1582 | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT 1583 | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED 1584 | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED 1585 | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED 1586 | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY; 1587 1588 /** 1589 * Temporary Rect currently for use in setBackground(). This will probably 1590 * be extended in the future to hold our own class with more than just 1591 * a Rect. :) 1592 */ 1593 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1594 1595 /** 1596 * Map used to store views' tags. 1597 */ 1598 private SparseArray<Object> mKeyedTags; 1599 1600 /** 1601 * The next available accessibility id. 1602 */ 1603 private static int sNextAccessibilityViewId; 1604 1605 /** 1606 * The animation currently associated with this view. 1607 * @hide 1608 */ 1609 protected Animation mCurrentAnimation = null; 1610 1611 /** 1612 * Width as measured during measure pass. 1613 * {@hide} 1614 */ 1615 @ViewDebug.ExportedProperty(category = "measurement") 1616 int mMeasuredWidth; 1617 1618 /** 1619 * Height as measured during measure pass. 1620 * {@hide} 1621 */ 1622 @ViewDebug.ExportedProperty(category = "measurement") 1623 int mMeasuredHeight; 1624 1625 /** 1626 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1627 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1628 * its display list. This flag, used only when hw accelerated, allows us to clear the 1629 * flag while retaining this information until it's needed (at getDisplayList() time and 1630 * in drawChild(), when we decide to draw a view's children's display lists into our own). 1631 * 1632 * {@hide} 1633 */ 1634 boolean mRecreateDisplayList = false; 1635 1636 /** 1637 * The view's identifier. 1638 * {@hide} 1639 * 1640 * @see #setId(int) 1641 * @see #getId() 1642 */ 1643 @ViewDebug.ExportedProperty(resolveId = true) 1644 int mID = NO_ID; 1645 1646 /** 1647 * The stable ID of this view for accessibility purposes. 1648 */ 1649 int mAccessibilityViewId = NO_ID; 1650 1651 private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 1652 1653 SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent; 1654 1655 /** 1656 * The view's tag. 1657 * {@hide} 1658 * 1659 * @see #setTag(Object) 1660 * @see #getTag() 1661 */ 1662 protected Object mTag = null; 1663 1664 // for mPrivateFlags: 1665 /** {@hide} */ 1666 static final int PFLAG_WANTS_FOCUS = 0x00000001; 1667 /** {@hide} */ 1668 static final int PFLAG_FOCUSED = 0x00000002; 1669 /** {@hide} */ 1670 static final int PFLAG_SELECTED = 0x00000004; 1671 /** {@hide} */ 1672 static final int PFLAG_IS_ROOT_NAMESPACE = 0x00000008; 1673 /** {@hide} */ 1674 static final int PFLAG_HAS_BOUNDS = 0x00000010; 1675 /** {@hide} */ 1676 static final int PFLAG_DRAWN = 0x00000020; 1677 /** 1678 * When this flag is set, this view is running an animation on behalf of its 1679 * children and should therefore not cancel invalidate requests, even if they 1680 * lie outside of this view's bounds. 1681 * 1682 * {@hide} 1683 */ 1684 static final int PFLAG_DRAW_ANIMATION = 0x00000040; 1685 /** {@hide} */ 1686 static final int PFLAG_SKIP_DRAW = 0x00000080; 1687 /** {@hide} */ 1688 static final int PFLAG_ONLY_DRAWS_BACKGROUND = 0x00000100; 1689 /** {@hide} */ 1690 static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1691 /** {@hide} */ 1692 static final int PFLAG_DRAWABLE_STATE_DIRTY = 0x00000400; 1693 /** {@hide} */ 1694 static final int PFLAG_MEASURED_DIMENSION_SET = 0x00000800; 1695 /** {@hide} */ 1696 static final int PFLAG_FORCE_LAYOUT = 0x00001000; 1697 /** {@hide} */ 1698 static final int PFLAG_LAYOUT_REQUIRED = 0x00002000; 1699 1700 private static final int PFLAG_PRESSED = 0x00004000; 1701 1702 /** {@hide} */ 1703 static final int PFLAG_DRAWING_CACHE_VALID = 0x00008000; 1704 /** 1705 * Flag used to indicate that this view should be drawn once more (and only once 1706 * more) after its animation has completed. 1707 * {@hide} 1708 */ 1709 static final int PFLAG_ANIMATION_STARTED = 0x00010000; 1710 1711 private static final int PFLAG_SAVE_STATE_CALLED = 0x00020000; 1712 1713 /** 1714 * Indicates that the View returned true when onSetAlpha() was called and that 1715 * the alpha must be restored. 1716 * {@hide} 1717 */ 1718 static final int PFLAG_ALPHA_SET = 0x00040000; 1719 1720 /** 1721 * Set by {@link #setScrollContainer(boolean)}. 1722 */ 1723 static final int PFLAG_SCROLL_CONTAINER = 0x00080000; 1724 1725 /** 1726 * Set by {@link #setScrollContainer(boolean)}. 1727 */ 1728 static final int PFLAG_SCROLL_CONTAINER_ADDED = 0x00100000; 1729 1730 /** 1731 * View flag indicating whether this view was invalidated (fully or partially.) 1732 * 1733 * @hide 1734 */ 1735 static final int PFLAG_DIRTY = 0x00200000; 1736 1737 /** 1738 * View flag indicating whether this view was invalidated by an opaque 1739 * invalidate request. 1740 * 1741 * @hide 1742 */ 1743 static final int PFLAG_DIRTY_OPAQUE = 0x00400000; 1744 1745 /** 1746 * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}. 1747 * 1748 * @hide 1749 */ 1750 static final int PFLAG_DIRTY_MASK = 0x00600000; 1751 1752 /** 1753 * Indicates whether the background is opaque. 1754 * 1755 * @hide 1756 */ 1757 static final int PFLAG_OPAQUE_BACKGROUND = 0x00800000; 1758 1759 /** 1760 * Indicates whether the scrollbars are opaque. 1761 * 1762 * @hide 1763 */ 1764 static final int PFLAG_OPAQUE_SCROLLBARS = 0x01000000; 1765 1766 /** 1767 * Indicates whether the view is opaque. 1768 * 1769 * @hide 1770 */ 1771 static final int PFLAG_OPAQUE_MASK = 0x01800000; 1772 1773 /** 1774 * Indicates a prepressed state; 1775 * the short time between ACTION_DOWN and recognizing 1776 * a 'real' press. Prepressed is used to recognize quick taps 1777 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1778 * 1779 * @hide 1780 */ 1781 private static final int PFLAG_PREPRESSED = 0x02000000; 1782 1783 /** 1784 * Indicates whether the view is temporarily detached. 1785 * 1786 * @hide 1787 */ 1788 static final int PFLAG_CANCEL_NEXT_UP_EVENT = 0x04000000; 1789 1790 /** 1791 * Indicates that we should awaken scroll bars once attached 1792 * 1793 * @hide 1794 */ 1795 private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1796 1797 /** 1798 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 1799 * @hide 1800 */ 1801 private static final int PFLAG_HOVERED = 0x10000000; 1802 1803 /** 1804 * no longer needed, should be reused 1805 */ 1806 private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000; 1807 1808 /** {@hide} */ 1809 static final int PFLAG_ACTIVATED = 0x40000000; 1810 1811 /** 1812 * Indicates that this view was specifically invalidated, not just dirtied because some 1813 * child view was invalidated. The flag is used to determine when we need to recreate 1814 * a view's display list (as opposed to just returning a reference to its existing 1815 * display list). 1816 * 1817 * @hide 1818 */ 1819 static final int PFLAG_INVALIDATED = 0x80000000; 1820 1821 /** 1822 * Masks for mPrivateFlags2, as generated by dumpFlags(): 1823 * 1824 * |-------|-------|-------|-------| 1825 * 1 PFLAG2_DRAG_CAN_ACCEPT 1826 * 1 PFLAG2_DRAG_HOVERED 1827 * 11 PFLAG2_LAYOUT_DIRECTION_MASK 1828 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL 1829 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED 1830 * 11 PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK 1831 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[1] 1832 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[2] 1833 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[3] 1834 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[4] 1835 * 1 1 PFLAG2_TEXT_DIRECTION_FLAGS[5] 1836 * 111 PFLAG2_TEXT_DIRECTION_MASK 1837 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED 1838 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT 1839 * 111 PFLAG2_TEXT_DIRECTION_RESOLVED_MASK 1840 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[1] 1841 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[2] 1842 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[3] 1843 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[4] 1844 * 1 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[5] 1845 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[6] 1846 * 111 PFLAG2_TEXT_ALIGNMENT_MASK 1847 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED 1848 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT 1849 * 111 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK 1850 * 111 PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK 1851 * 11 PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK 1852 * 1 PFLAG2_ACCESSIBILITY_FOCUSED 1853 * 1 PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED 1854 * 1 PFLAG2_VIEW_QUICK_REJECTED 1855 * 1 PFLAG2_PADDING_RESOLVED 1856 * 1 PFLAG2_DRAWABLE_RESOLVED 1857 * 1 PFLAG2_HAS_TRANSIENT_STATE 1858 * |-------|-------|-------|-------| 1859 */ 1860 1861 /** 1862 * Indicates that this view has reported that it can accept the current drag's content. 1863 * Cleared when the drag operation concludes. 1864 * @hide 1865 */ 1866 static final int PFLAG2_DRAG_CAN_ACCEPT = 0x00000001; 1867 1868 /** 1869 * Indicates that this view is currently directly under the drag location in a 1870 * drag-and-drop operation involving content that it can accept. Cleared when 1871 * the drag exits the view, or when the drag operation concludes. 1872 * @hide 1873 */ 1874 static final int PFLAG2_DRAG_HOVERED = 0x00000002; 1875 1876 /** @hide */ 1877 @IntDef({ 1878 LAYOUT_DIRECTION_LTR, 1879 LAYOUT_DIRECTION_RTL, 1880 LAYOUT_DIRECTION_INHERIT, 1881 LAYOUT_DIRECTION_LOCALE 1882 }) 1883 @Retention(RetentionPolicy.SOURCE) 1884 // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection 1885 public @interface LayoutDir {} 1886 1887 /** @hide */ 1888 @IntDef({ 1889 LAYOUT_DIRECTION_LTR, 1890 LAYOUT_DIRECTION_RTL 1891 }) 1892 @Retention(RetentionPolicy.SOURCE) 1893 public @interface ResolvedLayoutDir {} 1894 1895 /** 1896 * Horizontal layout direction of this view is from Left to Right. 1897 * Use with {@link #setLayoutDirection}. 1898 */ 1899 public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR; 1900 1901 /** 1902 * Horizontal layout direction of this view is from Right to Left. 1903 * Use with {@link #setLayoutDirection}. 1904 */ 1905 public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL; 1906 1907 /** 1908 * Horizontal layout direction of this view is inherited from its parent. 1909 * Use with {@link #setLayoutDirection}. 1910 */ 1911 public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT; 1912 1913 /** 1914 * Horizontal layout direction of this view is from deduced from the default language 1915 * script for the locale. Use with {@link #setLayoutDirection}. 1916 */ 1917 public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE; 1918 1919 /** 1920 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 1921 * @hide 1922 */ 1923 static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2; 1924 1925 /** 1926 * Mask for use with private flags indicating bits used for horizontal layout direction. 1927 * @hide 1928 */ 1929 static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1930 1931 /** 1932 * Indicates whether the view horizontal layout direction has been resolved and drawn to the 1933 * right-to-left direction. 1934 * @hide 1935 */ 1936 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1937 1938 /** 1939 * Indicates whether the view horizontal layout direction has been resolved. 1940 * @hide 1941 */ 1942 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1943 1944 /** 1945 * Mask for use with private flags indicating bits used for resolved horizontal layout direction. 1946 * @hide 1947 */ 1948 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C 1949 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1950 1951 /* 1952 * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct 1953 * flag value. 1954 * @hide 1955 */ 1956 private static final int[] LAYOUT_DIRECTION_FLAGS = { 1957 LAYOUT_DIRECTION_LTR, 1958 LAYOUT_DIRECTION_RTL, 1959 LAYOUT_DIRECTION_INHERIT, 1960 LAYOUT_DIRECTION_LOCALE 1961 }; 1962 1963 /** 1964 * Default horizontal layout direction. 1965 */ 1966 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 1967 1968 /** 1969 * Default horizontal layout direction. 1970 * @hide 1971 */ 1972 static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR; 1973 1974 /** 1975 * Text direction is inherited thru {@link ViewGroup} 1976 */ 1977 public static final int TEXT_DIRECTION_INHERIT = 0; 1978 1979 /** 1980 * Text direction is using "first strong algorithm". The first strong directional character 1981 * determines the paragraph direction. If there is no strong directional character, the 1982 * paragraph direction is the view's resolved layout direction. 1983 */ 1984 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 1985 1986 /** 1987 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 1988 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 1989 * If there are neither, the paragraph direction is the view's resolved layout direction. 1990 */ 1991 public static final int TEXT_DIRECTION_ANY_RTL = 2; 1992 1993 /** 1994 * Text direction is forced to LTR. 1995 */ 1996 public static final int TEXT_DIRECTION_LTR = 3; 1997 1998 /** 1999 * Text direction is forced to RTL. 2000 */ 2001 public static final int TEXT_DIRECTION_RTL = 4; 2002 2003 /** 2004 * Text direction is coming from the system Locale. 2005 */ 2006 public static final int TEXT_DIRECTION_LOCALE = 5; 2007 2008 /** 2009 * Default text direction is inherited 2010 */ 2011 private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT; 2012 2013 /** 2014 * Default resolved text direction 2015 * @hide 2016 */ 2017 static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG; 2018 2019 /** 2020 * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED) 2021 * @hide 2022 */ 2023 static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6; 2024 2025 /** 2026 * Mask for use with private flags indicating bits used for text direction. 2027 * @hide 2028 */ 2029 static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007 2030 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2031 2032 /** 2033 * Array of text direction flags for mapping attribute "textDirection" to correct 2034 * flag value. 2035 * @hide 2036 */ 2037 private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = { 2038 TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2039 TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2040 TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2041 TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2042 TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2043 TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT 2044 }; 2045 2046 /** 2047 * Indicates whether the view text direction has been resolved. 2048 * @hide 2049 */ 2050 static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008 2051 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2052 2053 /** 2054 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2055 * @hide 2056 */ 2057 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10; 2058 2059 /** 2060 * Mask for use with private flags indicating bits used for resolved text direction. 2061 * @hide 2062 */ 2063 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 2064 << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2065 2066 /** 2067 * Indicates whether the view text direction has been resolved to the "first strong" heuristic. 2068 * @hide 2069 */ 2070 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT = 2071 TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2072 2073 /** @hide */ 2074 @IntDef({ 2075 TEXT_ALIGNMENT_INHERIT, 2076 TEXT_ALIGNMENT_GRAVITY, 2077 TEXT_ALIGNMENT_CENTER, 2078 TEXT_ALIGNMENT_TEXT_START, 2079 TEXT_ALIGNMENT_TEXT_END, 2080 TEXT_ALIGNMENT_VIEW_START, 2081 TEXT_ALIGNMENT_VIEW_END 2082 }) 2083 @Retention(RetentionPolicy.SOURCE) 2084 public @interface TextAlignment {} 2085 2086 /** 2087 * Default text alignment. The text alignment of this View is inherited from its parent. 2088 * Use with {@link #setTextAlignment(int)} 2089 */ 2090 public static final int TEXT_ALIGNMENT_INHERIT = 0; 2091 2092 /** 2093 * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL, 2094 * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction. 2095 * 2096 * Use with {@link #setTextAlignment(int)} 2097 */ 2098 public static final int TEXT_ALIGNMENT_GRAVITY = 1; 2099 2100 /** 2101 * Align to the start of the paragraph, e.g. ALIGN_NORMAL. 2102 * 2103 * Use with {@link #setTextAlignment(int)} 2104 */ 2105 public static final int TEXT_ALIGNMENT_TEXT_START = 2; 2106 2107 /** 2108 * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE. 2109 * 2110 * Use with {@link #setTextAlignment(int)} 2111 */ 2112 public static final int TEXT_ALIGNMENT_TEXT_END = 3; 2113 2114 /** 2115 * Center the paragraph, e.g. ALIGN_CENTER. 2116 * 2117 * Use with {@link #setTextAlignment(int)} 2118 */ 2119 public static final int TEXT_ALIGNMENT_CENTER = 4; 2120 2121 /** 2122 * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved 2123 * layoutDirection is LTR, and ALIGN_RIGHT otherwise. 2124 * 2125 * Use with {@link #setTextAlignment(int)} 2126 */ 2127 public static final int TEXT_ALIGNMENT_VIEW_START = 5; 2128 2129 /** 2130 * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved 2131 * layoutDirection is LTR, and ALIGN_LEFT otherwise. 2132 * 2133 * Use with {@link #setTextAlignment(int)} 2134 */ 2135 public static final int TEXT_ALIGNMENT_VIEW_END = 6; 2136 2137 /** 2138 * Default text alignment is inherited 2139 */ 2140 private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2141 2142 /** 2143 * Default resolved text alignment 2144 * @hide 2145 */ 2146 static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2147 2148 /** 2149 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2150 * @hide 2151 */ 2152 static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13; 2153 2154 /** 2155 * Mask for use with private flags indicating bits used for text alignment. 2156 * @hide 2157 */ 2158 static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2159 2160 /** 2161 * Array of text direction flags for mapping attribute "textAlignment" to correct 2162 * flag value. 2163 * @hide 2164 */ 2165 private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = { 2166 TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2167 TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2168 TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2169 TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2170 TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2171 TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2172 TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT 2173 }; 2174 2175 /** 2176 * Indicates whether the view text alignment has been resolved. 2177 * @hide 2178 */ 2179 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2180 2181 /** 2182 * Bit shift to get the resolved text alignment. 2183 * @hide 2184 */ 2185 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17; 2186 2187 /** 2188 * Mask for use with private flags indicating bits used for text alignment. 2189 * @hide 2190 */ 2191 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 2192 << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2193 2194 /** 2195 * Indicates whether if the view text alignment has been resolved to gravity 2196 */ 2197 private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT = 2198 TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2199 2200 // Accessiblity constants for mPrivateFlags2 2201 2202 /** 2203 * Shift for the bits in {@link #mPrivateFlags2} related to the 2204 * "importantForAccessibility" attribute. 2205 */ 2206 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20; 2207 2208 /** 2209 * Automatically determine whether a view is important for accessibility. 2210 */ 2211 public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000; 2212 2213 /** 2214 * The view is important for accessibility. 2215 */ 2216 public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001; 2217 2218 /** 2219 * The view is not important for accessibility. 2220 */ 2221 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002; 2222 2223 /** 2224 * The view is not important for accessibility, nor are any of its 2225 * descendant views. 2226 */ 2227 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004; 2228 2229 /** 2230 * The default whether the view is important for accessibility. 2231 */ 2232 static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO; 2233 2234 /** 2235 * Mask for obtainig the bits which specify how to determine 2236 * whether a view is important for accessibility. 2237 */ 2238 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO 2239 | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO 2240 | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) 2241 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2242 2243 /** 2244 * Shift for the bits in {@link #mPrivateFlags2} related to the 2245 * "accessibilityLiveRegion" attribute. 2246 */ 2247 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23; 2248 2249 /** 2250 * Live region mode specifying that accessibility services should not 2251 * automatically announce changes to this view. This is the default live 2252 * region mode for most views. 2253 * <p> 2254 * Use with {@link #setAccessibilityLiveRegion(int)}. 2255 */ 2256 public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000; 2257 2258 /** 2259 * Live region mode specifying that accessibility services should announce 2260 * changes to this view. 2261 * <p> 2262 * Use with {@link #setAccessibilityLiveRegion(int)}. 2263 */ 2264 public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001; 2265 2266 /** 2267 * Live region mode specifying that accessibility services should interrupt 2268 * ongoing speech to immediately announce changes to this view. 2269 * <p> 2270 * Use with {@link #setAccessibilityLiveRegion(int)}. 2271 */ 2272 public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002; 2273 2274 /** 2275 * The default whether the view is important for accessibility. 2276 */ 2277 static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE; 2278 2279 /** 2280 * Mask for obtaining the bits which specify a view's accessibility live 2281 * region mode. 2282 */ 2283 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE 2284 | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE) 2285 << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 2286 2287 /** 2288 * Flag indicating whether a view has accessibility focus. 2289 */ 2290 static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000; 2291 2292 /** 2293 * Flag whether the accessibility state of the subtree rooted at this view changed. 2294 */ 2295 static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000; 2296 2297 /** 2298 * Flag indicating whether a view failed the quickReject() check in draw(). This condition 2299 * is used to check whether later changes to the view's transform should invalidate the 2300 * view to force the quickReject test to run again. 2301 */ 2302 static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000; 2303 2304 /** 2305 * Flag indicating that start/end padding has been resolved into left/right padding 2306 * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()} 2307 * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved 2308 * during measurement. In some special cases this is required such as when an adapter-based 2309 * view measures prospective children without attaching them to a window. 2310 */ 2311 static final int PFLAG2_PADDING_RESOLVED = 0x20000000; 2312 2313 /** 2314 * Flag indicating that the start/end drawables has been resolved into left/right ones. 2315 */ 2316 static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000; 2317 2318 /** 2319 * Indicates that the view is tracking some sort of transient state 2320 * that the app should not need to be aware of, but that the framework 2321 * should take special care to preserve. 2322 */ 2323 static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000; 2324 2325 /** 2326 * Group of bits indicating that RTL properties resolution is done. 2327 */ 2328 static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED | 2329 PFLAG2_TEXT_DIRECTION_RESOLVED | 2330 PFLAG2_TEXT_ALIGNMENT_RESOLVED | 2331 PFLAG2_PADDING_RESOLVED | 2332 PFLAG2_DRAWABLE_RESOLVED; 2333 2334 // There are a couple of flags left in mPrivateFlags2 2335 2336 /* End of masks for mPrivateFlags2 */ 2337 2338 /** 2339 * Masks for mPrivateFlags3, as generated by dumpFlags(): 2340 * 2341 * |-------|-------|-------|-------| 2342 * 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM 2343 * 1 PFLAG3_VIEW_IS_ANIMATING_ALPHA 2344 * 1 PFLAG3_IS_LAID_OUT 2345 * 1 PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT 2346 * 1 PFLAG3_CALLED_SUPER 2347 * |-------|-------|-------|-------| 2348 */ 2349 2350 /** 2351 * Flag indicating that view has a transform animation set on it. This is used to track whether 2352 * an animation is cleared between successive frames, in order to tell the associated 2353 * DisplayList to clear its animation matrix. 2354 */ 2355 static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1; 2356 2357 /** 2358 * Flag indicating that view has an alpha animation set on it. This is used to track whether an 2359 * animation is cleared between successive frames, in order to tell the associated 2360 * DisplayList to restore its alpha value. 2361 */ 2362 static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2; 2363 2364 /** 2365 * Flag indicating that the view has been through at least one layout since it 2366 * was last attached to a window. 2367 */ 2368 static final int PFLAG3_IS_LAID_OUT = 0x4; 2369 2370 /** 2371 * Flag indicating that a call to measure() was skipped and should be done 2372 * instead when layout() is invoked. 2373 */ 2374 static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8; 2375 2376 /** 2377 * Flag indicating that an overridden method correctly called down to 2378 * the superclass implementation as required by the API spec. 2379 */ 2380 static final int PFLAG3_CALLED_SUPER = 0x10; 2381 2382 /** 2383 * Flag indicating that we're in the process of applying window insets. 2384 */ 2385 static final int PFLAG3_APPLYING_INSETS = 0x20; 2386 2387 /** 2388 * Flag indicating that we're in the process of fitting system windows using the old method. 2389 */ 2390 static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40; 2391 2392 /** 2393 * Flag indicating that nested scrolling is enabled for this view. 2394 * The view will optionally cooperate with views up its parent chain to allow for 2395 * integrated nested scrolling along the same axis. 2396 */ 2397 static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80; 2398 2399 /* End of masks for mPrivateFlags3 */ 2400 2401 static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED; 2402 2403 /** 2404 * Always allow a user to over-scroll this view, provided it is a 2405 * view that can scroll. 2406 * 2407 * @see #getOverScrollMode() 2408 * @see #setOverScrollMode(int) 2409 */ 2410 public static final int OVER_SCROLL_ALWAYS = 0; 2411 2412 /** 2413 * Allow a user to over-scroll this view only if the content is large 2414 * enough to meaningfully scroll, provided it is a view that can scroll. 2415 * 2416 * @see #getOverScrollMode() 2417 * @see #setOverScrollMode(int) 2418 */ 2419 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 2420 2421 /** 2422 * Never allow a user to over-scroll this view. 2423 * 2424 * @see #getOverScrollMode() 2425 * @see #setOverScrollMode(int) 2426 */ 2427 public static final int OVER_SCROLL_NEVER = 2; 2428 2429 /** 2430 * Special constant for {@link #setSystemUiVisibility(int)}: View has 2431 * requested the system UI (status bar) to be visible (the default). 2432 * 2433 * @see #setSystemUiVisibility(int) 2434 */ 2435 public static final int SYSTEM_UI_FLAG_VISIBLE = 0; 2436 2437 /** 2438 * Flag for {@link #setSystemUiVisibility(int)}: View has requested the 2439 * system UI to enter an unobtrusive "low profile" mode. 2440 * 2441 * <p>This is for use in games, book readers, video players, or any other 2442 * "immersive" application where the usual system chrome is deemed too distracting. 2443 * 2444 * <p>In low profile mode, the status bar and/or navigation icons may dim. 2445 * 2446 * @see #setSystemUiVisibility(int) 2447 */ 2448 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001; 2449 2450 /** 2451 * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the 2452 * system navigation be temporarily hidden. 2453 * 2454 * <p>This is an even less obtrusive state than that called for by 2455 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls 2456 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause 2457 * those to disappear. This is useful (in conjunction with the 2458 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and 2459 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN} 2460 * window flags) for displaying content using every last pixel on the display. 2461 * 2462 * <p>There is a limitation: because navigation controls are so important, the least user 2463 * interaction will cause them to reappear immediately. When this happens, both 2464 * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically, 2465 * so that both elements reappear at the same time. 2466 * 2467 * @see #setSystemUiVisibility(int) 2468 */ 2469 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002; 2470 2471 /** 2472 * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go 2473 * into the normal fullscreen mode so that its content can take over the screen 2474 * while still allowing the user to interact with the application. 2475 * 2476 * <p>This has the same visual effect as 2477 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN 2478 * WindowManager.LayoutParams.FLAG_FULLSCREEN}, 2479 * meaning that non-critical screen decorations (such as the status bar) will be 2480 * hidden while the user is in the View's window, focusing the experience on 2481 * that content. Unlike the window flag, if you are using ActionBar in 2482 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2483 * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also 2484 * hide the action bar. 2485 * 2486 * <p>This approach to going fullscreen is best used over the window flag when 2487 * it is a transient state -- that is, the application does this at certain 2488 * points in its user interaction where it wants to allow the user to focus 2489 * on content, but not as a continuous state. For situations where the application 2490 * would like to simply stay full screen the entire time (such as a game that 2491 * wants to take over the screen), the 2492 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag} 2493 * is usually a better approach. The state set here will be removed by the system 2494 * in various situations (such as the user moving to another application) like 2495 * the other system UI states. 2496 * 2497 * <p>When using this flag, the application should provide some easy facility 2498 * for the user to go out of it. A common example would be in an e-book 2499 * reader, where tapping on the screen brings back whatever screen and UI 2500 * decorations that had been hidden while the user was immersed in reading 2501 * the book. 2502 * 2503 * @see #setSystemUiVisibility(int) 2504 */ 2505 public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004; 2506 2507 /** 2508 * Flag for {@link #setSystemUiVisibility(int)}: When using other layout 2509 * flags, we would like a stable view of the content insets given to 2510 * {@link #fitSystemWindows(Rect)}. This means that the insets seen there 2511 * will always represent the worst case that the application can expect 2512 * as a continuous state. In the stock Android UI this is the space for 2513 * the system bar, nav bar, and status bar, but not more transient elements 2514 * such as an input method. 2515 * 2516 * The stable layout your UI sees is based on the system UI modes you can 2517 * switch to. That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 2518 * then you will get a stable layout for changes of the 2519 * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify 2520 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and 2521 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition 2522 * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} 2523 * with a stable layout. (Note that you should avoid using 2524 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.) 2525 * 2526 * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN} 2527 * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}), 2528 * then a hidden status bar will be considered a "stable" state for purposes 2529 * here. This allows your UI to continually hide the status bar, while still 2530 * using the system UI flags to hide the action bar while still retaining 2531 * a stable layout. Note that changing the window fullscreen flag will never 2532 * provide a stable layout for a clean transition. 2533 * 2534 * <p>If you are using ActionBar in 2535 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2536 * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the 2537 * insets it adds to those given to the application. 2538 */ 2539 public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100; 2540 2541 /** 2542 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2543 * to be layed out as if it has requested 2544 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't. This 2545 * allows it to avoid artifacts when switching in and out of that mode, at 2546 * the expense that some of its user interface may be covered by screen 2547 * decorations when they are shown. You can perform layout of your inner 2548 * UI elements to account for the navigation system UI through the 2549 * {@link #fitSystemWindows(Rect)} method. 2550 */ 2551 public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200; 2552 2553 /** 2554 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2555 * to be layed out as if it has requested 2556 * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't. This 2557 * allows it to avoid artifacts when switching in and out of that mode, at 2558 * the expense that some of its user interface may be covered by screen 2559 * decorations when they are shown. You can perform layout of your inner 2560 * UI elements to account for non-fullscreen system UI through the 2561 * {@link #fitSystemWindows(Rect)} method. 2562 */ 2563 public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400; 2564 2565 /** 2566 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2567 * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. If this flag is 2568 * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any 2569 * user interaction. 2570 * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only 2571 * has an effect when used in combination with that flag.</p> 2572 */ 2573 public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800; 2574 2575 /** 2576 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2577 * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation 2578 * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. Use this flag to create an immersive 2579 * experience while also hiding the system bars. If this flag is not set, 2580 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user 2581 * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system 2582 * if the user swipes from the top of the screen. 2583 * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with 2584 * system gestures, such as swiping from the top of the screen. These transient system bars 2585 * will overlay app’s content, may have some degree of transparency, and will automatically 2586 * hide after a short timeout. 2587 * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and 2588 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination 2589 * with one or both of those flags.</p> 2590 */ 2591 public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000; 2592 2593 /** 2594 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead. 2595 */ 2596 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE; 2597 2598 /** 2599 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead. 2600 */ 2601 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE; 2602 2603 /** 2604 * @hide 2605 * 2606 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2607 * out of the public fields to keep the undefined bits out of the developer's way. 2608 * 2609 * Flag to make the status bar not expandable. Unless you also 2610 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 2611 */ 2612 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 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 hide notification icons and scrolling ticker text. 2621 */ 2622 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 2623 2624 /** 2625 * @hide 2626 * 2627 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2628 * out of the public fields to keep the undefined bits out of the developer's way. 2629 * 2630 * Flag to disable incoming notification alerts. This will not block 2631 * icons, but it will block sound, vibrating and other visual or aural notifications. 2632 */ 2633 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 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 hide only the scrolling ticker. Note that 2642 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 2643 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 2644 */ 2645 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 2646 2647 /** 2648 * @hide 2649 * 2650 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2651 * out of the public fields to keep the undefined bits out of the developer's way. 2652 * 2653 * Flag to hide the center system info area. 2654 */ 2655 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 2656 2657 /** 2658 * @hide 2659 * 2660 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2661 * out of the public fields to keep the undefined bits out of the developer's way. 2662 * 2663 * Flag to hide only the home button. Don't use this 2664 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2665 */ 2666 public static final int STATUS_BAR_DISABLE_HOME = 0x00200000; 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 back 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_BACK = 0x00400000; 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 clock. You might use this if your activity has 2686 * its own clock making the status bar's clock redundant. 2687 */ 2688 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 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 recent apps button. Don't use this 2697 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2698 */ 2699 public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000; 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 disable the global search gesture. 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_SEARCH = 0x02000000; 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 specify that the status bar is displayed in transient mode. 2719 */ 2720 public static final int STATUS_BAR_TRANSIENT = 0x04000000; 2721 2722 /** 2723 * @hide 2724 * 2725 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2726 * out of the public fields to keep the undefined bits out of the developer's way. 2727 * 2728 * Flag to specify that the navigation bar is displayed in transient mode. 2729 */ 2730 public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000; 2731 2732 /** 2733 * @hide 2734 * 2735 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2736 * out of the public fields to keep the undefined bits out of the developer's way. 2737 * 2738 * Flag to specify that the hidden status bar would like to be shown. 2739 */ 2740 public static final int STATUS_BAR_UNHIDE = 0x10000000; 2741 2742 /** 2743 * @hide 2744 * 2745 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2746 * out of the public fields to keep the undefined bits out of the developer's way. 2747 * 2748 * Flag to specify that the hidden navigation bar would like to be shown. 2749 */ 2750 public static final int NAVIGATION_BAR_UNHIDE = 0x20000000; 2751 2752 /** 2753 * @hide 2754 * 2755 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2756 * out of the public fields to keep the undefined bits out of the developer's way. 2757 * 2758 * Flag to specify that the status bar is displayed in translucent mode. 2759 */ 2760 public static final int STATUS_BAR_TRANSLUCENT = 0x40000000; 2761 2762 /** 2763 * @hide 2764 * 2765 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2766 * out of the public fields to keep the undefined bits out of the developer's way. 2767 * 2768 * Flag to specify that the navigation bar is displayed in translucent mode. 2769 */ 2770 public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000; 2771 2772 /** 2773 * @hide 2774 * 2775 * Whether Recents is visible or not. 2776 */ 2777 public static final int RECENT_APPS_VISIBLE = 0x00004000; 2778 2779 /** 2780 * @hide 2781 * 2782 * Makes system ui transparent. 2783 */ 2784 public static final int SYSTEM_UI_TRANSPARENT = 0x00008000; 2785 2786 /** 2787 * @hide 2788 */ 2789 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FFF; 2790 2791 /** 2792 * These are the system UI flags that can be cleared by events outside 2793 * of an application. Currently this is just the ability to tap on the 2794 * screen while hiding the navigation bar to have it return. 2795 * @hide 2796 */ 2797 public static final int SYSTEM_UI_CLEARABLE_FLAGS = 2798 SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION 2799 | SYSTEM_UI_FLAG_FULLSCREEN; 2800 2801 /** 2802 * Flags that can impact the layout in relation to system UI. 2803 */ 2804 public static final int SYSTEM_UI_LAYOUT_FLAGS = 2805 SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 2806 | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; 2807 2808 /** @hide */ 2809 @IntDef(flag = true, 2810 value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION }) 2811 @Retention(RetentionPolicy.SOURCE) 2812 public @interface FindViewFlags {} 2813 2814 /** 2815 * Find views that render the specified text. 2816 * 2817 * @see #findViewsWithText(ArrayList, CharSequence, int) 2818 */ 2819 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001; 2820 2821 /** 2822 * Find find views that contain the specified content description. 2823 * 2824 * @see #findViewsWithText(ArrayList, CharSequence, int) 2825 */ 2826 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002; 2827 2828 /** 2829 * Find views that contain {@link AccessibilityNodeProvider}. Such 2830 * a View is a root of virtual view hierarchy and may contain the searched 2831 * text. If this flag is set Views with providers are automatically 2832 * added and it is a responsibility of the client to call the APIs of 2833 * the provider to determine whether the virtual tree rooted at this View 2834 * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s 2835 * representing the virtual views with this text. 2836 * 2837 * @see #findViewsWithText(ArrayList, CharSequence, int) 2838 * 2839 * @hide 2840 */ 2841 public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004; 2842 2843 /** 2844 * The undefined cursor position. 2845 * 2846 * @hide 2847 */ 2848 public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1; 2849 2850 /** 2851 * Indicates that the screen has changed state and is now off. 2852 * 2853 * @see #onScreenStateChanged(int) 2854 */ 2855 public static final int SCREEN_STATE_OFF = 0x0; 2856 2857 /** 2858 * Indicates that the screen has changed state and is now on. 2859 * 2860 * @see #onScreenStateChanged(int) 2861 */ 2862 public static final int SCREEN_STATE_ON = 0x1; 2863 2864 /** 2865 * Indicates no axis of view scrolling. 2866 */ 2867 public static final int SCROLL_AXIS_NONE = 0; 2868 2869 /** 2870 * Indicates scrolling along the horizontal axis. 2871 */ 2872 public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0; 2873 2874 /** 2875 * Indicates scrolling along the vertical axis. 2876 */ 2877 public static final int SCROLL_AXIS_VERTICAL = 1 << 1; 2878 2879 /** 2880 * Controls the over-scroll mode for this view. 2881 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 2882 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 2883 * and {@link #OVER_SCROLL_NEVER}. 2884 */ 2885 private int mOverScrollMode; 2886 2887 /** 2888 * The parent this view is attached to. 2889 * {@hide} 2890 * 2891 * @see #getParent() 2892 */ 2893 protected ViewParent mParent; 2894 2895 /** 2896 * {@hide} 2897 */ 2898 AttachInfo mAttachInfo; 2899 2900 /** 2901 * {@hide} 2902 */ 2903 @ViewDebug.ExportedProperty(flagMapping = { 2904 @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT, 2905 name = "FORCE_LAYOUT"), 2906 @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED, 2907 name = "LAYOUT_REQUIRED"), 2908 @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID, 2909 name = "DRAWING_CACHE_INVALID", outputIf = false), 2910 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true), 2911 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false), 2912 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 2913 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY") 2914 }) 2915 int mPrivateFlags; 2916 int mPrivateFlags2; 2917 int mPrivateFlags3; 2918 2919 /** 2920 * This view's request for the visibility of the status bar. 2921 * @hide 2922 */ 2923 @ViewDebug.ExportedProperty(flagMapping = { 2924 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 2925 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 2926 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 2927 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2928 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2929 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 2930 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 2931 equals = SYSTEM_UI_FLAG_VISIBLE, 2932 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 2933 }) 2934 int mSystemUiVisibility; 2935 2936 /** 2937 * Reference count for transient state. 2938 * @see #setHasTransientState(boolean) 2939 */ 2940 int mTransientStateCount = 0; 2941 2942 /** 2943 * Count of how many windows this view has been attached to. 2944 */ 2945 int mWindowAttachCount; 2946 2947 /** 2948 * The layout parameters associated with this view and used by the parent 2949 * {@link android.view.ViewGroup} to determine how this view should be 2950 * laid out. 2951 * {@hide} 2952 */ 2953 protected ViewGroup.LayoutParams mLayoutParams; 2954 2955 /** 2956 * The view flags hold various views states. 2957 * {@hide} 2958 */ 2959 @ViewDebug.ExportedProperty 2960 int mViewFlags; 2961 2962 static class TransformationInfo { 2963 /** 2964 * The transform matrix for the View. This transform is calculated internally 2965 * based on the translation, rotation, and scale properties. 2966 * 2967 * Do *not* use this variable directly; instead call getMatrix(), which will 2968 * load the value from the View's RenderNode. 2969 */ 2970 private final Matrix mMatrix = new Matrix(); 2971 2972 /** 2973 * The inverse transform matrix for the View. This transform is calculated 2974 * internally based on the translation, rotation, and scale properties. 2975 * 2976 * Do *not* use this variable directly; instead call getInverseMatrix(), 2977 * which will load the value from the View's RenderNode. 2978 */ 2979 private Matrix mInverseMatrix; 2980 2981 /** 2982 * The opacity of the View. This is a value from 0 to 1, where 0 means 2983 * completely transparent and 1 means completely opaque. 2984 */ 2985 @ViewDebug.ExportedProperty 2986 float mAlpha = 1f; 2987 2988 /** 2989 * The opacity of the view as manipulated by the Fade transition. This is a hidden 2990 * property only used by transitions, which is composited with the other alpha 2991 * values to calculate the final visual alpha value. 2992 */ 2993 float mTransitionAlpha = 1f; 2994 } 2995 2996 TransformationInfo mTransformationInfo; 2997 2998 /** 2999 * Current clip bounds. to which all drawing of this view are constrained. 3000 */ 3001 Rect mClipBounds = null; 3002 3003 private boolean mLastIsOpaque; 3004 3005 /** 3006 * The distance in pixels from the left edge of this view's parent 3007 * to the left edge of this view. 3008 * {@hide} 3009 */ 3010 @ViewDebug.ExportedProperty(category = "layout") 3011 protected int mLeft; 3012 /** 3013 * The distance in pixels from the left edge of this view's parent 3014 * to the right edge of this view. 3015 * {@hide} 3016 */ 3017 @ViewDebug.ExportedProperty(category = "layout") 3018 protected int mRight; 3019 /** 3020 * The distance in pixels from the top edge of this view's parent 3021 * to the top edge of this view. 3022 * {@hide} 3023 */ 3024 @ViewDebug.ExportedProperty(category = "layout") 3025 protected int mTop; 3026 /** 3027 * The distance in pixels from the top edge of this view's parent 3028 * to the bottom edge of this view. 3029 * {@hide} 3030 */ 3031 @ViewDebug.ExportedProperty(category = "layout") 3032 protected int mBottom; 3033 3034 /** 3035 * The offset, in pixels, by which the content of this view is scrolled 3036 * horizontally. 3037 * {@hide} 3038 */ 3039 @ViewDebug.ExportedProperty(category = "scrolling") 3040 protected int mScrollX; 3041 /** 3042 * The offset, in pixels, by which the content of this view is scrolled 3043 * vertically. 3044 * {@hide} 3045 */ 3046 @ViewDebug.ExportedProperty(category = "scrolling") 3047 protected int mScrollY; 3048 3049 /** 3050 * The left padding in pixels, that is the distance in pixels between the 3051 * left edge of this view and the left edge of its content. 3052 * {@hide} 3053 */ 3054 @ViewDebug.ExportedProperty(category = "padding") 3055 protected int mPaddingLeft = 0; 3056 /** 3057 * The right padding in pixels, that is the distance in pixels between the 3058 * right edge of this view and the right edge of its content. 3059 * {@hide} 3060 */ 3061 @ViewDebug.ExportedProperty(category = "padding") 3062 protected int mPaddingRight = 0; 3063 /** 3064 * The top padding in pixels, that is the distance in pixels between the 3065 * top edge of this view and the top edge of its content. 3066 * {@hide} 3067 */ 3068 @ViewDebug.ExportedProperty(category = "padding") 3069 protected int mPaddingTop; 3070 /** 3071 * The bottom padding in pixels, that is the distance in pixels between the 3072 * bottom edge of this view and the bottom edge of its content. 3073 * {@hide} 3074 */ 3075 @ViewDebug.ExportedProperty(category = "padding") 3076 protected int mPaddingBottom; 3077 3078 /** 3079 * The layout insets in pixels, that is the distance in pixels between the 3080 * visible edges of this view its bounds. 3081 */ 3082 private Insets mLayoutInsets; 3083 3084 /** 3085 * Briefly describes the view and is primarily used for accessibility support. 3086 */ 3087 private CharSequence mContentDescription; 3088 3089 /** 3090 * Specifies the id of a view for which this view serves as a label for 3091 * accessibility purposes. 3092 */ 3093 private int mLabelForId = View.NO_ID; 3094 3095 /** 3096 * Predicate for matching labeled view id with its label for 3097 * accessibility purposes. 3098 */ 3099 private MatchLabelForPredicate mMatchLabelForPredicate; 3100 3101 /** 3102 * Predicate for matching a view by its id. 3103 */ 3104 private MatchIdPredicate mMatchIdPredicate; 3105 3106 /** 3107 * Cache the paddingRight set by the user to append to the scrollbar's size. 3108 * 3109 * @hide 3110 */ 3111 @ViewDebug.ExportedProperty(category = "padding") 3112 protected int mUserPaddingRight; 3113 3114 /** 3115 * Cache the paddingBottom set by the user to append to the scrollbar's size. 3116 * 3117 * @hide 3118 */ 3119 @ViewDebug.ExportedProperty(category = "padding") 3120 protected int mUserPaddingBottom; 3121 3122 /** 3123 * Cache the paddingLeft set by the user to append to the scrollbar's size. 3124 * 3125 * @hide 3126 */ 3127 @ViewDebug.ExportedProperty(category = "padding") 3128 protected int mUserPaddingLeft; 3129 3130 /** 3131 * Cache the paddingStart set by the user to append to the scrollbar's size. 3132 * 3133 */ 3134 @ViewDebug.ExportedProperty(category = "padding") 3135 int mUserPaddingStart; 3136 3137 /** 3138 * Cache the paddingEnd set by the user to append to the scrollbar's size. 3139 * 3140 */ 3141 @ViewDebug.ExportedProperty(category = "padding") 3142 int mUserPaddingEnd; 3143 3144 /** 3145 * Cache initial left padding. 3146 * 3147 * @hide 3148 */ 3149 int mUserPaddingLeftInitial; 3150 3151 /** 3152 * Cache initial right padding. 3153 * 3154 * @hide 3155 */ 3156 int mUserPaddingRightInitial; 3157 3158 /** 3159 * Default undefined padding 3160 */ 3161 private static final int UNDEFINED_PADDING = Integer.MIN_VALUE; 3162 3163 /** 3164 * Cache if a left padding has been defined 3165 */ 3166 private boolean mLeftPaddingDefined = false; 3167 3168 /** 3169 * Cache if a right padding has been defined 3170 */ 3171 private boolean mRightPaddingDefined = false; 3172 3173 /** 3174 * @hide 3175 */ 3176 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 3177 /** 3178 * @hide 3179 */ 3180 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 3181 3182 private LongSparseLongArray mMeasureCache; 3183 3184 @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_") 3185 private Drawable mBackground; 3186 private ColorStateList mBackgroundTint = null; 3187 private PorterDuff.Mode mBackgroundTintMode = PorterDuff.Mode.SRC_ATOP; 3188 private boolean mHasBackgroundTint = false; 3189 3190 /** 3191 * RenderNode used for backgrounds. 3192 * <p> 3193 * When non-null and valid, this is expected to contain an up-to-date copy 3194 * of the background drawable. It is cleared on temporary detach, and reset 3195 * on cleanup. 3196 */ 3197 private RenderNode mBackgroundRenderNode; 3198 3199 private int mBackgroundResource; 3200 private boolean mBackgroundSizeChanged; 3201 3202 private String mTransitionName; 3203 3204 static class ListenerInfo { 3205 /** 3206 * Listener used to dispatch focus change events. 3207 * This field should be made private, so it is hidden from the SDK. 3208 * {@hide} 3209 */ 3210 protected OnFocusChangeListener mOnFocusChangeListener; 3211 3212 /** 3213 * Listeners for layout change events. 3214 */ 3215 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 3216 3217 /** 3218 * Listeners for attach events. 3219 */ 3220 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 3221 3222 /** 3223 * Listener used to dispatch click events. 3224 * This field should be made private, so it is hidden from the SDK. 3225 * {@hide} 3226 */ 3227 public OnClickListener mOnClickListener; 3228 3229 /** 3230 * Listener used to dispatch long click events. 3231 * This field should be made private, so it is hidden from the SDK. 3232 * {@hide} 3233 */ 3234 protected OnLongClickListener mOnLongClickListener; 3235 3236 /** 3237 * Listener used to build the context menu. 3238 * This field should be made private, so it is hidden from the SDK. 3239 * {@hide} 3240 */ 3241 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 3242 3243 private OnKeyListener mOnKeyListener; 3244 3245 private OnTouchListener mOnTouchListener; 3246 3247 private OnHoverListener mOnHoverListener; 3248 3249 private OnGenericMotionListener mOnGenericMotionListener; 3250 3251 private OnDragListener mOnDragListener; 3252 3253 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 3254 3255 OnApplyWindowInsetsListener mOnApplyWindowInsetsListener; 3256 } 3257 3258 ListenerInfo mListenerInfo; 3259 3260 /** 3261 * The application environment this view lives in. 3262 * This field should be made private, so it is hidden from the SDK. 3263 * {@hide} 3264 */ 3265 protected Context mContext; 3266 3267 private final Resources mResources; 3268 3269 private ScrollabilityCache mScrollCache; 3270 3271 private int[] mDrawableState = null; 3272 3273 ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND; 3274 3275 /** 3276 * Animator that automatically runs based on state changes. 3277 */ 3278 private StateListAnimator mStateListAnimator; 3279 3280 /** 3281 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 3282 * the user may specify which view to go to next. 3283 */ 3284 private int mNextFocusLeftId = View.NO_ID; 3285 3286 /** 3287 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 3288 * the user may specify which view to go to next. 3289 */ 3290 private int mNextFocusRightId = View.NO_ID; 3291 3292 /** 3293 * When this view has focus and the next focus is {@link #FOCUS_UP}, 3294 * the user may specify which view to go to next. 3295 */ 3296 private int mNextFocusUpId = View.NO_ID; 3297 3298 /** 3299 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 3300 * the user may specify which view to go to next. 3301 */ 3302 private int mNextFocusDownId = View.NO_ID; 3303 3304 /** 3305 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 3306 * the user may specify which view to go to next. 3307 */ 3308 int mNextFocusForwardId = View.NO_ID; 3309 3310 private CheckForLongPress mPendingCheckForLongPress; 3311 private CheckForTap mPendingCheckForTap = null; 3312 private PerformClick mPerformClick; 3313 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 3314 3315 private UnsetPressedState mUnsetPressedState; 3316 3317 /** 3318 * Whether the long press's action has been invoked. The tap's action is invoked on the 3319 * up event while a long press is invoked as soon as the long press duration is reached, so 3320 * a long press could be performed before the tap is checked, in which case the tap's action 3321 * should not be invoked. 3322 */ 3323 private boolean mHasPerformedLongPress; 3324 3325 /** 3326 * The minimum height of the view. We'll try our best to have the height 3327 * of this view to at least this amount. 3328 */ 3329 @ViewDebug.ExportedProperty(category = "measurement") 3330 private int mMinHeight; 3331 3332 /** 3333 * The minimum width of the view. We'll try our best to have the width 3334 * of this view to at least this amount. 3335 */ 3336 @ViewDebug.ExportedProperty(category = "measurement") 3337 private int mMinWidth; 3338 3339 /** 3340 * The delegate to handle touch events that are physically in this view 3341 * but should be handled by another view. 3342 */ 3343 private TouchDelegate mTouchDelegate = null; 3344 3345 /** 3346 * Solid color to use as a background when creating the drawing cache. Enables 3347 * the cache to use 16 bit bitmaps instead of 32 bit. 3348 */ 3349 private int mDrawingCacheBackgroundColor = 0; 3350 3351 /** 3352 * Special tree observer used when mAttachInfo is null. 3353 */ 3354 private ViewTreeObserver mFloatingTreeObserver; 3355 3356 /** 3357 * Cache the touch slop from the context that created the view. 3358 */ 3359 private int mTouchSlop; 3360 3361 /** 3362 * Object that handles automatic animation of view properties. 3363 */ 3364 private ViewPropertyAnimator mAnimator = null; 3365 3366 /** 3367 * Flag indicating that a drag can cross window boundaries. When 3368 * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called 3369 * with this flag set, all visible applications will be able to participate 3370 * in the drag operation and receive the dragged content. 3371 * 3372 * @hide 3373 */ 3374 public static final int DRAG_FLAG_GLOBAL = 1; 3375 3376 /** 3377 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 3378 */ 3379 private float mVerticalScrollFactor; 3380 3381 /** 3382 * Position of the vertical scroll bar. 3383 */ 3384 private int mVerticalScrollbarPosition; 3385 3386 /** 3387 * Position the scroll bar at the default position as determined by the system. 3388 */ 3389 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 3390 3391 /** 3392 * Position the scroll bar along the left edge. 3393 */ 3394 public static final int SCROLLBAR_POSITION_LEFT = 1; 3395 3396 /** 3397 * Position the scroll bar along the right edge. 3398 */ 3399 public static final int SCROLLBAR_POSITION_RIGHT = 2; 3400 3401 /** 3402 * Indicates that the view does not have a layer. 3403 * 3404 * @see #getLayerType() 3405 * @see #setLayerType(int, android.graphics.Paint) 3406 * @see #LAYER_TYPE_SOFTWARE 3407 * @see #LAYER_TYPE_HARDWARE 3408 */ 3409 public static final int LAYER_TYPE_NONE = 0; 3410 3411 /** 3412 * <p>Indicates that the view has a software layer. A software layer is backed 3413 * by a bitmap and causes the view to be rendered using Android's software 3414 * rendering pipeline, even if hardware acceleration is enabled.</p> 3415 * 3416 * <p>Software layers have various usages:</p> 3417 * <p>When the application is not using hardware acceleration, a software layer 3418 * is useful to apply a specific color filter and/or blending mode and/or 3419 * translucency to a view and all its children.</p> 3420 * <p>When the application is using hardware acceleration, a software layer 3421 * is useful to render drawing primitives not supported by the hardware 3422 * accelerated pipeline. It can also be used to cache a complex view tree 3423 * into a texture and reduce the complexity of drawing operations. For instance, 3424 * when animating a complex view tree with a translation, a software layer can 3425 * be used to render the view tree only once.</p> 3426 * <p>Software layers should be avoided when the affected view tree updates 3427 * often. Every update will require to re-render the software layer, which can 3428 * potentially be slow (particularly when hardware acceleration is turned on 3429 * since the layer will have to be uploaded into a hardware texture after every 3430 * update.)</p> 3431 * 3432 * @see #getLayerType() 3433 * @see #setLayerType(int, android.graphics.Paint) 3434 * @see #LAYER_TYPE_NONE 3435 * @see #LAYER_TYPE_HARDWARE 3436 */ 3437 public static final int LAYER_TYPE_SOFTWARE = 1; 3438 3439 /** 3440 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 3441 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 3442 * OpenGL hardware) and causes the view to be rendered using Android's hardware 3443 * rendering pipeline, but only if hardware acceleration is turned on for the 3444 * view hierarchy. When hardware acceleration is turned off, hardware layers 3445 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 3446 * 3447 * <p>A hardware layer is useful to apply a specific color filter and/or 3448 * blending mode and/or translucency to a view and all its children.</p> 3449 * <p>A hardware layer can be used to cache a complex view tree into a 3450 * texture and reduce the complexity of drawing operations. For instance, 3451 * when animating a complex view tree with a translation, a hardware layer can 3452 * be used to render the view tree only once.</p> 3453 * <p>A hardware layer can also be used to increase the rendering quality when 3454 * rotation transformations are applied on a view. It can also be used to 3455 * prevent potential clipping issues when applying 3D transforms on a view.</p> 3456 * 3457 * @see #getLayerType() 3458 * @see #setLayerType(int, android.graphics.Paint) 3459 * @see #LAYER_TYPE_NONE 3460 * @see #LAYER_TYPE_SOFTWARE 3461 */ 3462 public static final int LAYER_TYPE_HARDWARE = 2; 3463 3464 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 3465 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 3466 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 3467 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 3468 }) 3469 int mLayerType = LAYER_TYPE_NONE; 3470 Paint mLayerPaint; 3471 3472 /** 3473 * Set to true when drawing cache is enabled and cannot be created. 3474 * 3475 * @hide 3476 */ 3477 public boolean mCachingFailed; 3478 private Bitmap mDrawingCache; 3479 private Bitmap mUnscaledDrawingCache; 3480 3481 /** 3482 * RenderNode holding View properties, potentially holding a DisplayList of View content. 3483 * <p> 3484 * When non-null and valid, this is expected to contain an up-to-date copy 3485 * of the View content. Its DisplayList content is cleared on temporary detach and reset on 3486 * cleanup. 3487 */ 3488 final RenderNode mRenderNode; 3489 3490 /** 3491 * Set to true when the view is sending hover accessibility events because it 3492 * is the innermost hovered view. 3493 */ 3494 private boolean mSendingHoverAccessibilityEvents; 3495 3496 /** 3497 * Delegate for injecting accessibility functionality. 3498 */ 3499 AccessibilityDelegate mAccessibilityDelegate; 3500 3501 /** 3502 * The view's overlay layer. Developers get a reference to the overlay via getOverlay() 3503 * and add/remove objects to/from the overlay directly through the Overlay methods. 3504 */ 3505 ViewOverlay mOverlay; 3506 3507 /** 3508 * The currently active parent view for receiving delegated nested scrolling events. 3509 * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared 3510 * by {@link #stopNestedScroll()} at the same point where we clear 3511 * requestDisallowInterceptTouchEvent. 3512 */ 3513 private ViewParent mNestedScrollingParent; 3514 3515 /** 3516 * Consistency verifier for debugging purposes. 3517 * @hide 3518 */ 3519 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 3520 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 3521 new InputEventConsistencyVerifier(this, 0) : null; 3522 3523 private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); 3524 3525 private int[] mTempNestedScrollConsumed; 3526 3527 /** 3528 * Simple constructor to use when creating a view from code. 3529 * 3530 * @param context The Context the view is running in, through which it can 3531 * access the current theme, resources, etc. 3532 */ 3533 public View(Context context) { 3534 mContext = context; 3535 mResources = context != null ? context.getResources() : null; 3536 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED; 3537 // Set some flags defaults 3538 mPrivateFlags2 = 3539 (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) | 3540 (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) | 3541 (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) | 3542 (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) | 3543 (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) | 3544 (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT); 3545 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 3546 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 3547 mUserPaddingStart = UNDEFINED_PADDING; 3548 mUserPaddingEnd = UNDEFINED_PADDING; 3549 mRenderNode = RenderNode.create(getClass().getName()); 3550 3551 if (!sCompatibilityDone && context != null) { 3552 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3553 3554 // Older apps may need this compatibility hack for measurement. 3555 sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1; 3556 3557 // Older apps expect onMeasure() to always be called on a layout pass, regardless 3558 // of whether a layout was requested on that View. 3559 sIgnoreMeasureCache = targetSdkVersion < KITKAT; 3560 3561 // Older apps may need this to ignore the clip bounds 3562 sIgnoreClipBoundsForChildren = targetSdkVersion < L; 3563 3564 sCompatibilityDone = true; 3565 } 3566 } 3567 3568 /** 3569 * Constructor that is called when inflating a view from XML. This is called 3570 * when a view is being constructed from an XML file, supplying attributes 3571 * that were specified in the XML file. This version uses a default style of 3572 * 0, so the only attribute values applied are those in the Context's Theme 3573 * and the given AttributeSet. 3574 * 3575 * <p> 3576 * The method onFinishInflate() will be called after all children have been 3577 * added. 3578 * 3579 * @param context The Context the view is running in, through which it can 3580 * access the current theme, resources, etc. 3581 * @param attrs The attributes of the XML tag that is inflating the view. 3582 * @see #View(Context, AttributeSet, int) 3583 */ 3584 public View(Context context, AttributeSet attrs) { 3585 this(context, attrs, 0); 3586 } 3587 3588 /** 3589 * Perform inflation from XML and apply a class-specific base style from a 3590 * theme attribute. This constructor of View allows subclasses to use their 3591 * own base style when they are inflating. For example, a Button class's 3592 * constructor would call this version of the super class constructor and 3593 * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this 3594 * allows the theme's button style to modify all of the base view attributes 3595 * (in particular its background) as well as the Button class's attributes. 3596 * 3597 * @param context The Context the view is running in, through which it can 3598 * access the current theme, resources, etc. 3599 * @param attrs The attributes of the XML tag that is inflating the view. 3600 * @param defStyleAttr An attribute in the current theme that contains a 3601 * reference to a style resource that supplies default values for 3602 * the view. Can be 0 to not look for defaults. 3603 * @see #View(Context, AttributeSet) 3604 */ 3605 public View(Context context, AttributeSet attrs, int defStyleAttr) { 3606 this(context, attrs, defStyleAttr, 0); 3607 } 3608 3609 /** 3610 * Perform inflation from XML and apply a class-specific base style from a 3611 * theme attribute or style resource. This constructor of View allows 3612 * subclasses to use their own base style when they are inflating. 3613 * <p> 3614 * When determining the final value of a particular attribute, there are 3615 * four inputs that come into play: 3616 * <ol> 3617 * <li>Any attribute values in the given AttributeSet. 3618 * <li>The style resource specified in the AttributeSet (named "style"). 3619 * <li>The default style specified by <var>defStyleAttr</var>. 3620 * <li>The default style specified by <var>defStyleRes</var>. 3621 * <li>The base values in this theme. 3622 * </ol> 3623 * <p> 3624 * Each of these inputs is considered in-order, with the first listed taking 3625 * precedence over the following ones. In other words, if in the 3626 * AttributeSet you have supplied <code><Button * textColor="#ff000000"></code> 3627 * , then the button's text will <em>always</em> be black, regardless of 3628 * what is specified in any of the styles. 3629 * 3630 * @param context The Context the view is running in, through which it can 3631 * access the current theme, resources, etc. 3632 * @param attrs The attributes of the XML tag that is inflating the view. 3633 * @param defStyleAttr An attribute in the current theme that contains a 3634 * reference to a style resource that supplies default values for 3635 * the view. Can be 0 to not look for defaults. 3636 * @param defStyleRes A resource identifier of a style resource that 3637 * supplies default values for the view, used only if 3638 * defStyleAttr is 0 or can not be found in the theme. Can be 0 3639 * to not look for defaults. 3640 * @see #View(Context, AttributeSet, int) 3641 */ 3642 public View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { 3643 this(context); 3644 3645 final TypedArray a = context.obtainStyledAttributes( 3646 attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes); 3647 3648 Drawable background = null; 3649 3650 int leftPadding = -1; 3651 int topPadding = -1; 3652 int rightPadding = -1; 3653 int bottomPadding = -1; 3654 int startPadding = UNDEFINED_PADDING; 3655 int endPadding = UNDEFINED_PADDING; 3656 3657 int padding = -1; 3658 3659 int viewFlagValues = 0; 3660 int viewFlagMasks = 0; 3661 3662 boolean setScrollContainer = false; 3663 3664 int x = 0; 3665 int y = 0; 3666 3667 float tx = 0; 3668 float ty = 0; 3669 float tz = 0; 3670 float elevation = 0; 3671 float rotation = 0; 3672 float rotationX = 0; 3673 float rotationY = 0; 3674 float sx = 1f; 3675 float sy = 1f; 3676 boolean transformSet = false; 3677 3678 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 3679 int overScrollMode = mOverScrollMode; 3680 boolean initializeScrollbars = false; 3681 3682 boolean startPaddingDefined = false; 3683 boolean endPaddingDefined = false; 3684 boolean leftPaddingDefined = false; 3685 boolean rightPaddingDefined = false; 3686 3687 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3688 3689 final int N = a.getIndexCount(); 3690 for (int i = 0; i < N; i++) { 3691 int attr = a.getIndex(i); 3692 switch (attr) { 3693 case com.android.internal.R.styleable.View_background: 3694 background = a.getDrawable(attr); 3695 break; 3696 case com.android.internal.R.styleable.View_padding: 3697 padding = a.getDimensionPixelSize(attr, -1); 3698 mUserPaddingLeftInitial = padding; 3699 mUserPaddingRightInitial = padding; 3700 leftPaddingDefined = true; 3701 rightPaddingDefined = true; 3702 break; 3703 case com.android.internal.R.styleable.View_paddingLeft: 3704 leftPadding = a.getDimensionPixelSize(attr, -1); 3705 mUserPaddingLeftInitial = leftPadding; 3706 leftPaddingDefined = true; 3707 break; 3708 case com.android.internal.R.styleable.View_paddingTop: 3709 topPadding = a.getDimensionPixelSize(attr, -1); 3710 break; 3711 case com.android.internal.R.styleable.View_paddingRight: 3712 rightPadding = a.getDimensionPixelSize(attr, -1); 3713 mUserPaddingRightInitial = rightPadding; 3714 rightPaddingDefined = true; 3715 break; 3716 case com.android.internal.R.styleable.View_paddingBottom: 3717 bottomPadding = a.getDimensionPixelSize(attr, -1); 3718 break; 3719 case com.android.internal.R.styleable.View_paddingStart: 3720 startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3721 startPaddingDefined = (startPadding != UNDEFINED_PADDING); 3722 break; 3723 case com.android.internal.R.styleable.View_paddingEnd: 3724 endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3725 endPaddingDefined = (endPadding != UNDEFINED_PADDING); 3726 break; 3727 case com.android.internal.R.styleable.View_scrollX: 3728 x = a.getDimensionPixelOffset(attr, 0); 3729 break; 3730 case com.android.internal.R.styleable.View_scrollY: 3731 y = a.getDimensionPixelOffset(attr, 0); 3732 break; 3733 case com.android.internal.R.styleable.View_alpha: 3734 setAlpha(a.getFloat(attr, 1f)); 3735 break; 3736 case com.android.internal.R.styleable.View_transformPivotX: 3737 setPivotX(a.getDimensionPixelOffset(attr, 0)); 3738 break; 3739 case com.android.internal.R.styleable.View_transformPivotY: 3740 setPivotY(a.getDimensionPixelOffset(attr, 0)); 3741 break; 3742 case com.android.internal.R.styleable.View_translationX: 3743 tx = a.getDimensionPixelOffset(attr, 0); 3744 transformSet = true; 3745 break; 3746 case com.android.internal.R.styleable.View_translationY: 3747 ty = a.getDimensionPixelOffset(attr, 0); 3748 transformSet = true; 3749 break; 3750 case com.android.internal.R.styleable.View_translationZ: 3751 tz = a.getDimensionPixelOffset(attr, 0); 3752 transformSet = true; 3753 break; 3754 case com.android.internal.R.styleable.View_elevation: 3755 elevation = a.getDimensionPixelOffset(attr, 0); 3756 transformSet = true; 3757 break; 3758 case com.android.internal.R.styleable.View_rotation: 3759 rotation = a.getFloat(attr, 0); 3760 transformSet = true; 3761 break; 3762 case com.android.internal.R.styleable.View_rotationX: 3763 rotationX = a.getFloat(attr, 0); 3764 transformSet = true; 3765 break; 3766 case com.android.internal.R.styleable.View_rotationY: 3767 rotationY = a.getFloat(attr, 0); 3768 transformSet = true; 3769 break; 3770 case com.android.internal.R.styleable.View_scaleX: 3771 sx = a.getFloat(attr, 1f); 3772 transformSet = true; 3773 break; 3774 case com.android.internal.R.styleable.View_scaleY: 3775 sy = a.getFloat(attr, 1f); 3776 transformSet = true; 3777 break; 3778 case com.android.internal.R.styleable.View_id: 3779 mID = a.getResourceId(attr, NO_ID); 3780 break; 3781 case com.android.internal.R.styleable.View_tag: 3782 mTag = a.getText(attr); 3783 break; 3784 case com.android.internal.R.styleable.View_fitsSystemWindows: 3785 if (a.getBoolean(attr, false)) { 3786 viewFlagValues |= FITS_SYSTEM_WINDOWS; 3787 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 3788 } 3789 break; 3790 case com.android.internal.R.styleable.View_focusable: 3791 if (a.getBoolean(attr, false)) { 3792 viewFlagValues |= FOCUSABLE; 3793 viewFlagMasks |= FOCUSABLE_MASK; 3794 } 3795 break; 3796 case com.android.internal.R.styleable.View_focusableInTouchMode: 3797 if (a.getBoolean(attr, false)) { 3798 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 3799 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 3800 } 3801 break; 3802 case com.android.internal.R.styleable.View_clickable: 3803 if (a.getBoolean(attr, false)) { 3804 viewFlagValues |= CLICKABLE; 3805 viewFlagMasks |= CLICKABLE; 3806 } 3807 break; 3808 case com.android.internal.R.styleable.View_longClickable: 3809 if (a.getBoolean(attr, false)) { 3810 viewFlagValues |= LONG_CLICKABLE; 3811 viewFlagMasks |= LONG_CLICKABLE; 3812 } 3813 break; 3814 case com.android.internal.R.styleable.View_saveEnabled: 3815 if (!a.getBoolean(attr, true)) { 3816 viewFlagValues |= SAVE_DISABLED; 3817 viewFlagMasks |= SAVE_DISABLED_MASK; 3818 } 3819 break; 3820 case com.android.internal.R.styleable.View_duplicateParentState: 3821 if (a.getBoolean(attr, false)) { 3822 viewFlagValues |= DUPLICATE_PARENT_STATE; 3823 viewFlagMasks |= DUPLICATE_PARENT_STATE; 3824 } 3825 break; 3826 case com.android.internal.R.styleable.View_visibility: 3827 final int visibility = a.getInt(attr, 0); 3828 if (visibility != 0) { 3829 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 3830 viewFlagMasks |= VISIBILITY_MASK; 3831 } 3832 break; 3833 case com.android.internal.R.styleable.View_layoutDirection: 3834 // Clear any layout direction flags (included resolved bits) already set 3835 mPrivateFlags2 &= 3836 ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK); 3837 // Set the layout direction flags depending on the value of the attribute 3838 final int layoutDirection = a.getInt(attr, -1); 3839 final int value = (layoutDirection != -1) ? 3840 LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT; 3841 mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT); 3842 break; 3843 case com.android.internal.R.styleable.View_drawingCacheQuality: 3844 final int cacheQuality = a.getInt(attr, 0); 3845 if (cacheQuality != 0) { 3846 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 3847 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 3848 } 3849 break; 3850 case com.android.internal.R.styleable.View_contentDescription: 3851 setContentDescription(a.getString(attr)); 3852 break; 3853 case com.android.internal.R.styleable.View_labelFor: 3854 setLabelFor(a.getResourceId(attr, NO_ID)); 3855 break; 3856 case com.android.internal.R.styleable.View_soundEffectsEnabled: 3857 if (!a.getBoolean(attr, true)) { 3858 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 3859 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 3860 } 3861 break; 3862 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 3863 if (!a.getBoolean(attr, true)) { 3864 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 3865 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 3866 } 3867 break; 3868 case R.styleable.View_scrollbars: 3869 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 3870 if (scrollbars != SCROLLBARS_NONE) { 3871 viewFlagValues |= scrollbars; 3872 viewFlagMasks |= SCROLLBARS_MASK; 3873 initializeScrollbars = true; 3874 } 3875 break; 3876 //noinspection deprecation 3877 case R.styleable.View_fadingEdge: 3878 if (targetSdkVersion >= ICE_CREAM_SANDWICH) { 3879 // Ignore the attribute starting with ICS 3880 break; 3881 } 3882 // With builds < ICS, fall through and apply fading edges 3883 case R.styleable.View_requiresFadingEdge: 3884 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 3885 if (fadingEdge != FADING_EDGE_NONE) { 3886 viewFlagValues |= fadingEdge; 3887 viewFlagMasks |= FADING_EDGE_MASK; 3888 initializeFadingEdgeInternal(a); 3889 } 3890 break; 3891 case R.styleable.View_scrollbarStyle: 3892 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 3893 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3894 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 3895 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 3896 } 3897 break; 3898 case R.styleable.View_isScrollContainer: 3899 setScrollContainer = true; 3900 if (a.getBoolean(attr, false)) { 3901 setScrollContainer(true); 3902 } 3903 break; 3904 case com.android.internal.R.styleable.View_keepScreenOn: 3905 if (a.getBoolean(attr, false)) { 3906 viewFlagValues |= KEEP_SCREEN_ON; 3907 viewFlagMasks |= KEEP_SCREEN_ON; 3908 } 3909 break; 3910 case R.styleable.View_filterTouchesWhenObscured: 3911 if (a.getBoolean(attr, false)) { 3912 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 3913 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 3914 } 3915 break; 3916 case R.styleable.View_nextFocusLeft: 3917 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 3918 break; 3919 case R.styleable.View_nextFocusRight: 3920 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 3921 break; 3922 case R.styleable.View_nextFocusUp: 3923 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 3924 break; 3925 case R.styleable.View_nextFocusDown: 3926 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 3927 break; 3928 case R.styleable.View_nextFocusForward: 3929 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 3930 break; 3931 case R.styleable.View_minWidth: 3932 mMinWidth = a.getDimensionPixelSize(attr, 0); 3933 break; 3934 case R.styleable.View_minHeight: 3935 mMinHeight = a.getDimensionPixelSize(attr, 0); 3936 break; 3937 case R.styleable.View_onClick: 3938 if (context.isRestricted()) { 3939 throw new IllegalStateException("The android:onClick attribute cannot " 3940 + "be used within a restricted context"); 3941 } 3942 3943 final String handlerName = a.getString(attr); 3944 if (handlerName != null) { 3945 setOnClickListener(new OnClickListener() { 3946 private Method mHandler; 3947 3948 public void onClick(View v) { 3949 if (mHandler == null) { 3950 try { 3951 mHandler = getContext().getClass().getMethod(handlerName, 3952 View.class); 3953 } catch (NoSuchMethodException e) { 3954 int id = getId(); 3955 String idText = id == NO_ID ? "" : " with id '" 3956 + getContext().getResources().getResourceEntryName( 3957 id) + "'"; 3958 throw new IllegalStateException("Could not find a method " + 3959 handlerName + "(View) in the activity " 3960 + getContext().getClass() + " for onClick handler" 3961 + " on view " + View.this.getClass() + idText, e); 3962 } 3963 } 3964 3965 try { 3966 mHandler.invoke(getContext(), View.this); 3967 } catch (IllegalAccessException e) { 3968 throw new IllegalStateException("Could not execute non " 3969 + "public method of the activity", e); 3970 } catch (InvocationTargetException e) { 3971 throw new IllegalStateException("Could not execute " 3972 + "method of the activity", e); 3973 } 3974 } 3975 }); 3976 } 3977 break; 3978 case R.styleable.View_overScrollMode: 3979 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 3980 break; 3981 case R.styleable.View_verticalScrollbarPosition: 3982 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 3983 break; 3984 case R.styleable.View_layerType: 3985 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 3986 break; 3987 case R.styleable.View_textDirection: 3988 // Clear any text direction flag already set 3989 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 3990 // Set the text direction flags depending on the value of the attribute 3991 final int textDirection = a.getInt(attr, -1); 3992 if (textDirection != -1) { 3993 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection]; 3994 } 3995 break; 3996 case R.styleable.View_textAlignment: 3997 // Clear any text alignment flag already set 3998 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 3999 // Set the text alignment flag depending on the value of the attribute 4000 final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT); 4001 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment]; 4002 break; 4003 case R.styleable.View_importantForAccessibility: 4004 setImportantForAccessibility(a.getInt(attr, 4005 IMPORTANT_FOR_ACCESSIBILITY_DEFAULT)); 4006 break; 4007 case R.styleable.View_accessibilityLiveRegion: 4008 setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT)); 4009 break; 4010 case R.styleable.View_transitionName: 4011 setTransitionName(a.getString(attr)); 4012 break; 4013 case R.styleable.View_nestedScrollingEnabled: 4014 setNestedScrollingEnabled(a.getBoolean(attr, false)); 4015 break; 4016 case R.styleable.View_stateListAnimator: 4017 setStateListAnimator(AnimatorInflater.loadStateListAnimator(context, 4018 a.getResourceId(attr, 0))); 4019 break; 4020 case R.styleable.View_backgroundTint: 4021 // This will get applied later during setBackground(). 4022 mBackgroundTint = a.getColorStateList(R.styleable.View_backgroundTint); 4023 mHasBackgroundTint = true; 4024 break; 4025 case R.styleable.View_backgroundTintMode: 4026 // This will get applied later during setBackground(). 4027 mBackgroundTintMode = Drawable.parseTintMode(a.getInt( 4028 R.styleable.View_backgroundTintMode, -1), mBackgroundTintMode); 4029 break; 4030 } 4031 } 4032 4033 setOverScrollMode(overScrollMode); 4034 4035 // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet 4036 // the resolved layout direction). Those cached values will be used later during padding 4037 // resolution. 4038 mUserPaddingStart = startPadding; 4039 mUserPaddingEnd = endPadding; 4040 4041 if (background != null) { 4042 setBackground(background); 4043 } 4044 4045 // setBackground above will record that padding is currently provided by the background. 4046 // If we have padding specified via xml, record that here instead and use it. 4047 mLeftPaddingDefined = leftPaddingDefined; 4048 mRightPaddingDefined = rightPaddingDefined; 4049 4050 if (padding >= 0) { 4051 leftPadding = padding; 4052 topPadding = padding; 4053 rightPadding = padding; 4054 bottomPadding = padding; 4055 mUserPaddingLeftInitial = padding; 4056 mUserPaddingRightInitial = padding; 4057 } 4058 4059 if (isRtlCompatibilityMode()) { 4060 // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case. 4061 // left / right padding are used if defined (meaning here nothing to do). If they are not 4062 // defined and start / end padding are defined (e.g. in Frameworks resources), then we use 4063 // start / end and resolve them as left / right (layout direction is not taken into account). 4064 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4065 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4066 // defined. 4067 if (!mLeftPaddingDefined && startPaddingDefined) { 4068 leftPadding = startPadding; 4069 } 4070 mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial; 4071 if (!mRightPaddingDefined && endPaddingDefined) { 4072 rightPadding = endPadding; 4073 } 4074 mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial; 4075 } else { 4076 // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right 4077 // values defined. Otherwise, left /right values are used. 4078 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4079 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4080 // defined. 4081 final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined; 4082 4083 if (mLeftPaddingDefined && !hasRelativePadding) { 4084 mUserPaddingLeftInitial = leftPadding; 4085 } 4086 if (mRightPaddingDefined && !hasRelativePadding) { 4087 mUserPaddingRightInitial = rightPadding; 4088 } 4089 } 4090 4091 internalSetPadding( 4092 mUserPaddingLeftInitial, 4093 topPadding >= 0 ? topPadding : mPaddingTop, 4094 mUserPaddingRightInitial, 4095 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 4096 4097 if (viewFlagMasks != 0) { 4098 setFlags(viewFlagValues, viewFlagMasks); 4099 } 4100 4101 if (initializeScrollbars) { 4102 initializeScrollbarsInternal(a); 4103 } 4104 4105 a.recycle(); 4106 4107 // Needs to be called after mViewFlags is set 4108 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 4109 recomputePadding(); 4110 } 4111 4112 if (x != 0 || y != 0) { 4113 scrollTo(x, y); 4114 } 4115 4116 if (transformSet) { 4117 setTranslationX(tx); 4118 setTranslationY(ty); 4119 setTranslationZ(tz); 4120 setElevation(elevation); 4121 setRotation(rotation); 4122 setRotationX(rotationX); 4123 setRotationY(rotationY); 4124 setScaleX(sx); 4125 setScaleY(sy); 4126 } 4127 4128 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 4129 setScrollContainer(true); 4130 } 4131 4132 computeOpaqueFlags(); 4133 } 4134 4135 /** 4136 * Non-public constructor for use in testing 4137 */ 4138 View() { 4139 mResources = null; 4140 mRenderNode = RenderNode.create(getClass().getName()); 4141 } 4142 4143 public String toString() { 4144 StringBuilder out = new StringBuilder(128); 4145 out.append(getClass().getName()); 4146 out.append('{'); 4147 out.append(Integer.toHexString(System.identityHashCode(this))); 4148 out.append(' '); 4149 switch (mViewFlags&VISIBILITY_MASK) { 4150 case VISIBLE: out.append('V'); break; 4151 case INVISIBLE: out.append('I'); break; 4152 case GONE: out.append('G'); break; 4153 default: out.append('.'); break; 4154 } 4155 out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.'); 4156 out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.'); 4157 out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D'); 4158 out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.'); 4159 out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.'); 4160 out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.'); 4161 out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.'); 4162 out.append(' '); 4163 out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.'); 4164 out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.'); 4165 out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.'); 4166 if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) { 4167 out.append('p'); 4168 } else { 4169 out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.'); 4170 } 4171 out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.'); 4172 out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.'); 4173 out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.'); 4174 out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.'); 4175 out.append(' '); 4176 out.append(mLeft); 4177 out.append(','); 4178 out.append(mTop); 4179 out.append('-'); 4180 out.append(mRight); 4181 out.append(','); 4182 out.append(mBottom); 4183 final int id = getId(); 4184 if (id != NO_ID) { 4185 out.append(" #"); 4186 out.append(Integer.toHexString(id)); 4187 final Resources r = mResources; 4188 if (Resources.resourceHasPackage(id) && r != null) { 4189 try { 4190 String pkgname; 4191 switch (id&0xff000000) { 4192 case 0x7f000000: 4193 pkgname="app"; 4194 break; 4195 case 0x01000000: 4196 pkgname="android"; 4197 break; 4198 default: 4199 pkgname = r.getResourcePackageName(id); 4200 break; 4201 } 4202 String typename = r.getResourceTypeName(id); 4203 String entryname = r.getResourceEntryName(id); 4204 out.append(" "); 4205 out.append(pkgname); 4206 out.append(":"); 4207 out.append(typename); 4208 out.append("/"); 4209 out.append(entryname); 4210 } catch (Resources.NotFoundException e) { 4211 } 4212 } 4213 } 4214 out.append("}"); 4215 return out.toString(); 4216 } 4217 4218 /** 4219 * <p> 4220 * Initializes the fading edges from a given set of styled attributes. This 4221 * method should be called by subclasses that need fading edges and when an 4222 * instance of these subclasses is created programmatically rather than 4223 * being inflated from XML. This method is automatically called when the XML 4224 * is inflated. 4225 * </p> 4226 * 4227 * @param a the styled attributes set to initialize the fading edges from 4228 */ 4229 protected void initializeFadingEdge(TypedArray a) { 4230 // This method probably shouldn't have been included in the SDK to begin with. 4231 // It relies on 'a' having been initialized using an attribute filter array that is 4232 // not publicly available to the SDK. The old method has been renamed 4233 // to initializeFadingEdgeInternal and hidden for framework use only; 4234 // this one initializes using defaults to make it safe to call for apps. 4235 4236 TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View); 4237 4238 initializeFadingEdgeInternal(arr); 4239 4240 arr.recycle(); 4241 } 4242 4243 /** 4244 * <p> 4245 * Initializes the fading edges from a given set of styled attributes. This 4246 * method should be called by subclasses that need fading edges and when an 4247 * instance of these subclasses is created programmatically rather than 4248 * being inflated from XML. This method is automatically called when the XML 4249 * is inflated. 4250 * </p> 4251 * 4252 * @param a the styled attributes set to initialize the fading edges from 4253 * @hide This is the real method; the public one is shimmed to be safe to call from apps. 4254 */ 4255 protected void initializeFadingEdgeInternal(TypedArray a) { 4256 initScrollCache(); 4257 4258 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 4259 R.styleable.View_fadingEdgeLength, 4260 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 4261 } 4262 4263 /** 4264 * Returns the size of the vertical faded edges used to indicate that more 4265 * content in this view is visible. 4266 * 4267 * @return The size in pixels of the vertical faded edge or 0 if vertical 4268 * faded edges are not enabled for this view. 4269 * @attr ref android.R.styleable#View_fadingEdgeLength 4270 */ 4271 public int getVerticalFadingEdgeLength() { 4272 if (isVerticalFadingEdgeEnabled()) { 4273 ScrollabilityCache cache = mScrollCache; 4274 if (cache != null) { 4275 return cache.fadingEdgeLength; 4276 } 4277 } 4278 return 0; 4279 } 4280 4281 /** 4282 * Set the size of the faded edge used to indicate that more content in this 4283 * view is available. Will not change whether the fading edge is enabled; use 4284 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 4285 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 4286 * for the vertical or horizontal fading edges. 4287 * 4288 * @param length The size in pixels of the faded edge used to indicate that more 4289 * content in this view is visible. 4290 */ 4291 public void setFadingEdgeLength(int length) { 4292 initScrollCache(); 4293 mScrollCache.fadingEdgeLength = length; 4294 } 4295 4296 /** 4297 * Returns the size of the horizontal faded edges used to indicate that more 4298 * content in this view is visible. 4299 * 4300 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 4301 * faded edges are not enabled for this view. 4302 * @attr ref android.R.styleable#View_fadingEdgeLength 4303 */ 4304 public int getHorizontalFadingEdgeLength() { 4305 if (isHorizontalFadingEdgeEnabled()) { 4306 ScrollabilityCache cache = mScrollCache; 4307 if (cache != null) { 4308 return cache.fadingEdgeLength; 4309 } 4310 } 4311 return 0; 4312 } 4313 4314 /** 4315 * Returns the width of the vertical scrollbar. 4316 * 4317 * @return The width in pixels of the vertical scrollbar or 0 if there 4318 * is no vertical scrollbar. 4319 */ 4320 public int getVerticalScrollbarWidth() { 4321 ScrollabilityCache cache = mScrollCache; 4322 if (cache != null) { 4323 ScrollBarDrawable scrollBar = cache.scrollBar; 4324 if (scrollBar != null) { 4325 int size = scrollBar.getSize(true); 4326 if (size <= 0) { 4327 size = cache.scrollBarSize; 4328 } 4329 return size; 4330 } 4331 return 0; 4332 } 4333 return 0; 4334 } 4335 4336 /** 4337 * Returns the height of the horizontal scrollbar. 4338 * 4339 * @return The height in pixels of the horizontal scrollbar or 0 if 4340 * there is no horizontal scrollbar. 4341 */ 4342 protected int getHorizontalScrollbarHeight() { 4343 ScrollabilityCache cache = mScrollCache; 4344 if (cache != null) { 4345 ScrollBarDrawable scrollBar = cache.scrollBar; 4346 if (scrollBar != null) { 4347 int size = scrollBar.getSize(false); 4348 if (size <= 0) { 4349 size = cache.scrollBarSize; 4350 } 4351 return size; 4352 } 4353 return 0; 4354 } 4355 return 0; 4356 } 4357 4358 /** 4359 * <p> 4360 * Initializes the scrollbars from a given set of styled attributes. This 4361 * method should be called by subclasses that need scrollbars and when an 4362 * instance of these subclasses is created programmatically rather than 4363 * being inflated from XML. This method is automatically called when the XML 4364 * is inflated. 4365 * </p> 4366 * 4367 * @param a the styled attributes set to initialize the scrollbars from 4368 */ 4369 protected void initializeScrollbars(TypedArray a) { 4370 // It's not safe to use this method from apps. The parameter 'a' must have been obtained 4371 // using the View filter array which is not available to the SDK. As such, internal 4372 // framework usage now uses initializeScrollbarsInternal and we grab a default 4373 // TypedArray with the right filter instead here. 4374 TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View); 4375 4376 initializeScrollbarsInternal(arr); 4377 4378 // We ignored the method parameter. Recycle the one we actually did use. 4379 arr.recycle(); 4380 } 4381 4382 /** 4383 * <p> 4384 * Initializes the scrollbars from a given set of styled attributes. This 4385 * method should be called by subclasses that need scrollbars and when an 4386 * instance of these subclasses is created programmatically rather than 4387 * being inflated from XML. This method is automatically called when the XML 4388 * is inflated. 4389 * </p> 4390 * 4391 * @param a the styled attributes set to initialize the scrollbars from 4392 * @hide 4393 */ 4394 protected void initializeScrollbarsInternal(TypedArray a) { 4395 initScrollCache(); 4396 4397 final ScrollabilityCache scrollabilityCache = mScrollCache; 4398 4399 if (scrollabilityCache.scrollBar == null) { 4400 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 4401 } 4402 4403 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 4404 4405 if (!fadeScrollbars) { 4406 scrollabilityCache.state = ScrollabilityCache.ON; 4407 } 4408 scrollabilityCache.fadeScrollBars = fadeScrollbars; 4409 4410 4411 scrollabilityCache.scrollBarFadeDuration = a.getInt( 4412 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 4413 .getScrollBarFadeDuration()); 4414 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 4415 R.styleable.View_scrollbarDefaultDelayBeforeFade, 4416 ViewConfiguration.getScrollDefaultDelay()); 4417 4418 4419 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 4420 com.android.internal.R.styleable.View_scrollbarSize, 4421 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 4422 4423 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 4424 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 4425 4426 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 4427 if (thumb != null) { 4428 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 4429 } 4430 4431 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 4432 false); 4433 if (alwaysDraw) { 4434 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 4435 } 4436 4437 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 4438 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 4439 4440 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 4441 if (thumb != null) { 4442 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 4443 } 4444 4445 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 4446 false); 4447 if (alwaysDraw) { 4448 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 4449 } 4450 4451 // Apply layout direction to the new Drawables if needed 4452 final int layoutDirection = getLayoutDirection(); 4453 if (track != null) { 4454 track.setLayoutDirection(layoutDirection); 4455 } 4456 if (thumb != null) { 4457 thumb.setLayoutDirection(layoutDirection); 4458 } 4459 4460 // Re-apply user/background padding so that scrollbar(s) get added 4461 resolvePadding(); 4462 } 4463 4464 /** 4465 * <p> 4466 * Initalizes the scrollability cache if necessary. 4467 * </p> 4468 */ 4469 private void initScrollCache() { 4470 if (mScrollCache == null) { 4471 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 4472 } 4473 } 4474 4475 private ScrollabilityCache getScrollCache() { 4476 initScrollCache(); 4477 return mScrollCache; 4478 } 4479 4480 /** 4481 * Set the position of the vertical scroll bar. Should be one of 4482 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 4483 * {@link #SCROLLBAR_POSITION_RIGHT}. 4484 * 4485 * @param position Where the vertical scroll bar should be positioned. 4486 */ 4487 public void setVerticalScrollbarPosition(int position) { 4488 if (mVerticalScrollbarPosition != position) { 4489 mVerticalScrollbarPosition = position; 4490 computeOpaqueFlags(); 4491 resolvePadding(); 4492 } 4493 } 4494 4495 /** 4496 * @return The position where the vertical scroll bar will show, if applicable. 4497 * @see #setVerticalScrollbarPosition(int) 4498 */ 4499 public int getVerticalScrollbarPosition() { 4500 return mVerticalScrollbarPosition; 4501 } 4502 4503 ListenerInfo getListenerInfo() { 4504 if (mListenerInfo != null) { 4505 return mListenerInfo; 4506 } 4507 mListenerInfo = new ListenerInfo(); 4508 return mListenerInfo; 4509 } 4510 4511 /** 4512 * Register a callback to be invoked when focus of this view changed. 4513 * 4514 * @param l The callback that will run. 4515 */ 4516 public void setOnFocusChangeListener(OnFocusChangeListener l) { 4517 getListenerInfo().mOnFocusChangeListener = l; 4518 } 4519 4520 /** 4521 * Add a listener that will be called when the bounds of the view change due to 4522 * layout processing. 4523 * 4524 * @param listener The listener that will be called when layout bounds change. 4525 */ 4526 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 4527 ListenerInfo li = getListenerInfo(); 4528 if (li.mOnLayoutChangeListeners == null) { 4529 li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 4530 } 4531 if (!li.mOnLayoutChangeListeners.contains(listener)) { 4532 li.mOnLayoutChangeListeners.add(listener); 4533 } 4534 } 4535 4536 /** 4537 * Remove a listener for layout changes. 4538 * 4539 * @param listener The listener for layout bounds change. 4540 */ 4541 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 4542 ListenerInfo li = mListenerInfo; 4543 if (li == null || li.mOnLayoutChangeListeners == null) { 4544 return; 4545 } 4546 li.mOnLayoutChangeListeners.remove(listener); 4547 } 4548 4549 /** 4550 * Add a listener for attach state changes. 4551 * 4552 * This listener will be called whenever this view is attached or detached 4553 * from a window. Remove the listener using 4554 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 4555 * 4556 * @param listener Listener to attach 4557 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 4558 */ 4559 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4560 ListenerInfo li = getListenerInfo(); 4561 if (li.mOnAttachStateChangeListeners == null) { 4562 li.mOnAttachStateChangeListeners 4563 = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 4564 } 4565 li.mOnAttachStateChangeListeners.add(listener); 4566 } 4567 4568 /** 4569 * Remove a listener for attach state changes. The listener will receive no further 4570 * notification of window attach/detach events. 4571 * 4572 * @param listener Listener to remove 4573 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 4574 */ 4575 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4576 ListenerInfo li = mListenerInfo; 4577 if (li == null || li.mOnAttachStateChangeListeners == null) { 4578 return; 4579 } 4580 li.mOnAttachStateChangeListeners.remove(listener); 4581 } 4582 4583 /** 4584 * Returns the focus-change callback registered for this view. 4585 * 4586 * @return The callback, or null if one is not registered. 4587 */ 4588 public OnFocusChangeListener getOnFocusChangeListener() { 4589 ListenerInfo li = mListenerInfo; 4590 return li != null ? li.mOnFocusChangeListener : null; 4591 } 4592 4593 /** 4594 * Register a callback to be invoked when this view is clicked. If this view is not 4595 * clickable, it becomes clickable. 4596 * 4597 * @param l The callback that will run 4598 * 4599 * @see #setClickable(boolean) 4600 */ 4601 public void setOnClickListener(OnClickListener l) { 4602 if (!isClickable()) { 4603 setClickable(true); 4604 } 4605 getListenerInfo().mOnClickListener = l; 4606 } 4607 4608 /** 4609 * Return whether this view has an attached OnClickListener. Returns 4610 * true if there is a listener, false if there is none. 4611 */ 4612 public boolean hasOnClickListeners() { 4613 ListenerInfo li = mListenerInfo; 4614 return (li != null && li.mOnClickListener != null); 4615 } 4616 4617 /** 4618 * Register a callback to be invoked when this view is clicked and held. If this view is not 4619 * long clickable, it becomes long clickable. 4620 * 4621 * @param l The callback that will run 4622 * 4623 * @see #setLongClickable(boolean) 4624 */ 4625 public void setOnLongClickListener(OnLongClickListener l) { 4626 if (!isLongClickable()) { 4627 setLongClickable(true); 4628 } 4629 getListenerInfo().mOnLongClickListener = l; 4630 } 4631 4632 /** 4633 * Register a callback to be invoked when the context menu for this view is 4634 * being built. If this view is not long clickable, it becomes long clickable. 4635 * 4636 * @param l The callback that will run 4637 * 4638 */ 4639 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 4640 if (!isLongClickable()) { 4641 setLongClickable(true); 4642 } 4643 getListenerInfo().mOnCreateContextMenuListener = l; 4644 } 4645 4646 /** 4647 * Call this view's OnClickListener, if it is defined. Performs all normal 4648 * actions associated with clicking: reporting accessibility event, playing 4649 * a sound, etc. 4650 * 4651 * @return True there was an assigned OnClickListener that was called, false 4652 * otherwise is returned. 4653 */ 4654 public boolean performClick() { 4655 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 4656 4657 ListenerInfo li = mListenerInfo; 4658 if (li != null && li.mOnClickListener != null) { 4659 playSoundEffect(SoundEffectConstants.CLICK); 4660 li.mOnClickListener.onClick(this); 4661 return true; 4662 } 4663 4664 return false; 4665 } 4666 4667 /** 4668 * Directly call any attached OnClickListener. Unlike {@link #performClick()}, 4669 * this only calls the listener, and does not do any associated clicking 4670 * actions like reporting an accessibility event. 4671 * 4672 * @return True there was an assigned OnClickListener that was called, false 4673 * otherwise is returned. 4674 */ 4675 public boolean callOnClick() { 4676 ListenerInfo li = mListenerInfo; 4677 if (li != null && li.mOnClickListener != null) { 4678 li.mOnClickListener.onClick(this); 4679 return true; 4680 } 4681 return false; 4682 } 4683 4684 /** 4685 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the 4686 * OnLongClickListener did not consume the event. 4687 * 4688 * @return True if one of the above receivers consumed the event, false otherwise. 4689 */ 4690 public boolean performLongClick() { 4691 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 4692 4693 boolean handled = false; 4694 ListenerInfo li = mListenerInfo; 4695 if (li != null && li.mOnLongClickListener != null) { 4696 handled = li.mOnLongClickListener.onLongClick(View.this); 4697 } 4698 if (!handled) { 4699 handled = showContextMenu(); 4700 } 4701 if (handled) { 4702 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 4703 } 4704 return handled; 4705 } 4706 4707 /** 4708 * Performs button-related actions during a touch down event. 4709 * 4710 * @param event The event. 4711 * @return True if the down was consumed. 4712 * 4713 * @hide 4714 */ 4715 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 4716 if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 4717 if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) { 4718 return true; 4719 } 4720 } 4721 return false; 4722 } 4723 4724 /** 4725 * Bring up the context menu for this view. 4726 * 4727 * @return Whether a context menu was displayed. 4728 */ 4729 public boolean showContextMenu() { 4730 return getParent().showContextMenuForChild(this); 4731 } 4732 4733 /** 4734 * Bring up the context menu for this view, referring to the item under the specified point. 4735 * 4736 * @param x The referenced x coordinate. 4737 * @param y The referenced y coordinate. 4738 * @param metaState The keyboard modifiers that were pressed. 4739 * @return Whether a context menu was displayed. 4740 * 4741 * @hide 4742 */ 4743 public boolean showContextMenu(float x, float y, int metaState) { 4744 return showContextMenu(); 4745 } 4746 4747 /** 4748 * Start an action mode. 4749 * 4750 * @param callback Callback that will control the lifecycle of the action mode 4751 * @return The new action mode if it is started, null otherwise 4752 * 4753 * @see ActionMode 4754 */ 4755 public ActionMode startActionMode(ActionMode.Callback callback) { 4756 ViewParent parent = getParent(); 4757 if (parent == null) return null; 4758 return parent.startActionModeForChild(this, callback); 4759 } 4760 4761 /** 4762 * Register a callback to be invoked when a hardware key is pressed in this view. 4763 * Key presses in software input methods will generally not trigger the methods of 4764 * this listener. 4765 * @param l the key listener to attach to this view 4766 */ 4767 public void setOnKeyListener(OnKeyListener l) { 4768 getListenerInfo().mOnKeyListener = l; 4769 } 4770 4771 /** 4772 * Register a callback to be invoked when a touch event is sent to this view. 4773 * @param l the touch listener to attach to this view 4774 */ 4775 public void setOnTouchListener(OnTouchListener l) { 4776 getListenerInfo().mOnTouchListener = l; 4777 } 4778 4779 /** 4780 * Register a callback to be invoked when a generic motion event is sent to this view. 4781 * @param l the generic motion listener to attach to this view 4782 */ 4783 public void setOnGenericMotionListener(OnGenericMotionListener l) { 4784 getListenerInfo().mOnGenericMotionListener = l; 4785 } 4786 4787 /** 4788 * Register a callback to be invoked when a hover event is sent to this view. 4789 * @param l the hover listener to attach to this view 4790 */ 4791 public void setOnHoverListener(OnHoverListener l) { 4792 getListenerInfo().mOnHoverListener = l; 4793 } 4794 4795 /** 4796 * Register a drag event listener callback object for this View. The parameter is 4797 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 4798 * View, the system calls the 4799 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 4800 * @param l An implementation of {@link android.view.View.OnDragListener}. 4801 */ 4802 public void setOnDragListener(OnDragListener l) { 4803 getListenerInfo().mOnDragListener = l; 4804 } 4805 4806 /** 4807 * Give this view focus. This will cause 4808 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 4809 * 4810 * Note: this does not check whether this {@link View} should get focus, it just 4811 * gives it focus no matter what. It should only be called internally by framework 4812 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 4813 * 4814 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 4815 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 4816 * focus moved when requestFocus() is called. It may not always 4817 * apply, in which case use the default View.FOCUS_DOWN. 4818 * @param previouslyFocusedRect The rectangle of the view that had focus 4819 * prior in this View's coordinate system. 4820 */ 4821 void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) { 4822 if (DBG) { 4823 System.out.println(this + " requestFocus()"); 4824 } 4825 4826 if ((mPrivateFlags & PFLAG_FOCUSED) == 0) { 4827 mPrivateFlags |= PFLAG_FOCUSED; 4828 4829 View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null; 4830 4831 if (mParent != null) { 4832 mParent.requestChildFocus(this, this); 4833 } 4834 4835 if (mAttachInfo != null) { 4836 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this); 4837 } 4838 4839 onFocusChanged(true, direction, previouslyFocusedRect); 4840 manageFocusHotspot(true, oldFocus); 4841 refreshDrawableState(); 4842 } 4843 } 4844 4845 /** 4846 * Forwards focus information to the background drawable, if necessary. When 4847 * the view is gaining focus, <code>v</code> is the previous focus holder. 4848 * When the view is losing focus, <code>v</code> is the next focus holder. 4849 * 4850 * @param focused whether this view is focused 4851 * @param v previous or the next focus holder, or null if none 4852 */ 4853 private void manageFocusHotspot(boolean focused, View v) { 4854 final Rect r = new Rect(); 4855 if (v != null && mAttachInfo != null) { 4856 v.getHotspotBounds(r); 4857 final int[] location = mAttachInfo.mTmpLocation; 4858 getLocationOnScreen(location); 4859 r.offset(-location[0], -location[1]); 4860 } else { 4861 r.set(0, 0, mRight - mLeft, mBottom - mTop); 4862 } 4863 4864 final float x = r.exactCenterX(); 4865 final float y = r.exactCenterY(); 4866 drawableHotspotChanged(x, y); 4867 } 4868 4869 /** 4870 * Populates <code>outRect</code> with the hotspot bounds. By default, 4871 * the hotspot bounds are identical to the screen bounds. 4872 * 4873 * @param outRect rect to populate with hotspot bounds 4874 * @hide Only for internal use by views and widgets. 4875 */ 4876 public void getHotspotBounds(Rect outRect) { 4877 final Drawable background = getBackground(); 4878 if (background != null) { 4879 background.getHotspotBounds(outRect); 4880 } else { 4881 getBoundsOnScreen(outRect); 4882 } 4883 } 4884 4885 /** 4886 * Request that a rectangle of this view be visible on the screen, 4887 * scrolling if necessary just enough. 4888 * 4889 * <p>A View should call this if it maintains some notion of which part 4890 * of its content is interesting. For example, a text editing view 4891 * should call this when its cursor moves. 4892 * 4893 * @param rectangle The rectangle. 4894 * @return Whether any parent scrolled. 4895 */ 4896 public boolean requestRectangleOnScreen(Rect rectangle) { 4897 return requestRectangleOnScreen(rectangle, false); 4898 } 4899 4900 /** 4901 * Request that a rectangle of this view be visible on the screen, 4902 * scrolling if necessary just enough. 4903 * 4904 * <p>A View should call this if it maintains some notion of which part 4905 * of its content is interesting. For example, a text editing view 4906 * should call this when its cursor moves. 4907 * 4908 * <p>When <code>immediate</code> is set to true, scrolling will not be 4909 * animated. 4910 * 4911 * @param rectangle The rectangle. 4912 * @param immediate True to forbid animated scrolling, false otherwise 4913 * @return Whether any parent scrolled. 4914 */ 4915 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 4916 if (mParent == null) { 4917 return false; 4918 } 4919 4920 View child = this; 4921 4922 RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF(); 4923 position.set(rectangle); 4924 4925 ViewParent parent = mParent; 4926 boolean scrolled = false; 4927 while (parent != null) { 4928 rectangle.set((int) position.left, (int) position.top, 4929 (int) position.right, (int) position.bottom); 4930 4931 scrolled |= parent.requestChildRectangleOnScreen(child, 4932 rectangle, immediate); 4933 4934 if (!child.hasIdentityMatrix()) { 4935 child.getMatrix().mapRect(position); 4936 } 4937 4938 position.offset(child.mLeft, child.mTop); 4939 4940 if (!(parent instanceof View)) { 4941 break; 4942 } 4943 4944 View parentView = (View) parent; 4945 4946 position.offset(-parentView.getScrollX(), -parentView.getScrollY()); 4947 4948 child = parentView; 4949 parent = child.getParent(); 4950 } 4951 4952 return scrolled; 4953 } 4954 4955 /** 4956 * Called when this view wants to give up focus. If focus is cleared 4957 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called. 4958 * <p> 4959 * <strong>Note:</strong> When a View clears focus the framework is trying 4960 * to give focus to the first focusable View from the top. Hence, if this 4961 * View is the first from the top that can take focus, then all callbacks 4962 * related to clearing focus will be invoked after wich the framework will 4963 * give focus to this view. 4964 * </p> 4965 */ 4966 public void clearFocus() { 4967 if (DBG) { 4968 System.out.println(this + " clearFocus()"); 4969 } 4970 4971 clearFocusInternal(null, true, true); 4972 } 4973 4974 /** 4975 * Clears focus from the view, optionally propagating the change up through 4976 * the parent hierarchy and requesting that the root view place new focus. 4977 * 4978 * @param propagate whether to propagate the change up through the parent 4979 * hierarchy 4980 * @param refocus when propagate is true, specifies whether to request the 4981 * root view place new focus 4982 */ 4983 void clearFocusInternal(View focused, boolean propagate, boolean refocus) { 4984 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 4985 mPrivateFlags &= ~PFLAG_FOCUSED; 4986 4987 if (propagate && mParent != null) { 4988 mParent.clearChildFocus(this); 4989 } 4990 4991 onFocusChanged(false, 0, null); 4992 4993 manageFocusHotspot(false, focused); 4994 refreshDrawableState(); 4995 4996 if (propagate && (!refocus || !rootViewRequestFocus())) { 4997 notifyGlobalFocusCleared(this); 4998 } 4999 } 5000 } 5001 5002 void notifyGlobalFocusCleared(View oldFocus) { 5003 if (oldFocus != null && mAttachInfo != null) { 5004 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null); 5005 } 5006 } 5007 5008 boolean rootViewRequestFocus() { 5009 final View root = getRootView(); 5010 return root != null && root.requestFocus(); 5011 } 5012 5013 /** 5014 * Called internally by the view system when a new view is getting focus. 5015 * This is what clears the old focus. 5016 * <p> 5017 * <b>NOTE:</b> The parent view's focused child must be updated manually 5018 * after calling this method. Otherwise, the view hierarchy may be left in 5019 * an inconstent state. 5020 */ 5021 void unFocus(View focused) { 5022 if (DBG) { 5023 System.out.println(this + " unFocus()"); 5024 } 5025 5026 clearFocusInternal(focused, false, false); 5027 } 5028 5029 /** 5030 * Returns true if this view has focus iteself, or is the ancestor of the 5031 * view that has focus. 5032 * 5033 * @return True if this view has or contains focus, false otherwise. 5034 */ 5035 @ViewDebug.ExportedProperty(category = "focus") 5036 public boolean hasFocus() { 5037 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 5038 } 5039 5040 /** 5041 * Returns true if this view is focusable or if it contains a reachable View 5042 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 5043 * is a View whose parents do not block descendants focus. 5044 * 5045 * Only {@link #VISIBLE} views are considered focusable. 5046 * 5047 * @return True if the view is focusable or if the view contains a focusable 5048 * View, false otherwise. 5049 * 5050 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 5051 */ 5052 public boolean hasFocusable() { 5053 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 5054 } 5055 5056 /** 5057 * Called by the view system when the focus state of this view changes. 5058 * When the focus change event is caused by directional navigation, direction 5059 * and previouslyFocusedRect provide insight into where the focus is coming from. 5060 * When overriding, be sure to call up through to the super class so that 5061 * the standard focus handling will occur. 5062 * 5063 * @param gainFocus True if the View has focus; false otherwise. 5064 * @param direction The direction focus has moved when requestFocus() 5065 * is called to give this view focus. Values are 5066 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 5067 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 5068 * It may not always apply, in which case use the default. 5069 * @param previouslyFocusedRect The rectangle, in this view's coordinate 5070 * system, of the previously focused view. If applicable, this will be 5071 * passed in as finer grained information about where the focus is coming 5072 * from (in addition to direction). Will be <code>null</code> otherwise. 5073 */ 5074 protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction, 5075 @Nullable Rect previouslyFocusedRect) { 5076 if (gainFocus) { 5077 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 5078 } else { 5079 notifyViewAccessibilityStateChangedIfNeeded( 5080 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 5081 } 5082 5083 InputMethodManager imm = InputMethodManager.peekInstance(); 5084 if (!gainFocus) { 5085 if (isPressed()) { 5086 setPressed(false); 5087 } 5088 if (imm != null && mAttachInfo != null 5089 && mAttachInfo.mHasWindowFocus) { 5090 imm.focusOut(this); 5091 } 5092 onFocusLost(); 5093 } else if (imm != null && mAttachInfo != null 5094 && mAttachInfo.mHasWindowFocus) { 5095 imm.focusIn(this); 5096 } 5097 5098 invalidate(true); 5099 ListenerInfo li = mListenerInfo; 5100 if (li != null && li.mOnFocusChangeListener != null) { 5101 li.mOnFocusChangeListener.onFocusChange(this, gainFocus); 5102 } 5103 5104 if (mAttachInfo != null) { 5105 mAttachInfo.mKeyDispatchState.reset(this); 5106 } 5107 } 5108 5109 /** 5110 * Sends an accessibility event of the given type. If accessibility is 5111 * not enabled this method has no effect. The default implementation calls 5112 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 5113 * to populate information about the event source (this View), then calls 5114 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 5115 * populate the text content of the event source including its descendants, 5116 * and last calls 5117 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 5118 * on its parent to resuest sending of the event to interested parties. 5119 * <p> 5120 * If an {@link AccessibilityDelegate} has been specified via calling 5121 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5122 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 5123 * responsible for handling this call. 5124 * </p> 5125 * 5126 * @param eventType The type of the event to send, as defined by several types from 5127 * {@link android.view.accessibility.AccessibilityEvent}, such as 5128 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or 5129 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}. 5130 * 5131 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 5132 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5133 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 5134 * @see AccessibilityDelegate 5135 */ 5136 public void sendAccessibilityEvent(int eventType) { 5137 if (mAccessibilityDelegate != null) { 5138 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 5139 } else { 5140 sendAccessibilityEventInternal(eventType); 5141 } 5142 } 5143 5144 /** 5145 * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT} 5146 * {@link AccessibilityEvent} to make an announcement which is related to some 5147 * sort of a context change for which none of the events representing UI transitions 5148 * is a good fit. For example, announcing a new page in a book. If accessibility 5149 * is not enabled this method does nothing. 5150 * 5151 * @param text The announcement text. 5152 */ 5153 public void announceForAccessibility(CharSequence text) { 5154 if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) { 5155 AccessibilityEvent event = AccessibilityEvent.obtain( 5156 AccessibilityEvent.TYPE_ANNOUNCEMENT); 5157 onInitializeAccessibilityEvent(event); 5158 event.getText().add(text); 5159 event.setContentDescription(null); 5160 mParent.requestSendAccessibilityEvent(this, event); 5161 } 5162 } 5163 5164 /** 5165 * @see #sendAccessibilityEvent(int) 5166 * 5167 * Note: Called from the default {@link AccessibilityDelegate}. 5168 */ 5169 void sendAccessibilityEventInternal(int eventType) { 5170 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 5171 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 5172 } 5173 } 5174 5175 /** 5176 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 5177 * takes as an argument an empty {@link AccessibilityEvent} and does not 5178 * perform a check whether accessibility is enabled. 5179 * <p> 5180 * If an {@link AccessibilityDelegate} has been specified via calling 5181 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5182 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 5183 * is responsible for handling this call. 5184 * </p> 5185 * 5186 * @param event The event to send. 5187 * 5188 * @see #sendAccessibilityEvent(int) 5189 */ 5190 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 5191 if (mAccessibilityDelegate != null) { 5192 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 5193 } else { 5194 sendAccessibilityEventUncheckedInternal(event); 5195 } 5196 } 5197 5198 /** 5199 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 5200 * 5201 * Note: Called from the default {@link AccessibilityDelegate}. 5202 */ 5203 void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 5204 if (!isShown()) { 5205 return; 5206 } 5207 onInitializeAccessibilityEvent(event); 5208 // Only a subset of accessibility events populates text content. 5209 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) { 5210 dispatchPopulateAccessibilityEvent(event); 5211 } 5212 // In the beginning we called #isShown(), so we know that getParent() is not null. 5213 getParent().requestSendAccessibilityEvent(this, event); 5214 } 5215 5216 /** 5217 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 5218 * to its children for adding their text content to the event. Note that the 5219 * event text is populated in a separate dispatch path since we add to the 5220 * event not only the text of the source but also the text of all its descendants. 5221 * A typical implementation will call 5222 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 5223 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 5224 * on each child. Override this method if custom population of the event text 5225 * content is required. 5226 * <p> 5227 * If an {@link AccessibilityDelegate} has been specified via calling 5228 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5229 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 5230 * is responsible for handling this call. 5231 * </p> 5232 * <p> 5233 * <em>Note:</em> Accessibility events of certain types are not dispatched for 5234 * populating the event text via this method. For details refer to {@link AccessibilityEvent}. 5235 * </p> 5236 * 5237 * @param event The event. 5238 * 5239 * @return True if the event population was completed. 5240 */ 5241 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 5242 if (mAccessibilityDelegate != null) { 5243 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 5244 } else { 5245 return dispatchPopulateAccessibilityEventInternal(event); 5246 } 5247 } 5248 5249 /** 5250 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5251 * 5252 * Note: Called from the default {@link AccessibilityDelegate}. 5253 */ 5254 boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5255 onPopulateAccessibilityEvent(event); 5256 return false; 5257 } 5258 5259 /** 5260 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 5261 * giving a chance to this View to populate the accessibility event with its 5262 * text content. While this method is free to modify event 5263 * attributes other than text content, doing so should normally be performed in 5264 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 5265 * <p> 5266 * Example: Adding formatted date string to an accessibility event in addition 5267 * to the text added by the super implementation: 5268 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5269 * super.onPopulateAccessibilityEvent(event); 5270 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 5271 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 5272 * mCurrentDate.getTimeInMillis(), flags); 5273 * event.getText().add(selectedDateUtterance); 5274 * }</pre> 5275 * <p> 5276 * If an {@link AccessibilityDelegate} has been specified via calling 5277 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5278 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 5279 * is responsible for handling this call. 5280 * </p> 5281 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5282 * information to the event, in case the default implementation has basic information to add. 5283 * </p> 5284 * 5285 * @param event The accessibility event which to populate. 5286 * 5287 * @see #sendAccessibilityEvent(int) 5288 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5289 */ 5290 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5291 if (mAccessibilityDelegate != null) { 5292 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 5293 } else { 5294 onPopulateAccessibilityEventInternal(event); 5295 } 5296 } 5297 5298 /** 5299 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 5300 * 5301 * Note: Called from the default {@link AccessibilityDelegate}. 5302 */ 5303 void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5304 } 5305 5306 /** 5307 * Initializes an {@link AccessibilityEvent} with information about 5308 * this View which is the event source. In other words, the source of 5309 * an accessibility event is the view whose state change triggered firing 5310 * the event. 5311 * <p> 5312 * Example: Setting the password property of an event in addition 5313 * to properties set by the super implementation: 5314 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5315 * super.onInitializeAccessibilityEvent(event); 5316 * event.setPassword(true); 5317 * }</pre> 5318 * <p> 5319 * If an {@link AccessibilityDelegate} has been specified via calling 5320 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5321 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 5322 * is responsible for handling this call. 5323 * </p> 5324 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5325 * information to the event, in case the default implementation has basic information to add. 5326 * </p> 5327 * @param event The event to initialize. 5328 * 5329 * @see #sendAccessibilityEvent(int) 5330 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5331 */ 5332 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5333 if (mAccessibilityDelegate != null) { 5334 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 5335 } else { 5336 onInitializeAccessibilityEventInternal(event); 5337 } 5338 } 5339 5340 /** 5341 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 5342 * 5343 * Note: Called from the default {@link AccessibilityDelegate}. 5344 */ 5345 void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 5346 event.setSource(this); 5347 event.setClassName(View.class.getName()); 5348 event.setPackageName(getContext().getPackageName()); 5349 event.setEnabled(isEnabled()); 5350 event.setContentDescription(mContentDescription); 5351 5352 switch (event.getEventType()) { 5353 case AccessibilityEvent.TYPE_VIEW_FOCUSED: { 5354 ArrayList<View> focusablesTempList = (mAttachInfo != null) 5355 ? mAttachInfo.mTempArrayList : new ArrayList<View>(); 5356 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL); 5357 event.setItemCount(focusablesTempList.size()); 5358 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 5359 if (mAttachInfo != null) { 5360 focusablesTempList.clear(); 5361 } 5362 } break; 5363 case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: { 5364 CharSequence text = getIterableTextForAccessibility(); 5365 if (text != null && text.length() > 0) { 5366 event.setFromIndex(getAccessibilitySelectionStart()); 5367 event.setToIndex(getAccessibilitySelectionEnd()); 5368 event.setItemCount(text.length()); 5369 } 5370 } break; 5371 } 5372 } 5373 5374 /** 5375 * Returns an {@link AccessibilityNodeInfo} representing this view from the 5376 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 5377 * This method is responsible for obtaining an accessibility node info from a 5378 * pool of reusable instances and calling 5379 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 5380 * initialize the former. 5381 * <p> 5382 * Note: The client is responsible for recycling the obtained instance by calling 5383 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 5384 * </p> 5385 * 5386 * @return A populated {@link AccessibilityNodeInfo}. 5387 * 5388 * @see AccessibilityNodeInfo 5389 */ 5390 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 5391 if (mAccessibilityDelegate != null) { 5392 return mAccessibilityDelegate.createAccessibilityNodeInfo(this); 5393 } else { 5394 return createAccessibilityNodeInfoInternal(); 5395 } 5396 } 5397 5398 /** 5399 * @see #createAccessibilityNodeInfo() 5400 */ 5401 AccessibilityNodeInfo createAccessibilityNodeInfoInternal() { 5402 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 5403 if (provider != null) { 5404 return provider.createAccessibilityNodeInfo(View.NO_ID); 5405 } else { 5406 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 5407 onInitializeAccessibilityNodeInfo(info); 5408 return info; 5409 } 5410 } 5411 5412 /** 5413 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 5414 * The base implementation sets: 5415 * <ul> 5416 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 5417 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 5418 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 5419 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 5420 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 5421 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 5422 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 5423 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 5424 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 5425 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 5426 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 5427 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 5428 * </ul> 5429 * <p> 5430 * Subclasses should override this method, call the super implementation, 5431 * and set additional attributes. 5432 * </p> 5433 * <p> 5434 * If an {@link AccessibilityDelegate} has been specified via calling 5435 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5436 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 5437 * is responsible for handling this call. 5438 * </p> 5439 * 5440 * @param info The instance to initialize. 5441 */ 5442 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 5443 if (mAccessibilityDelegate != null) { 5444 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 5445 } else { 5446 onInitializeAccessibilityNodeInfoInternal(info); 5447 } 5448 } 5449 5450 /** 5451 * Gets the location of this view in screen coordintates. 5452 * 5453 * @param outRect The output location 5454 * @hide 5455 */ 5456 public void getBoundsOnScreen(Rect outRect) { 5457 if (mAttachInfo == null) { 5458 return; 5459 } 5460 5461 RectF position = mAttachInfo.mTmpTransformRect; 5462 position.set(0, 0, mRight - mLeft, mBottom - mTop); 5463 5464 if (!hasIdentityMatrix()) { 5465 getMatrix().mapRect(position); 5466 } 5467 5468 position.offset(mLeft, mTop); 5469 5470 ViewParent parent = mParent; 5471 while (parent instanceof View) { 5472 View parentView = (View) parent; 5473 5474 position.offset(-parentView.mScrollX, -parentView.mScrollY); 5475 5476 if (!parentView.hasIdentityMatrix()) { 5477 parentView.getMatrix().mapRect(position); 5478 } 5479 5480 position.offset(parentView.mLeft, parentView.mTop); 5481 5482 parent = parentView.mParent; 5483 } 5484 5485 if (parent instanceof ViewRootImpl) { 5486 ViewRootImpl viewRootImpl = (ViewRootImpl) parent; 5487 position.offset(0, -viewRootImpl.mCurScrollY); 5488 } 5489 5490 position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 5491 5492 outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f), 5493 (int) (position.right + 0.5f), (int) (position.bottom + 0.5f)); 5494 } 5495 5496 /** 5497 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 5498 * 5499 * Note: Called from the default {@link AccessibilityDelegate}. 5500 */ 5501 void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 5502 Rect bounds = mAttachInfo.mTmpInvalRect; 5503 5504 getDrawingRect(bounds); 5505 info.setBoundsInParent(bounds); 5506 5507 getBoundsOnScreen(bounds); 5508 info.setBoundsInScreen(bounds); 5509 5510 ViewParent parent = getParentForAccessibility(); 5511 if (parent instanceof View) { 5512 info.setParent((View) parent); 5513 } 5514 5515 if (mID != View.NO_ID) { 5516 View rootView = getRootView(); 5517 if (rootView == null) { 5518 rootView = this; 5519 } 5520 View label = rootView.findLabelForView(this, mID); 5521 if (label != null) { 5522 info.setLabeledBy(label); 5523 } 5524 5525 if ((mAttachInfo.mAccessibilityFetchFlags 5526 & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0 5527 && Resources.resourceHasPackage(mID)) { 5528 try { 5529 String viewId = getResources().getResourceName(mID); 5530 info.setViewIdResourceName(viewId); 5531 } catch (Resources.NotFoundException nfe) { 5532 /* ignore */ 5533 } 5534 } 5535 } 5536 5537 if (mLabelForId != View.NO_ID) { 5538 View rootView = getRootView(); 5539 if (rootView == null) { 5540 rootView = this; 5541 } 5542 View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId); 5543 if (labeled != null) { 5544 info.setLabelFor(labeled); 5545 } 5546 } 5547 5548 info.setVisibleToUser(isVisibleToUser()); 5549 5550 info.setPackageName(mContext.getPackageName()); 5551 info.setClassName(View.class.getName()); 5552 info.setContentDescription(getContentDescription()); 5553 5554 info.setEnabled(isEnabled()); 5555 info.setClickable(isClickable()); 5556 info.setFocusable(isFocusable()); 5557 info.setFocused(isFocused()); 5558 info.setAccessibilityFocused(isAccessibilityFocused()); 5559 info.setSelected(isSelected()); 5560 info.setLongClickable(isLongClickable()); 5561 info.setLiveRegion(getAccessibilityLiveRegion()); 5562 5563 // TODO: These make sense only if we are in an AdapterView but all 5564 // views can be selected. Maybe from accessibility perspective 5565 // we should report as selectable view in an AdapterView. 5566 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 5567 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 5568 5569 if (isFocusable()) { 5570 if (isFocused()) { 5571 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 5572 } else { 5573 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 5574 } 5575 } 5576 5577 if (!isAccessibilityFocused()) { 5578 info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); 5579 } else { 5580 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); 5581 } 5582 5583 if (isClickable() && isEnabled()) { 5584 info.addAction(AccessibilityNodeInfo.ACTION_CLICK); 5585 } 5586 5587 if (isLongClickable() && isEnabled()) { 5588 info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); 5589 } 5590 5591 CharSequence text = getIterableTextForAccessibility(); 5592 if (text != null && text.length() > 0) { 5593 info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd()); 5594 5595 info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION); 5596 info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); 5597 info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); 5598 info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER 5599 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD 5600 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH); 5601 } 5602 } 5603 5604 private View findLabelForView(View view, int labeledId) { 5605 if (mMatchLabelForPredicate == null) { 5606 mMatchLabelForPredicate = new MatchLabelForPredicate(); 5607 } 5608 mMatchLabelForPredicate.mLabeledId = labeledId; 5609 return findViewByPredicateInsideOut(view, mMatchLabelForPredicate); 5610 } 5611 5612 /** 5613 * Computes whether this view is visible to the user. Such a view is 5614 * attached, visible, all its predecessors are visible, it is not clipped 5615 * entirely by its predecessors, and has an alpha greater than zero. 5616 * 5617 * @return Whether the view is visible on the screen. 5618 * 5619 * @hide 5620 */ 5621 protected boolean isVisibleToUser() { 5622 return isVisibleToUser(null); 5623 } 5624 5625 /** 5626 * Computes whether the given portion of this view is visible to the user. 5627 * Such a view is attached, visible, all its predecessors are visible, 5628 * has an alpha greater than zero, and the specified portion is not 5629 * clipped entirely by its predecessors. 5630 * 5631 * @param boundInView the portion of the view to test; coordinates should be relative; may be 5632 * <code>null</code>, and the entire view will be tested in this case. 5633 * When <code>true</code> is returned by the function, the actual visible 5634 * region will be stored in this parameter; that is, if boundInView is fully 5635 * contained within the view, no modification will be made, otherwise regions 5636 * outside of the visible area of the view will be clipped. 5637 * 5638 * @return Whether the specified portion of the view is visible on the screen. 5639 * 5640 * @hide 5641 */ 5642 protected boolean isVisibleToUser(Rect boundInView) { 5643 if (mAttachInfo != null) { 5644 // Attached to invisible window means this view is not visible. 5645 if (mAttachInfo.mWindowVisibility != View.VISIBLE) { 5646 return false; 5647 } 5648 // An invisible predecessor or one with alpha zero means 5649 // that this view is not visible to the user. 5650 Object current = this; 5651 while (current instanceof View) { 5652 View view = (View) current; 5653 // We have attach info so this view is attached and there is no 5654 // need to check whether we reach to ViewRootImpl on the way up. 5655 if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 || 5656 view.getVisibility() != VISIBLE) { 5657 return false; 5658 } 5659 current = view.mParent; 5660 } 5661 // Check if the view is entirely covered by its predecessors. 5662 Rect visibleRect = mAttachInfo.mTmpInvalRect; 5663 Point offset = mAttachInfo.mPoint; 5664 if (!getGlobalVisibleRect(visibleRect, offset)) { 5665 return false; 5666 } 5667 // Check if the visible portion intersects the rectangle of interest. 5668 if (boundInView != null) { 5669 visibleRect.offset(-offset.x, -offset.y); 5670 return boundInView.intersect(visibleRect); 5671 } 5672 return true; 5673 } 5674 return false; 5675 } 5676 5677 /** 5678 * Returns the delegate for implementing accessibility support via 5679 * composition. For more details see {@link AccessibilityDelegate}. 5680 * 5681 * @return The delegate, or null if none set. 5682 * 5683 * @hide 5684 */ 5685 public AccessibilityDelegate getAccessibilityDelegate() { 5686 return mAccessibilityDelegate; 5687 } 5688 5689 /** 5690 * Sets a delegate for implementing accessibility support via composition as 5691 * opposed to inheritance. The delegate's primary use is for implementing 5692 * backwards compatible widgets. For more details see {@link AccessibilityDelegate}. 5693 * 5694 * @param delegate The delegate instance. 5695 * 5696 * @see AccessibilityDelegate 5697 */ 5698 public void setAccessibilityDelegate(AccessibilityDelegate delegate) { 5699 mAccessibilityDelegate = delegate; 5700 } 5701 5702 /** 5703 * Gets the provider for managing a virtual view hierarchy rooted at this View 5704 * and reported to {@link android.accessibilityservice.AccessibilityService}s 5705 * that explore the window content. 5706 * <p> 5707 * If this method returns an instance, this instance is responsible for managing 5708 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this 5709 * View including the one representing the View itself. Similarly the returned 5710 * instance is responsible for performing accessibility actions on any virtual 5711 * view or the root view itself. 5712 * </p> 5713 * <p> 5714 * If an {@link AccessibilityDelegate} has been specified via calling 5715 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5716 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)} 5717 * is responsible for handling this call. 5718 * </p> 5719 * 5720 * @return The provider. 5721 * 5722 * @see AccessibilityNodeProvider 5723 */ 5724 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 5725 if (mAccessibilityDelegate != null) { 5726 return mAccessibilityDelegate.getAccessibilityNodeProvider(this); 5727 } else { 5728 return null; 5729 } 5730 } 5731 5732 /** 5733 * Gets the unique identifier of this view on the screen for accessibility purposes. 5734 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 5735 * 5736 * @return The view accessibility id. 5737 * 5738 * @hide 5739 */ 5740 public int getAccessibilityViewId() { 5741 if (mAccessibilityViewId == NO_ID) { 5742 mAccessibilityViewId = sNextAccessibilityViewId++; 5743 } 5744 return mAccessibilityViewId; 5745 } 5746 5747 /** 5748 * Gets the unique identifier of the window in which this View reseides. 5749 * 5750 * @return The window accessibility id. 5751 * 5752 * @hide 5753 */ 5754 public int getAccessibilityWindowId() { 5755 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId 5756 : AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 5757 } 5758 5759 /** 5760 * Gets the {@link View} description. It briefly describes the view and is 5761 * primarily used for accessibility support. Set this property to enable 5762 * better accessibility support for your application. This is especially 5763 * true for views that do not have textual representation (For example, 5764 * ImageButton). 5765 * 5766 * @return The content description. 5767 * 5768 * @attr ref android.R.styleable#View_contentDescription 5769 */ 5770 @ViewDebug.ExportedProperty(category = "accessibility") 5771 public CharSequence getContentDescription() { 5772 return mContentDescription; 5773 } 5774 5775 /** 5776 * Sets the {@link View} description. It briefly describes the view and is 5777 * primarily used for accessibility support. Set this property to enable 5778 * better accessibility support for your application. This is especially 5779 * true for views that do not have textual representation (For example, 5780 * ImageButton). 5781 * 5782 * @param contentDescription The content description. 5783 * 5784 * @attr ref android.R.styleable#View_contentDescription 5785 */ 5786 @RemotableViewMethod 5787 public void setContentDescription(CharSequence contentDescription) { 5788 if (mContentDescription == null) { 5789 if (contentDescription == null) { 5790 return; 5791 } 5792 } else if (mContentDescription.equals(contentDescription)) { 5793 return; 5794 } 5795 mContentDescription = contentDescription; 5796 final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0; 5797 if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 5798 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); 5799 notifySubtreeAccessibilityStateChangedIfNeeded(); 5800 } else { 5801 notifyViewAccessibilityStateChangedIfNeeded( 5802 AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION); 5803 } 5804 } 5805 5806 /** 5807 * Gets the id of a view for which this view serves as a label for 5808 * accessibility purposes. 5809 * 5810 * @return The labeled view id. 5811 */ 5812 @ViewDebug.ExportedProperty(category = "accessibility") 5813 public int getLabelFor() { 5814 return mLabelForId; 5815 } 5816 5817 /** 5818 * Sets the id of a view for which this view serves as a label for 5819 * accessibility purposes. 5820 * 5821 * @param id The labeled view id. 5822 */ 5823 @RemotableViewMethod 5824 public void setLabelFor(int id) { 5825 mLabelForId = id; 5826 if (mLabelForId != View.NO_ID 5827 && mID == View.NO_ID) { 5828 mID = generateViewId(); 5829 } 5830 } 5831 5832 /** 5833 * Invoked whenever this view loses focus, either by losing window focus or by losing 5834 * focus within its window. This method can be used to clear any state tied to the 5835 * focus. For instance, if a button is held pressed with the trackball and the window 5836 * loses focus, this method can be used to cancel the press. 5837 * 5838 * Subclasses of View overriding this method should always call super.onFocusLost(). 5839 * 5840 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 5841 * @see #onWindowFocusChanged(boolean) 5842 * 5843 * @hide pending API council approval 5844 */ 5845 protected void onFocusLost() { 5846 resetPressedState(); 5847 } 5848 5849 private void resetPressedState() { 5850 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 5851 return; 5852 } 5853 5854 if (isPressed()) { 5855 setPressed(false); 5856 5857 if (!mHasPerformedLongPress) { 5858 removeLongPressCallback(); 5859 } 5860 } 5861 } 5862 5863 /** 5864 * Returns true if this view has focus 5865 * 5866 * @return True if this view has focus, false otherwise. 5867 */ 5868 @ViewDebug.ExportedProperty(category = "focus") 5869 public boolean isFocused() { 5870 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 5871 } 5872 5873 /** 5874 * Find the view in the hierarchy rooted at this view that currently has 5875 * focus. 5876 * 5877 * @return The view that currently has focus, or null if no focused view can 5878 * be found. 5879 */ 5880 public View findFocus() { 5881 return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null; 5882 } 5883 5884 /** 5885 * Indicates whether this view is one of the set of scrollable containers in 5886 * its window. 5887 * 5888 * @return whether this view is one of the set of scrollable containers in 5889 * its window 5890 * 5891 * @attr ref android.R.styleable#View_isScrollContainer 5892 */ 5893 public boolean isScrollContainer() { 5894 return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0; 5895 } 5896 5897 /** 5898 * Change whether this view is one of the set of scrollable containers in 5899 * its window. This will be used to determine whether the window can 5900 * resize or must pan when a soft input area is open -- scrollable 5901 * containers allow the window to use resize mode since the container 5902 * will appropriately shrink. 5903 * 5904 * @attr ref android.R.styleable#View_isScrollContainer 5905 */ 5906 public void setScrollContainer(boolean isScrollContainer) { 5907 if (isScrollContainer) { 5908 if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) { 5909 mAttachInfo.mScrollContainers.add(this); 5910 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 5911 } 5912 mPrivateFlags |= PFLAG_SCROLL_CONTAINER; 5913 } else { 5914 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 5915 mAttachInfo.mScrollContainers.remove(this); 5916 } 5917 mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED); 5918 } 5919 } 5920 5921 /** 5922 * Returns the quality of the drawing cache. 5923 * 5924 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5925 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5926 * 5927 * @see #setDrawingCacheQuality(int) 5928 * @see #setDrawingCacheEnabled(boolean) 5929 * @see #isDrawingCacheEnabled() 5930 * 5931 * @attr ref android.R.styleable#View_drawingCacheQuality 5932 */ 5933 @DrawingCacheQuality 5934 public int getDrawingCacheQuality() { 5935 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 5936 } 5937 5938 /** 5939 * Set the drawing cache quality of this view. This value is used only when the 5940 * drawing cache is enabled 5941 * 5942 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5943 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5944 * 5945 * @see #getDrawingCacheQuality() 5946 * @see #setDrawingCacheEnabled(boolean) 5947 * @see #isDrawingCacheEnabled() 5948 * 5949 * @attr ref android.R.styleable#View_drawingCacheQuality 5950 */ 5951 public void setDrawingCacheQuality(@DrawingCacheQuality int quality) { 5952 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 5953 } 5954 5955 /** 5956 * Returns whether the screen should remain on, corresponding to the current 5957 * value of {@link #KEEP_SCREEN_ON}. 5958 * 5959 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 5960 * 5961 * @see #setKeepScreenOn(boolean) 5962 * 5963 * @attr ref android.R.styleable#View_keepScreenOn 5964 */ 5965 public boolean getKeepScreenOn() { 5966 return (mViewFlags & KEEP_SCREEN_ON) != 0; 5967 } 5968 5969 /** 5970 * Controls whether the screen should remain on, modifying the 5971 * value of {@link #KEEP_SCREEN_ON}. 5972 * 5973 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 5974 * 5975 * @see #getKeepScreenOn() 5976 * 5977 * @attr ref android.R.styleable#View_keepScreenOn 5978 */ 5979 public void setKeepScreenOn(boolean keepScreenOn) { 5980 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 5981 } 5982 5983 /** 5984 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5985 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5986 * 5987 * @attr ref android.R.styleable#View_nextFocusLeft 5988 */ 5989 public int getNextFocusLeftId() { 5990 return mNextFocusLeftId; 5991 } 5992 5993 /** 5994 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5995 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 5996 * decide automatically. 5997 * 5998 * @attr ref android.R.styleable#View_nextFocusLeft 5999 */ 6000 public void setNextFocusLeftId(int nextFocusLeftId) { 6001 mNextFocusLeftId = nextFocusLeftId; 6002 } 6003 6004 /** 6005 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 6006 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6007 * 6008 * @attr ref android.R.styleable#View_nextFocusRight 6009 */ 6010 public int getNextFocusRightId() { 6011 return mNextFocusRightId; 6012 } 6013 6014 /** 6015 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 6016 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 6017 * decide automatically. 6018 * 6019 * @attr ref android.R.styleable#View_nextFocusRight 6020 */ 6021 public void setNextFocusRightId(int nextFocusRightId) { 6022 mNextFocusRightId = nextFocusRightId; 6023 } 6024 6025 /** 6026 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 6027 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6028 * 6029 * @attr ref android.R.styleable#View_nextFocusUp 6030 */ 6031 public int getNextFocusUpId() { 6032 return mNextFocusUpId; 6033 } 6034 6035 /** 6036 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 6037 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 6038 * decide automatically. 6039 * 6040 * @attr ref android.R.styleable#View_nextFocusUp 6041 */ 6042 public void setNextFocusUpId(int nextFocusUpId) { 6043 mNextFocusUpId = nextFocusUpId; 6044 } 6045 6046 /** 6047 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 6048 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6049 * 6050 * @attr ref android.R.styleable#View_nextFocusDown 6051 */ 6052 public int getNextFocusDownId() { 6053 return mNextFocusDownId; 6054 } 6055 6056 /** 6057 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 6058 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 6059 * decide automatically. 6060 * 6061 * @attr ref android.R.styleable#View_nextFocusDown 6062 */ 6063 public void setNextFocusDownId(int nextFocusDownId) { 6064 mNextFocusDownId = nextFocusDownId; 6065 } 6066 6067 /** 6068 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 6069 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6070 * 6071 * @attr ref android.R.styleable#View_nextFocusForward 6072 */ 6073 public int getNextFocusForwardId() { 6074 return mNextFocusForwardId; 6075 } 6076 6077 /** 6078 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 6079 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 6080 * decide automatically. 6081 * 6082 * @attr ref android.R.styleable#View_nextFocusForward 6083 */ 6084 public void setNextFocusForwardId(int nextFocusForwardId) { 6085 mNextFocusForwardId = nextFocusForwardId; 6086 } 6087 6088 /** 6089 * Returns the visibility of this view and all of its ancestors 6090 * 6091 * @return True if this view and all of its ancestors are {@link #VISIBLE} 6092 */ 6093 public boolean isShown() { 6094 View current = this; 6095 //noinspection ConstantConditions 6096 do { 6097 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 6098 return false; 6099 } 6100 ViewParent parent = current.mParent; 6101 if (parent == null) { 6102 return false; // We are not attached to the view root 6103 } 6104 if (!(parent instanceof View)) { 6105 return true; 6106 } 6107 current = (View) parent; 6108 } while (current != null); 6109 6110 return false; 6111 } 6112 6113 /** 6114 * Called by the view hierarchy when the content insets for a window have 6115 * changed, to allow it to adjust its content to fit within those windows. 6116 * The content insets tell you the space that the status bar, input method, 6117 * and other system windows infringe on the application's window. 6118 * 6119 * <p>You do not normally need to deal with this function, since the default 6120 * window decoration given to applications takes care of applying it to the 6121 * content of the window. If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 6122 * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case, 6123 * and your content can be placed under those system elements. You can then 6124 * use this method within your view hierarchy if you have parts of your UI 6125 * which you would like to ensure are not being covered. 6126 * 6127 * <p>The default implementation of this method simply applies the content 6128 * insets to the view's padding, consuming that content (modifying the 6129 * insets to be 0), and returning true. This behavior is off by default, but can 6130 * be enabled through {@link #setFitsSystemWindows(boolean)}. 6131 * 6132 * <p>This function's traversal down the hierarchy is depth-first. The same content 6133 * insets object is propagated down the hierarchy, so any changes made to it will 6134 * be seen by all following views (including potentially ones above in 6135 * the hierarchy since this is a depth-first traversal). The first view 6136 * that returns true will abort the entire traversal. 6137 * 6138 * <p>The default implementation works well for a situation where it is 6139 * used with a container that covers the entire window, allowing it to 6140 * apply the appropriate insets to its content on all edges. If you need 6141 * a more complicated layout (such as two different views fitting system 6142 * windows, one on the top of the window, and one on the bottom), 6143 * you can override the method and handle the insets however you would like. 6144 * Note that the insets provided by the framework are always relative to the 6145 * far edges of the window, not accounting for the location of the called view 6146 * within that window. (In fact when this method is called you do not yet know 6147 * where the layout will place the view, as it is done before layout happens.) 6148 * 6149 * <p>Note: unlike many View methods, there is no dispatch phase to this 6150 * call. If you are overriding it in a ViewGroup and want to allow the 6151 * call to continue to your children, you must be sure to call the super 6152 * implementation. 6153 * 6154 * <p>Here is a sample layout that makes use of fitting system windows 6155 * to have controls for a video view placed inside of the window decorations 6156 * that it hides and shows. This can be used with code like the second 6157 * sample (video player) shown in {@link #setSystemUiVisibility(int)}. 6158 * 6159 * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete} 6160 * 6161 * @param insets Current content insets of the window. Prior to 6162 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify 6163 * the insets or else you and Android will be unhappy. 6164 * 6165 * @return {@code true} if this view applied the insets and it should not 6166 * continue propagating further down the hierarchy, {@code false} otherwise. 6167 * @see #getFitsSystemWindows() 6168 * @see #setFitsSystemWindows(boolean) 6169 * @see #setSystemUiVisibility(int) 6170 * 6171 * @deprecated As of API XX use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply 6172 * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use 6173 * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)} 6174 * to implement handling their own insets. 6175 */ 6176 protected boolean fitSystemWindows(Rect insets) { 6177 if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) { 6178 if (insets == null) { 6179 // Null insets by definition have already been consumed. 6180 // This call cannot apply insets since there are none to apply, 6181 // so return false. 6182 return false; 6183 } 6184 // If we're not in the process of dispatching the newer apply insets call, 6185 // that means we're not in the compatibility path. Dispatch into the newer 6186 // apply insets path and take things from there. 6187 try { 6188 mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS; 6189 return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed(); 6190 } finally { 6191 mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS; 6192 } 6193 } else { 6194 // We're being called from the newer apply insets path. 6195 // Perform the standard fallback behavior. 6196 return fitSystemWindowsInt(insets); 6197 } 6198 } 6199 6200 private boolean fitSystemWindowsInt(Rect insets) { 6201 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 6202 mUserPaddingStart = UNDEFINED_PADDING; 6203 mUserPaddingEnd = UNDEFINED_PADDING; 6204 Rect localInsets = sThreadLocal.get(); 6205 if (localInsets == null) { 6206 localInsets = new Rect(); 6207 sThreadLocal.set(localInsets); 6208 } 6209 boolean res = computeFitSystemWindows(insets, localInsets); 6210 mUserPaddingLeftInitial = localInsets.left; 6211 mUserPaddingRightInitial = localInsets.right; 6212 internalSetPadding(localInsets.left, localInsets.top, 6213 localInsets.right, localInsets.bottom); 6214 return res; 6215 } 6216 return false; 6217 } 6218 6219 /** 6220 * Called when the view should apply {@link WindowInsets} according to its internal policy. 6221 * 6222 * <p>This method should be overridden by views that wish to apply a policy different from or 6223 * in addition to the default behavior. Clients that wish to force a view subtree 6224 * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p> 6225 * 6226 * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set 6227 * it will be called during dispatch instead of this method. The listener may optionally 6228 * call this method from its own implementation if it wishes to apply the view's default 6229 * insets policy in addition to its own.</p> 6230 * 6231 * <p>Implementations of this method should either return the insets parameter unchanged 6232 * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed 6233 * that this view applied itself. This allows new inset types added in future platform 6234 * versions to pass through existing implementations unchanged without being erroneously 6235 * consumed.</p> 6236 * 6237 * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows} 6238 * property is set then the view will consume the system window insets and apply them 6239 * as padding for the view.</p> 6240 * 6241 * @param insets Insets to apply 6242 * @return The supplied insets with any applied insets consumed 6243 */ 6244 public WindowInsets onApplyWindowInsets(WindowInsets insets) { 6245 if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) { 6246 // We weren't called from within a direct call to fitSystemWindows, 6247 // call into it as a fallback in case we're in a class that overrides it 6248 // and has logic to perform. 6249 if (fitSystemWindows(insets.getSystemWindowInsets())) { 6250 return insets.consumeSystemWindowInsets(); 6251 } 6252 } else { 6253 // We were called from within a direct call to fitSystemWindows. 6254 if (fitSystemWindowsInt(insets.getSystemWindowInsets())) { 6255 return insets.consumeSystemWindowInsets(); 6256 } 6257 } 6258 return insets; 6259 } 6260 6261 /** 6262 * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying 6263 * window insets to this view. The listener's 6264 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 6265 * method will be called instead of the view's 6266 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 6267 * 6268 * @param listener Listener to set 6269 * 6270 * @see #onApplyWindowInsets(WindowInsets) 6271 */ 6272 public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) { 6273 getListenerInfo().mOnApplyWindowInsetsListener = listener; 6274 } 6275 6276 /** 6277 * Request to apply the given window insets to this view or another view in its subtree. 6278 * 6279 * <p>This method should be called by clients wishing to apply insets corresponding to areas 6280 * obscured by window decorations or overlays. This can include the status and navigation bars, 6281 * action bars, input methods and more. New inset categories may be added in the future. 6282 * The method returns the insets provided minus any that were applied by this view or its 6283 * children.</p> 6284 * 6285 * <p>Clients wishing to provide custom behavior should override the 6286 * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a 6287 * {@link OnApplyWindowInsetsListener} via the 6288 * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener} 6289 * method.</p> 6290 * 6291 * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method. 6292 * </p> 6293 * 6294 * @param insets Insets to apply 6295 * @return The provided insets minus the insets that were consumed 6296 */ 6297 public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) { 6298 try { 6299 mPrivateFlags3 |= PFLAG3_APPLYING_INSETS; 6300 if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) { 6301 return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets); 6302 } else { 6303 return onApplyWindowInsets(insets); 6304 } 6305 } finally { 6306 mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS; 6307 } 6308 } 6309 6310 /** 6311 * @hide Compute the insets that should be consumed by this view and the ones 6312 * that should propagate to those under it. 6313 */ 6314 protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) { 6315 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 6316 || mAttachInfo == null 6317 || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0 6318 && !mAttachInfo.mOverscanRequested)) { 6319 outLocalInsets.set(inoutInsets); 6320 inoutInsets.set(0, 0, 0, 0); 6321 return true; 6322 } else { 6323 // The application wants to take care of fitting system window for 6324 // the content... however we still need to take care of any overscan here. 6325 final Rect overscan = mAttachInfo.mOverscanInsets; 6326 outLocalInsets.set(overscan); 6327 inoutInsets.left -= overscan.left; 6328 inoutInsets.top -= overscan.top; 6329 inoutInsets.right -= overscan.right; 6330 inoutInsets.bottom -= overscan.bottom; 6331 return false; 6332 } 6333 } 6334 6335 /** 6336 * Sets whether or not this view should account for system screen decorations 6337 * such as the status bar and inset its content; that is, controlling whether 6338 * the default implementation of {@link #fitSystemWindows(Rect)} will be 6339 * executed. See that method for more details. 6340 * 6341 * <p>Note that if you are providing your own implementation of 6342 * {@link #fitSystemWindows(Rect)}, then there is no need to set this 6343 * flag to true -- your implementation will be overriding the default 6344 * implementation that checks this flag. 6345 * 6346 * @param fitSystemWindows If true, then the default implementation of 6347 * {@link #fitSystemWindows(Rect)} will be executed. 6348 * 6349 * @attr ref android.R.styleable#View_fitsSystemWindows 6350 * @see #getFitsSystemWindows() 6351 * @see #fitSystemWindows(Rect) 6352 * @see #setSystemUiVisibility(int) 6353 */ 6354 public void setFitsSystemWindows(boolean fitSystemWindows) { 6355 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 6356 } 6357 6358 /** 6359 * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method 6360 * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)} 6361 * will be executed. 6362 * 6363 * @return {@code true} if the default implementation of 6364 * {@link #fitSystemWindows(Rect)} will be executed. 6365 * 6366 * @attr ref android.R.styleable#View_fitsSystemWindows 6367 * @see #setFitsSystemWindows(boolean) 6368 * @see #fitSystemWindows(Rect) 6369 * @see #setSystemUiVisibility(int) 6370 */ 6371 public boolean getFitsSystemWindows() { 6372 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 6373 } 6374 6375 /** @hide */ 6376 public boolean fitsSystemWindows() { 6377 return getFitsSystemWindows(); 6378 } 6379 6380 /** 6381 * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed. 6382 * @deprecated Use {@link #requestApplyInsets()} for newer platform versions. 6383 */ 6384 public void requestFitSystemWindows() { 6385 if (mParent != null) { 6386 mParent.requestFitSystemWindows(); 6387 } 6388 } 6389 6390 /** 6391 * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed. 6392 */ 6393 public void requestApplyInsets() { 6394 requestFitSystemWindows(); 6395 } 6396 6397 /** 6398 * For use by PhoneWindow to make its own system window fitting optional. 6399 * @hide 6400 */ 6401 public void makeOptionalFitsSystemWindows() { 6402 setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS); 6403 } 6404 6405 /** 6406 * Returns the visibility status for this view. 6407 * 6408 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 6409 * @attr ref android.R.styleable#View_visibility 6410 */ 6411 @ViewDebug.ExportedProperty(mapping = { 6412 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 6413 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 6414 @ViewDebug.IntToString(from = GONE, to = "GONE") 6415 }) 6416 @Visibility 6417 public int getVisibility() { 6418 return mViewFlags & VISIBILITY_MASK; 6419 } 6420 6421 /** 6422 * Set the enabled state of this view. 6423 * 6424 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 6425 * @attr ref android.R.styleable#View_visibility 6426 */ 6427 @RemotableViewMethod 6428 public void setVisibility(@Visibility int visibility) { 6429 setFlags(visibility, VISIBILITY_MASK); 6430 if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false); 6431 } 6432 6433 /** 6434 * Returns the enabled status for this view. The interpretation of the 6435 * enabled state varies by subclass. 6436 * 6437 * @return True if this view is enabled, false otherwise. 6438 */ 6439 @ViewDebug.ExportedProperty 6440 public boolean isEnabled() { 6441 return (mViewFlags & ENABLED_MASK) == ENABLED; 6442 } 6443 6444 /** 6445 * Set the enabled state of this view. The interpretation of the enabled 6446 * state varies by subclass. 6447 * 6448 * @param enabled True if this view is enabled, false otherwise. 6449 */ 6450 @RemotableViewMethod 6451 public void setEnabled(boolean enabled) { 6452 if (enabled == isEnabled()) return; 6453 6454 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 6455 6456 /* 6457 * The View most likely has to change its appearance, so refresh 6458 * the drawable state. 6459 */ 6460 refreshDrawableState(); 6461 6462 // Invalidate too, since the default behavior for views is to be 6463 // be drawn at 50% alpha rather than to change the drawable. 6464 invalidate(true); 6465 6466 if (!enabled) { 6467 cancelPendingInputEvents(); 6468 } 6469 } 6470 6471 /** 6472 * Set whether this view can receive the focus. 6473 * 6474 * Setting this to false will also ensure that this view is not focusable 6475 * in touch mode. 6476 * 6477 * @param focusable If true, this view can receive the focus. 6478 * 6479 * @see #setFocusableInTouchMode(boolean) 6480 * @attr ref android.R.styleable#View_focusable 6481 */ 6482 public void setFocusable(boolean focusable) { 6483 if (!focusable) { 6484 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 6485 } 6486 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 6487 } 6488 6489 /** 6490 * Set whether this view can receive focus while in touch mode. 6491 * 6492 * Setting this to true will also ensure that this view is focusable. 6493 * 6494 * @param focusableInTouchMode If true, this view can receive the focus while 6495 * in touch mode. 6496 * 6497 * @see #setFocusable(boolean) 6498 * @attr ref android.R.styleable#View_focusableInTouchMode 6499 */ 6500 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 6501 // Focusable in touch mode should always be set before the focusable flag 6502 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 6503 // which, in touch mode, will not successfully request focus on this view 6504 // because the focusable in touch mode flag is not set 6505 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 6506 if (focusableInTouchMode) { 6507 setFlags(FOCUSABLE, FOCUSABLE_MASK); 6508 } 6509 } 6510 6511 /** 6512 * Set whether this view should have sound effects enabled for events such as 6513 * clicking and touching. 6514 * 6515 * <p>You may wish to disable sound effects for a view if you already play sounds, 6516 * for instance, a dial key that plays dtmf tones. 6517 * 6518 * @param soundEffectsEnabled whether sound effects are enabled for this view. 6519 * @see #isSoundEffectsEnabled() 6520 * @see #playSoundEffect(int) 6521 * @attr ref android.R.styleable#View_soundEffectsEnabled 6522 */ 6523 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 6524 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 6525 } 6526 6527 /** 6528 * @return whether this view should have sound effects enabled for events such as 6529 * clicking and touching. 6530 * 6531 * @see #setSoundEffectsEnabled(boolean) 6532 * @see #playSoundEffect(int) 6533 * @attr ref android.R.styleable#View_soundEffectsEnabled 6534 */ 6535 @ViewDebug.ExportedProperty 6536 public boolean isSoundEffectsEnabled() { 6537 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 6538 } 6539 6540 /** 6541 * Set whether this view should have haptic feedback for events such as 6542 * long presses. 6543 * 6544 * <p>You may wish to disable haptic feedback if your view already controls 6545 * its own haptic feedback. 6546 * 6547 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 6548 * @see #isHapticFeedbackEnabled() 6549 * @see #performHapticFeedback(int) 6550 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6551 */ 6552 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 6553 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 6554 } 6555 6556 /** 6557 * @return whether this view should have haptic feedback enabled for events 6558 * long presses. 6559 * 6560 * @see #setHapticFeedbackEnabled(boolean) 6561 * @see #performHapticFeedback(int) 6562 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6563 */ 6564 @ViewDebug.ExportedProperty 6565 public boolean isHapticFeedbackEnabled() { 6566 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 6567 } 6568 6569 /** 6570 * Returns the layout direction for this view. 6571 * 6572 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 6573 * {@link #LAYOUT_DIRECTION_RTL}, 6574 * {@link #LAYOUT_DIRECTION_INHERIT} or 6575 * {@link #LAYOUT_DIRECTION_LOCALE}. 6576 * 6577 * @attr ref android.R.styleable#View_layoutDirection 6578 * 6579 * @hide 6580 */ 6581 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6582 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 6583 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 6584 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 6585 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 6586 }) 6587 @LayoutDir 6588 public int getRawLayoutDirection() { 6589 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 6590 } 6591 6592 /** 6593 * Set the layout direction for this view. This will propagate a reset of layout direction 6594 * resolution to the view's children and resolve layout direction for this view. 6595 * 6596 * @param layoutDirection the layout direction to set. Should be one of: 6597 * 6598 * {@link #LAYOUT_DIRECTION_LTR}, 6599 * {@link #LAYOUT_DIRECTION_RTL}, 6600 * {@link #LAYOUT_DIRECTION_INHERIT}, 6601 * {@link #LAYOUT_DIRECTION_LOCALE}. 6602 * 6603 * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution 6604 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 6605 * will return the default {@link #LAYOUT_DIRECTION_LTR}. 6606 * 6607 * @attr ref android.R.styleable#View_layoutDirection 6608 */ 6609 @RemotableViewMethod 6610 public void setLayoutDirection(@LayoutDir int layoutDirection) { 6611 if (getRawLayoutDirection() != layoutDirection) { 6612 // Reset the current layout direction and the resolved one 6613 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK; 6614 resetRtlProperties(); 6615 // Set the new layout direction (filtered) 6616 mPrivateFlags2 |= 6617 ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK); 6618 // We need to resolve all RTL properties as they all depend on layout direction 6619 resolveRtlPropertiesIfNeeded(); 6620 requestLayout(); 6621 invalidate(true); 6622 } 6623 } 6624 6625 /** 6626 * Returns the resolved layout direction for this view. 6627 * 6628 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 6629 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL. 6630 * 6631 * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version 6632 * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}. 6633 * 6634 * @attr ref android.R.styleable#View_layoutDirection 6635 */ 6636 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6637 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 6638 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 6639 }) 6640 @ResolvedLayoutDir 6641 public int getLayoutDirection() { 6642 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 6643 if (targetSdkVersion < JELLY_BEAN_MR1) { 6644 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 6645 return LAYOUT_DIRECTION_RESOLVED_DEFAULT; 6646 } 6647 return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) == 6648 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 6649 } 6650 6651 /** 6652 * Indicates whether or not this view's layout is right-to-left. This is resolved from 6653 * layout attribute and/or the inherited value from the parent 6654 * 6655 * @return true if the layout is right-to-left. 6656 * 6657 * @hide 6658 */ 6659 @ViewDebug.ExportedProperty(category = "layout") 6660 public boolean isLayoutRtl() { 6661 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL); 6662 } 6663 6664 /** 6665 * Indicates whether the view is currently tracking transient state that the 6666 * app should not need to concern itself with saving and restoring, but that 6667 * the framework should take special note to preserve when possible. 6668 * 6669 * <p>A view with transient state cannot be trivially rebound from an external 6670 * data source, such as an adapter binding item views in a list. This may be 6671 * because the view is performing an animation, tracking user selection 6672 * of content, or similar.</p> 6673 * 6674 * @return true if the view has transient state 6675 */ 6676 @ViewDebug.ExportedProperty(category = "layout") 6677 public boolean hasTransientState() { 6678 return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE; 6679 } 6680 6681 /** 6682 * Set whether this view is currently tracking transient state that the 6683 * framework should attempt to preserve when possible. This flag is reference counted, 6684 * so every call to setHasTransientState(true) should be paired with a later call 6685 * to setHasTransientState(false). 6686 * 6687 * <p>A view with transient state cannot be trivially rebound from an external 6688 * data source, such as an adapter binding item views in a list. This may be 6689 * because the view is performing an animation, tracking user selection 6690 * of content, or similar.</p> 6691 * 6692 * @param hasTransientState true if this view has transient state 6693 */ 6694 public void setHasTransientState(boolean hasTransientState) { 6695 mTransientStateCount = hasTransientState ? mTransientStateCount + 1 : 6696 mTransientStateCount - 1; 6697 if (mTransientStateCount < 0) { 6698 mTransientStateCount = 0; 6699 Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " + 6700 "unmatched pair of setHasTransientState calls"); 6701 } else if ((hasTransientState && mTransientStateCount == 1) || 6702 (!hasTransientState && mTransientStateCount == 0)) { 6703 // update flag if we've just incremented up from 0 or decremented down to 0 6704 mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) | 6705 (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0); 6706 if (mParent != null) { 6707 try { 6708 mParent.childHasTransientStateChanged(this, hasTransientState); 6709 } catch (AbstractMethodError e) { 6710 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 6711 " does not fully implement ViewParent", e); 6712 } 6713 } 6714 } 6715 } 6716 6717 /** 6718 * Returns true if this view is currently attached to a window. 6719 */ 6720 public boolean isAttachedToWindow() { 6721 return mAttachInfo != null; 6722 } 6723 6724 /** 6725 * Returns true if this view has been through at least one layout since it 6726 * was last attached to or detached from a window. 6727 */ 6728 public boolean isLaidOut() { 6729 return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT; 6730 } 6731 6732 /** 6733 * If this view doesn't do any drawing on its own, set this flag to 6734 * allow further optimizations. By default, this flag is not set on 6735 * View, but could be set on some View subclasses such as ViewGroup. 6736 * 6737 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 6738 * you should clear this flag. 6739 * 6740 * @param willNotDraw whether or not this View draw on its own 6741 */ 6742 public void setWillNotDraw(boolean willNotDraw) { 6743 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 6744 } 6745 6746 /** 6747 * Returns whether or not this View draws on its own. 6748 * 6749 * @return true if this view has nothing to draw, false otherwise 6750 */ 6751 @ViewDebug.ExportedProperty(category = "drawing") 6752 public boolean willNotDraw() { 6753 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 6754 } 6755 6756 /** 6757 * When a View's drawing cache is enabled, drawing is redirected to an 6758 * offscreen bitmap. Some views, like an ImageView, must be able to 6759 * bypass this mechanism if they already draw a single bitmap, to avoid 6760 * unnecessary usage of the memory. 6761 * 6762 * @param willNotCacheDrawing true if this view does not cache its 6763 * drawing, false otherwise 6764 */ 6765 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 6766 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 6767 } 6768 6769 /** 6770 * Returns whether or not this View can cache its drawing or not. 6771 * 6772 * @return true if this view does not cache its drawing, false otherwise 6773 */ 6774 @ViewDebug.ExportedProperty(category = "drawing") 6775 public boolean willNotCacheDrawing() { 6776 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 6777 } 6778 6779 /** 6780 * Indicates whether this view reacts to click events or not. 6781 * 6782 * @return true if the view is clickable, false otherwise 6783 * 6784 * @see #setClickable(boolean) 6785 * @attr ref android.R.styleable#View_clickable 6786 */ 6787 @ViewDebug.ExportedProperty 6788 public boolean isClickable() { 6789 return (mViewFlags & CLICKABLE) == CLICKABLE; 6790 } 6791 6792 /** 6793 * Enables or disables click events for this view. When a view 6794 * is clickable it will change its state to "pressed" on every click. 6795 * Subclasses should set the view clickable to visually react to 6796 * user's clicks. 6797 * 6798 * @param clickable true to make the view clickable, false otherwise 6799 * 6800 * @see #isClickable() 6801 * @attr ref android.R.styleable#View_clickable 6802 */ 6803 public void setClickable(boolean clickable) { 6804 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 6805 } 6806 6807 /** 6808 * Indicates whether this view reacts to long click events or not. 6809 * 6810 * @return true if the view is long clickable, false otherwise 6811 * 6812 * @see #setLongClickable(boolean) 6813 * @attr ref android.R.styleable#View_longClickable 6814 */ 6815 public boolean isLongClickable() { 6816 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 6817 } 6818 6819 /** 6820 * Enables or disables long click events for this view. When a view is long 6821 * clickable it reacts to the user holding down the button for a longer 6822 * duration than a tap. This event can either launch the listener or a 6823 * context menu. 6824 * 6825 * @param longClickable true to make the view long clickable, false otherwise 6826 * @see #isLongClickable() 6827 * @attr ref android.R.styleable#View_longClickable 6828 */ 6829 public void setLongClickable(boolean longClickable) { 6830 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 6831 } 6832 6833 /** 6834 * Sets the pressed state for this view and provides a touch coordinate for 6835 * animation hinting. 6836 * 6837 * @param pressed Pass true to set the View's internal state to "pressed", 6838 * or false to reverts the View's internal state from a 6839 * previously set "pressed" state. 6840 * @param x The x coordinate of the touch that caused the press 6841 * @param y The y coordinate of the touch that caused the press 6842 */ 6843 private void setPressed(boolean pressed, float x, float y) { 6844 if (pressed) { 6845 drawableHotspotChanged(x, y); 6846 } 6847 6848 setPressed(pressed); 6849 } 6850 6851 /** 6852 * Sets the pressed state for this view. 6853 * 6854 * @see #isClickable() 6855 * @see #setClickable(boolean) 6856 * 6857 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 6858 * the View's internal state from a previously set "pressed" state. 6859 */ 6860 public void setPressed(boolean pressed) { 6861 final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED); 6862 6863 if (pressed) { 6864 mPrivateFlags |= PFLAG_PRESSED; 6865 } else { 6866 mPrivateFlags &= ~PFLAG_PRESSED; 6867 } 6868 6869 if (needsRefresh) { 6870 refreshDrawableState(); 6871 } 6872 dispatchSetPressed(pressed); 6873 } 6874 6875 /** 6876 * Dispatch setPressed to all of this View's children. 6877 * 6878 * @see #setPressed(boolean) 6879 * 6880 * @param pressed The new pressed state 6881 */ 6882 protected void dispatchSetPressed(boolean pressed) { 6883 } 6884 6885 /** 6886 * Indicates whether the view is currently in pressed state. Unless 6887 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 6888 * the pressed state. 6889 * 6890 * @see #setPressed(boolean) 6891 * @see #isClickable() 6892 * @see #setClickable(boolean) 6893 * 6894 * @return true if the view is currently pressed, false otherwise 6895 */ 6896 public boolean isPressed() { 6897 return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED; 6898 } 6899 6900 /** 6901 * Indicates whether this view will save its state (that is, 6902 * whether its {@link #onSaveInstanceState} method will be called). 6903 * 6904 * @return Returns true if the view state saving is enabled, else false. 6905 * 6906 * @see #setSaveEnabled(boolean) 6907 * @attr ref android.R.styleable#View_saveEnabled 6908 */ 6909 public boolean isSaveEnabled() { 6910 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 6911 } 6912 6913 /** 6914 * Controls whether the saving of this view's state is 6915 * enabled (that is, whether its {@link #onSaveInstanceState} method 6916 * will be called). Note that even if freezing is enabled, the 6917 * view still must have an id assigned to it (via {@link #setId(int)}) 6918 * for its state to be saved. This flag can only disable the 6919 * saving of this view; any child views may still have their state saved. 6920 * 6921 * @param enabled Set to false to <em>disable</em> state saving, or true 6922 * (the default) to allow it. 6923 * 6924 * @see #isSaveEnabled() 6925 * @see #setId(int) 6926 * @see #onSaveInstanceState() 6927 * @attr ref android.R.styleable#View_saveEnabled 6928 */ 6929 public void setSaveEnabled(boolean enabled) { 6930 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 6931 } 6932 6933 /** 6934 * Gets whether the framework should discard touches when the view's 6935 * window is obscured by another visible window. 6936 * Refer to the {@link View} security documentation for more details. 6937 * 6938 * @return True if touch filtering is enabled. 6939 * 6940 * @see #setFilterTouchesWhenObscured(boolean) 6941 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 6942 */ 6943 @ViewDebug.ExportedProperty 6944 public boolean getFilterTouchesWhenObscured() { 6945 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 6946 } 6947 6948 /** 6949 * Sets whether the framework should discard touches when the view's 6950 * window is obscured by another visible window. 6951 * Refer to the {@link View} security documentation for more details. 6952 * 6953 * @param enabled True if touch filtering should be enabled. 6954 * 6955 * @see #getFilterTouchesWhenObscured 6956 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 6957 */ 6958 public void setFilterTouchesWhenObscured(boolean enabled) { 6959 setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0, 6960 FILTER_TOUCHES_WHEN_OBSCURED); 6961 } 6962 6963 /** 6964 * Indicates whether the entire hierarchy under this view will save its 6965 * state when a state saving traversal occurs from its parent. The default 6966 * is true; if false, these views will not be saved unless 6967 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 6968 * 6969 * @return Returns true if the view state saving from parent is enabled, else false. 6970 * 6971 * @see #setSaveFromParentEnabled(boolean) 6972 */ 6973 public boolean isSaveFromParentEnabled() { 6974 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 6975 } 6976 6977 /** 6978 * Controls whether the entire hierarchy under this view will save its 6979 * state when a state saving traversal occurs from its parent. The default 6980 * is true; if false, these views will not be saved unless 6981 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 6982 * 6983 * @param enabled Set to false to <em>disable</em> state saving, or true 6984 * (the default) to allow it. 6985 * 6986 * @see #isSaveFromParentEnabled() 6987 * @see #setId(int) 6988 * @see #onSaveInstanceState() 6989 */ 6990 public void setSaveFromParentEnabled(boolean enabled) { 6991 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 6992 } 6993 6994 6995 /** 6996 * Returns whether this View is able to take focus. 6997 * 6998 * @return True if this view can take focus, or false otherwise. 6999 * @attr ref android.R.styleable#View_focusable 7000 */ 7001 @ViewDebug.ExportedProperty(category = "focus") 7002 public final boolean isFocusable() { 7003 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 7004 } 7005 7006 /** 7007 * When a view is focusable, it may not want to take focus when in touch mode. 7008 * For example, a button would like focus when the user is navigating via a D-pad 7009 * so that the user can click on it, but once the user starts touching the screen, 7010 * the button shouldn't take focus 7011 * @return Whether the view is focusable in touch mode. 7012 * @attr ref android.R.styleable#View_focusableInTouchMode 7013 */ 7014 @ViewDebug.ExportedProperty 7015 public final boolean isFocusableInTouchMode() { 7016 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 7017 } 7018 7019 /** 7020 * Find the nearest view in the specified direction that can take focus. 7021 * This does not actually give focus to that view. 7022 * 7023 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7024 * 7025 * @return The nearest focusable in the specified direction, or null if none 7026 * can be found. 7027 */ 7028 public View focusSearch(@FocusRealDirection int direction) { 7029 if (mParent != null) { 7030 return mParent.focusSearch(this, direction); 7031 } else { 7032 return null; 7033 } 7034 } 7035 7036 /** 7037 * This method is the last chance for the focused view and its ancestors to 7038 * respond to an arrow key. This is called when the focused view did not 7039 * consume the key internally, nor could the view system find a new view in 7040 * the requested direction to give focus to. 7041 * 7042 * @param focused The currently focused view. 7043 * @param direction The direction focus wants to move. One of FOCUS_UP, 7044 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 7045 * @return True if the this view consumed this unhandled move. 7046 */ 7047 public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) { 7048 return false; 7049 } 7050 7051 /** 7052 * If a user manually specified the next view id for a particular direction, 7053 * use the root to look up the view. 7054 * @param root The root view of the hierarchy containing this view. 7055 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 7056 * or FOCUS_BACKWARD. 7057 * @return The user specified next view, or null if there is none. 7058 */ 7059 View findUserSetNextFocus(View root, @FocusDirection int direction) { 7060 switch (direction) { 7061 case FOCUS_LEFT: 7062 if (mNextFocusLeftId == View.NO_ID) return null; 7063 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 7064 case FOCUS_RIGHT: 7065 if (mNextFocusRightId == View.NO_ID) return null; 7066 return findViewInsideOutShouldExist(root, mNextFocusRightId); 7067 case FOCUS_UP: 7068 if (mNextFocusUpId == View.NO_ID) return null; 7069 return findViewInsideOutShouldExist(root, mNextFocusUpId); 7070 case FOCUS_DOWN: 7071 if (mNextFocusDownId == View.NO_ID) return null; 7072 return findViewInsideOutShouldExist(root, mNextFocusDownId); 7073 case FOCUS_FORWARD: 7074 if (mNextFocusForwardId == View.NO_ID) return null; 7075 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 7076 case FOCUS_BACKWARD: { 7077 if (mID == View.NO_ID) return null; 7078 final int id = mID; 7079 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 7080 @Override 7081 public boolean apply(View t) { 7082 return t.mNextFocusForwardId == id; 7083 } 7084 }); 7085 } 7086 } 7087 return null; 7088 } 7089 7090 private View findViewInsideOutShouldExist(View root, int id) { 7091 if (mMatchIdPredicate == null) { 7092 mMatchIdPredicate = new MatchIdPredicate(); 7093 } 7094 mMatchIdPredicate.mId = id; 7095 View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate); 7096 if (result == null) { 7097 Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id); 7098 } 7099 return result; 7100 } 7101 7102 /** 7103 * Find and return all focusable views that are descendants of this view, 7104 * possibly including this view if it is focusable itself. 7105 * 7106 * @param direction The direction of the focus 7107 * @return A list of focusable views 7108 */ 7109 public ArrayList<View> getFocusables(@FocusDirection int direction) { 7110 ArrayList<View> result = new ArrayList<View>(24); 7111 addFocusables(result, direction); 7112 return result; 7113 } 7114 7115 /** 7116 * Add any focusable views that are descendants of this view (possibly 7117 * including this view if it is focusable itself) to views. If we are in touch mode, 7118 * only add views that are also focusable in touch mode. 7119 * 7120 * @param views Focusable views found so far 7121 * @param direction The direction of the focus 7122 */ 7123 public void addFocusables(ArrayList<View> views, @FocusDirection int direction) { 7124 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 7125 } 7126 7127 /** 7128 * Adds any focusable views that are descendants of this view (possibly 7129 * including this view if it is focusable itself) to views. This method 7130 * adds all focusable views regardless if we are in touch mode or 7131 * only views focusable in touch mode if we are in touch mode or 7132 * only views that can take accessibility focus if accessibility is enabeld 7133 * depending on the focusable mode paramater. 7134 * 7135 * @param views Focusable views found so far or null if all we are interested is 7136 * the number of focusables. 7137 * @param direction The direction of the focus. 7138 * @param focusableMode The type of focusables to be added. 7139 * 7140 * @see #FOCUSABLES_ALL 7141 * @see #FOCUSABLES_TOUCH_MODE 7142 */ 7143 public void addFocusables(ArrayList<View> views, @FocusDirection int direction, 7144 @FocusableMode int focusableMode) { 7145 if (views == null) { 7146 return; 7147 } 7148 if (!isFocusable()) { 7149 return; 7150 } 7151 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE 7152 && isInTouchMode() && !isFocusableInTouchMode()) { 7153 return; 7154 } 7155 views.add(this); 7156 } 7157 7158 /** 7159 * Finds the Views that contain given text. The containment is case insensitive. 7160 * The search is performed by either the text that the View renders or the content 7161 * description that describes the view for accessibility purposes and the view does 7162 * not render or both. Clients can specify how the search is to be performed via 7163 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 7164 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 7165 * 7166 * @param outViews The output list of matching Views. 7167 * @param searched The text to match against. 7168 * 7169 * @see #FIND_VIEWS_WITH_TEXT 7170 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 7171 * @see #setContentDescription(CharSequence) 7172 */ 7173 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, 7174 @FindViewFlags int flags) { 7175 if (getAccessibilityNodeProvider() != null) { 7176 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 7177 outViews.add(this); 7178 } 7179 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 7180 && (searched != null && searched.length() > 0) 7181 && (mContentDescription != null && mContentDescription.length() > 0)) { 7182 String searchedLowerCase = searched.toString().toLowerCase(); 7183 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 7184 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 7185 outViews.add(this); 7186 } 7187 } 7188 } 7189 7190 /** 7191 * Find and return all touchable views that are descendants of this view, 7192 * possibly including this view if it is touchable itself. 7193 * 7194 * @return A list of touchable views 7195 */ 7196 public ArrayList<View> getTouchables() { 7197 ArrayList<View> result = new ArrayList<View>(); 7198 addTouchables(result); 7199 return result; 7200 } 7201 7202 /** 7203 * Add any touchable views that are descendants of this view (possibly 7204 * including this view if it is touchable itself) to views. 7205 * 7206 * @param views Touchable views found so far 7207 */ 7208 public void addTouchables(ArrayList<View> views) { 7209 final int viewFlags = mViewFlags; 7210 7211 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 7212 && (viewFlags & ENABLED_MASK) == ENABLED) { 7213 views.add(this); 7214 } 7215 } 7216 7217 /** 7218 * Returns whether this View is accessibility focused. 7219 * 7220 * @return True if this View is accessibility focused. 7221 */ 7222 public boolean isAccessibilityFocused() { 7223 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0; 7224 } 7225 7226 /** 7227 * Call this to try to give accessibility focus to this view. 7228 * 7229 * A view will not actually take focus if {@link AccessibilityManager#isEnabled()} 7230 * returns false or the view is no visible or the view already has accessibility 7231 * focus. 7232 * 7233 * See also {@link #focusSearch(int)}, which is what you call to say that you 7234 * have focus, and you want your parent to look for the next one. 7235 * 7236 * @return Whether this view actually took accessibility focus. 7237 * 7238 * @hide 7239 */ 7240 public boolean requestAccessibilityFocus() { 7241 AccessibilityManager manager = AccessibilityManager.getInstance(mContext); 7242 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 7243 return false; 7244 } 7245 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7246 return false; 7247 } 7248 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) { 7249 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED; 7250 ViewRootImpl viewRootImpl = getViewRootImpl(); 7251 if (viewRootImpl != null) { 7252 viewRootImpl.setAccessibilityFocus(this, null); 7253 } 7254 invalidate(); 7255 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); 7256 return true; 7257 } 7258 return false; 7259 } 7260 7261 /** 7262 * Call this to try to clear accessibility focus of this view. 7263 * 7264 * See also {@link #focusSearch(int)}, which is what you call to say that you 7265 * have focus, and you want your parent to look for the next one. 7266 * 7267 * @hide 7268 */ 7269 public void clearAccessibilityFocus() { 7270 clearAccessibilityFocusNoCallbacks(); 7271 // Clear the global reference of accessibility focus if this 7272 // view or any of its descendants had accessibility focus. 7273 ViewRootImpl viewRootImpl = getViewRootImpl(); 7274 if (viewRootImpl != null) { 7275 View focusHost = viewRootImpl.getAccessibilityFocusedHost(); 7276 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 7277 viewRootImpl.setAccessibilityFocus(null, null); 7278 } 7279 } 7280 } 7281 7282 private void sendAccessibilityHoverEvent(int eventType) { 7283 // Since we are not delivering to a client accessibility events from not 7284 // important views (unless the clinet request that) we need to fire the 7285 // event from the deepest view exposed to the client. As a consequence if 7286 // the user crosses a not exposed view the client will see enter and exit 7287 // of the exposed predecessor followed by and enter and exit of that same 7288 // predecessor when entering and exiting the not exposed descendant. This 7289 // is fine since the client has a clear idea which view is hovered at the 7290 // price of a couple more events being sent. This is a simple and 7291 // working solution. 7292 View source = this; 7293 while (true) { 7294 if (source.includeForAccessibility()) { 7295 source.sendAccessibilityEvent(eventType); 7296 return; 7297 } 7298 ViewParent parent = source.getParent(); 7299 if (parent instanceof View) { 7300 source = (View) parent; 7301 } else { 7302 return; 7303 } 7304 } 7305 } 7306 7307 /** 7308 * Clears accessibility focus without calling any callback methods 7309 * normally invoked in {@link #clearAccessibilityFocus()}. This method 7310 * is used for clearing accessibility focus when giving this focus to 7311 * another view. 7312 */ 7313 void clearAccessibilityFocusNoCallbacks() { 7314 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 7315 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 7316 invalidate(); 7317 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); 7318 } 7319 } 7320 7321 /** 7322 * Call this to try to give focus to a specific view or to one of its 7323 * descendants. 7324 * 7325 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7326 * false), or if it is focusable and it is not focusable in touch mode 7327 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7328 * 7329 * See also {@link #focusSearch(int)}, which is what you call to say that you 7330 * have focus, and you want your parent to look for the next one. 7331 * 7332 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 7333 * {@link #FOCUS_DOWN} and <code>null</code>. 7334 * 7335 * @return Whether this view or one of its descendants actually took focus. 7336 */ 7337 public final boolean requestFocus() { 7338 return requestFocus(View.FOCUS_DOWN); 7339 } 7340 7341 /** 7342 * Call this to try to give focus to a specific view or to one of its 7343 * descendants and give it a hint about what direction focus is heading. 7344 * 7345 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7346 * false), or if it is focusable and it is not focusable in touch mode 7347 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7348 * 7349 * See also {@link #focusSearch(int)}, which is what you call to say that you 7350 * have focus, and you want your parent to look for the next one. 7351 * 7352 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 7353 * <code>null</code> set for the previously focused rectangle. 7354 * 7355 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7356 * @return Whether this view or one of its descendants actually took focus. 7357 */ 7358 public final boolean requestFocus(int direction) { 7359 return requestFocus(direction, null); 7360 } 7361 7362 /** 7363 * Call this to try to give focus to a specific view or to one of its descendants 7364 * and give it hints about the direction and a specific rectangle that the focus 7365 * is coming from. The rectangle can help give larger views a finer grained hint 7366 * about where focus is coming from, and therefore, where to show selection, or 7367 * forward focus change internally. 7368 * 7369 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7370 * false), or if it is focusable and it is not focusable in touch mode 7371 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7372 * 7373 * A View will not take focus if it is not visible. 7374 * 7375 * A View will not take focus if one of its parents has 7376 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 7377 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 7378 * 7379 * See also {@link #focusSearch(int)}, which is what you call to say that you 7380 * have focus, and you want your parent to look for the next one. 7381 * 7382 * You may wish to override this method if your custom {@link View} has an internal 7383 * {@link View} that it wishes to forward the request to. 7384 * 7385 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7386 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 7387 * to give a finer grained hint about where focus is coming from. May be null 7388 * if there is no hint. 7389 * @return Whether this view or one of its descendants actually took focus. 7390 */ 7391 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 7392 return requestFocusNoSearch(direction, previouslyFocusedRect); 7393 } 7394 7395 private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) { 7396 // need to be focusable 7397 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 7398 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7399 return false; 7400 } 7401 7402 // need to be focusable in touch mode if in touch mode 7403 if (isInTouchMode() && 7404 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 7405 return false; 7406 } 7407 7408 // need to not have any parents blocking us 7409 if (hasAncestorThatBlocksDescendantFocus()) { 7410 return false; 7411 } 7412 7413 handleFocusGainInternal(direction, previouslyFocusedRect); 7414 return true; 7415 } 7416 7417 /** 7418 * Call this to try to give focus to a specific view or to one of its descendants. This is a 7419 * special variant of {@link #requestFocus() } that will allow views that are not focuable in 7420 * touch mode to request focus when they are touched. 7421 * 7422 * @return Whether this view or one of its descendants actually took focus. 7423 * 7424 * @see #isInTouchMode() 7425 * 7426 */ 7427 public final boolean requestFocusFromTouch() { 7428 // Leave touch mode if we need to 7429 if (isInTouchMode()) { 7430 ViewRootImpl viewRoot = getViewRootImpl(); 7431 if (viewRoot != null) { 7432 viewRoot.ensureTouchMode(false); 7433 } 7434 } 7435 return requestFocus(View.FOCUS_DOWN); 7436 } 7437 7438 /** 7439 * @return Whether any ancestor of this view blocks descendant focus. 7440 */ 7441 private boolean hasAncestorThatBlocksDescendantFocus() { 7442 ViewParent ancestor = mParent; 7443 while (ancestor instanceof ViewGroup) { 7444 final ViewGroup vgAncestor = (ViewGroup) ancestor; 7445 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS 7446 || vgAncestor.shouldBlockFocusForTouchscreen()) { 7447 return true; 7448 } else { 7449 ancestor = vgAncestor.getParent(); 7450 } 7451 } 7452 return false; 7453 } 7454 7455 /** 7456 * Gets the mode for determining whether this View is important for accessibility 7457 * which is if it fires accessibility events and if it is reported to 7458 * accessibility services that query the screen. 7459 * 7460 * @return The mode for determining whether a View is important for accessibility. 7461 * 7462 * @attr ref android.R.styleable#View_importantForAccessibility 7463 * 7464 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 7465 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 7466 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 7467 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 7468 */ 7469 @ViewDebug.ExportedProperty(category = "accessibility", mapping = { 7470 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"), 7471 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"), 7472 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"), 7473 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS, 7474 to = "noHideDescendants") 7475 }) 7476 public int getImportantForAccessibility() { 7477 return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 7478 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 7479 } 7480 7481 /** 7482 * Sets the live region mode for this view. This indicates to accessibility 7483 * services whether they should automatically notify the user about changes 7484 * to the view's content description or text, or to the content descriptions 7485 * or text of the view's children (where applicable). 7486 * <p> 7487 * For example, in a login screen with a TextView that displays an "incorrect 7488 * password" notification, that view should be marked as a live region with 7489 * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 7490 * <p> 7491 * To disable change notifications for this view, use 7492 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region 7493 * mode for most views. 7494 * <p> 7495 * To indicate that the user should be notified of changes, use 7496 * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 7497 * <p> 7498 * If the view's changes should interrupt ongoing speech and notify the user 7499 * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}. 7500 * 7501 * @param mode The live region mode for this view, one of: 7502 * <ul> 7503 * <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE} 7504 * <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE} 7505 * <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE} 7506 * </ul> 7507 * @attr ref android.R.styleable#View_accessibilityLiveRegion 7508 */ 7509 public void setAccessibilityLiveRegion(int mode) { 7510 if (mode != getAccessibilityLiveRegion()) { 7511 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 7512 mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT) 7513 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 7514 notifyViewAccessibilityStateChangedIfNeeded( 7515 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7516 } 7517 } 7518 7519 /** 7520 * Gets the live region mode for this View. 7521 * 7522 * @return The live region mode for the view. 7523 * 7524 * @attr ref android.R.styleable#View_accessibilityLiveRegion 7525 * 7526 * @see #setAccessibilityLiveRegion(int) 7527 */ 7528 public int getAccessibilityLiveRegion() { 7529 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK) 7530 >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 7531 } 7532 7533 /** 7534 * Sets how to determine whether this view is important for accessibility 7535 * which is if it fires accessibility events and if it is reported to 7536 * accessibility services that query the screen. 7537 * 7538 * @param mode How to determine whether this view is important for accessibility. 7539 * 7540 * @attr ref android.R.styleable#View_importantForAccessibility 7541 * 7542 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 7543 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 7544 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 7545 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 7546 */ 7547 public void setImportantForAccessibility(int mode) { 7548 final int oldMode = getImportantForAccessibility(); 7549 if (mode != oldMode) { 7550 // If we're moving between AUTO and another state, we might not need 7551 // to send a subtree changed notification. We'll store the computed 7552 // importance, since we'll need to check it later to make sure. 7553 final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO 7554 || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO; 7555 final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility(); 7556 mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 7557 mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT) 7558 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 7559 if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) { 7560 notifySubtreeAccessibilityStateChangedIfNeeded(); 7561 } else { 7562 notifyViewAccessibilityStateChangedIfNeeded( 7563 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7564 } 7565 } 7566 } 7567 7568 /** 7569 * Computes whether this view should be exposed for accessibility. In 7570 * general, views that are interactive or provide information are exposed 7571 * while views that serve only as containers are hidden. 7572 * <p> 7573 * If an ancestor of this view has importance 7574 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method 7575 * returns <code>false</code>. 7576 * <p> 7577 * Otherwise, the value is computed according to the view's 7578 * {@link #getImportantForAccessibility()} value: 7579 * <ol> 7580 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or 7581 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false 7582 * </code> 7583 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code> 7584 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if 7585 * view satisfies any of the following: 7586 * <ul> 7587 * <li>Is actionable, e.g. {@link #isClickable()}, 7588 * {@link #isLongClickable()}, or {@link #isFocusable()} 7589 * <li>Has an {@link AccessibilityDelegate} 7590 * <li>Has an interaction listener, e.g. {@link OnTouchListener}, 7591 * {@link OnKeyListener}, etc. 7592 * <li>Is an accessibility live region, e.g. 7593 * {@link #getAccessibilityLiveRegion()} is not 7594 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. 7595 * </ul> 7596 * </ol> 7597 * 7598 * @return Whether the view is exposed for accessibility. 7599 * @see #setImportantForAccessibility(int) 7600 * @see #getImportantForAccessibility() 7601 */ 7602 public boolean isImportantForAccessibility() { 7603 final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 7604 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 7605 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO 7606 || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 7607 return false; 7608 } 7609 7610 // Check parent mode to ensure we're not hidden. 7611 ViewParent parent = mParent; 7612 while (parent instanceof View) { 7613 if (((View) parent).getImportantForAccessibility() 7614 == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 7615 return false; 7616 } 7617 parent = parent.getParent(); 7618 } 7619 7620 return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility() 7621 || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null 7622 || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE; 7623 } 7624 7625 /** 7626 * Gets the parent for accessibility purposes. Note that the parent for 7627 * accessibility is not necessary the immediate parent. It is the first 7628 * predecessor that is important for accessibility. 7629 * 7630 * @return The parent for accessibility purposes. 7631 */ 7632 public ViewParent getParentForAccessibility() { 7633 if (mParent instanceof View) { 7634 View parentView = (View) mParent; 7635 if (parentView.includeForAccessibility()) { 7636 return mParent; 7637 } else { 7638 return mParent.getParentForAccessibility(); 7639 } 7640 } 7641 return null; 7642 } 7643 7644 /** 7645 * Adds the children of a given View for accessibility. Since some Views are 7646 * not important for accessibility the children for accessibility are not 7647 * necessarily direct children of the view, rather they are the first level of 7648 * descendants important for accessibility. 7649 * 7650 * @param children The list of children for accessibility. 7651 */ 7652 public void addChildrenForAccessibility(ArrayList<View> children) { 7653 7654 } 7655 7656 /** 7657 * Whether to regard this view for accessibility. A view is regarded for 7658 * accessibility if it is important for accessibility or the querying 7659 * accessibility service has explicitly requested that view not 7660 * important for accessibility are regarded. 7661 * 7662 * @return Whether to regard the view for accessibility. 7663 * 7664 * @hide 7665 */ 7666 public boolean includeForAccessibility() { 7667 if (mAttachInfo != null) { 7668 return (mAttachInfo.mAccessibilityFetchFlags 7669 & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0 7670 || isImportantForAccessibility(); 7671 } 7672 return false; 7673 } 7674 7675 /** 7676 * Returns whether the View is considered actionable from 7677 * accessibility perspective. Such view are important for 7678 * accessibility. 7679 * 7680 * @return True if the view is actionable for accessibility. 7681 * 7682 * @hide 7683 */ 7684 public boolean isActionableForAccessibility() { 7685 return (isClickable() || isLongClickable() || isFocusable()); 7686 } 7687 7688 /** 7689 * Returns whether the View has registered callbacks which makes it 7690 * important for accessibility. 7691 * 7692 * @return True if the view is actionable for accessibility. 7693 */ 7694 private boolean hasListenersForAccessibility() { 7695 ListenerInfo info = getListenerInfo(); 7696 return mTouchDelegate != null || info.mOnKeyListener != null 7697 || info.mOnTouchListener != null || info.mOnGenericMotionListener != null 7698 || info.mOnHoverListener != null || info.mOnDragListener != null; 7699 } 7700 7701 /** 7702 * Notifies that the accessibility state of this view changed. The change 7703 * is local to this view and does not represent structural changes such 7704 * as children and parent. For example, the view became focusable. The 7705 * notification is at at most once every 7706 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 7707 * to avoid unnecessary load to the system. Also once a view has a pending 7708 * notification this method is a NOP until the notification has been sent. 7709 * 7710 * @hide 7711 */ 7712 public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) { 7713 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 7714 return; 7715 } 7716 if (mSendViewStateChangedAccessibilityEvent == null) { 7717 mSendViewStateChangedAccessibilityEvent = 7718 new SendViewStateChangedAccessibilityEvent(); 7719 } 7720 mSendViewStateChangedAccessibilityEvent.runOrPost(changeType); 7721 } 7722 7723 /** 7724 * Notifies that the accessibility state of this view changed. The change 7725 * is *not* local to this view and does represent structural changes such 7726 * as children and parent. For example, the view size changed. The 7727 * notification is at at most once every 7728 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 7729 * to avoid unnecessary load to the system. Also once a view has a pending 7730 * notification this method is a NOP until the notification has been sent. 7731 * 7732 * @hide 7733 */ 7734 public void notifySubtreeAccessibilityStateChangedIfNeeded() { 7735 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 7736 return; 7737 } 7738 if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) { 7739 mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 7740 if (mParent != null) { 7741 try { 7742 mParent.notifySubtreeAccessibilityStateChanged( 7743 this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE); 7744 } catch (AbstractMethodError e) { 7745 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 7746 " does not fully implement ViewParent", e); 7747 } 7748 } 7749 } 7750 } 7751 7752 /** 7753 * Reset the flag indicating the accessibility state of the subtree rooted 7754 * at this view changed. 7755 */ 7756 void resetSubtreeAccessibilityStateChanged() { 7757 mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 7758 } 7759 7760 /** 7761 * Performs the specified accessibility action on the view. For 7762 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 7763 * <p> 7764 * If an {@link AccessibilityDelegate} has been specified via calling 7765 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 7766 * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)} 7767 * is responsible for handling this call. 7768 * </p> 7769 * 7770 * @param action The action to perform. 7771 * @param arguments Optional action arguments. 7772 * @return Whether the action was performed. 7773 */ 7774 public boolean performAccessibilityAction(int action, Bundle arguments) { 7775 if (mAccessibilityDelegate != null) { 7776 return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments); 7777 } else { 7778 return performAccessibilityActionInternal(action, arguments); 7779 } 7780 } 7781 7782 /** 7783 * @see #performAccessibilityAction(int, Bundle) 7784 * 7785 * Note: Called from the default {@link AccessibilityDelegate}. 7786 */ 7787 boolean performAccessibilityActionInternal(int action, Bundle arguments) { 7788 switch (action) { 7789 case AccessibilityNodeInfo.ACTION_CLICK: { 7790 if (isClickable()) { 7791 performClick(); 7792 return true; 7793 } 7794 } break; 7795 case AccessibilityNodeInfo.ACTION_LONG_CLICK: { 7796 if (isLongClickable()) { 7797 performLongClick(); 7798 return true; 7799 } 7800 } break; 7801 case AccessibilityNodeInfo.ACTION_FOCUS: { 7802 if (!hasFocus()) { 7803 // Get out of touch mode since accessibility 7804 // wants to move focus around. 7805 getViewRootImpl().ensureTouchMode(false); 7806 return requestFocus(); 7807 } 7808 } break; 7809 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 7810 if (hasFocus()) { 7811 clearFocus(); 7812 return !isFocused(); 7813 } 7814 } break; 7815 case AccessibilityNodeInfo.ACTION_SELECT: { 7816 if (!isSelected()) { 7817 setSelected(true); 7818 return isSelected(); 7819 } 7820 } break; 7821 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: { 7822 if (isSelected()) { 7823 setSelected(false); 7824 return !isSelected(); 7825 } 7826 } break; 7827 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 7828 if (!isAccessibilityFocused()) { 7829 return requestAccessibilityFocus(); 7830 } 7831 } break; 7832 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 7833 if (isAccessibilityFocused()) { 7834 clearAccessibilityFocus(); 7835 return true; 7836 } 7837 } break; 7838 case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { 7839 if (arguments != null) { 7840 final int granularity = arguments.getInt( 7841 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 7842 final boolean extendSelection = arguments.getBoolean( 7843 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 7844 return traverseAtGranularity(granularity, true, extendSelection); 7845 } 7846 } break; 7847 case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { 7848 if (arguments != null) { 7849 final int granularity = arguments.getInt( 7850 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 7851 final boolean extendSelection = arguments.getBoolean( 7852 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 7853 return traverseAtGranularity(granularity, false, extendSelection); 7854 } 7855 } break; 7856 case AccessibilityNodeInfo.ACTION_SET_SELECTION: { 7857 CharSequence text = getIterableTextForAccessibility(); 7858 if (text == null) { 7859 return false; 7860 } 7861 final int start = (arguments != null) ? arguments.getInt( 7862 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1; 7863 final int end = (arguments != null) ? arguments.getInt( 7864 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1; 7865 // Only cursor position can be specified (selection length == 0) 7866 if ((getAccessibilitySelectionStart() != start 7867 || getAccessibilitySelectionEnd() != end) 7868 && (start == end)) { 7869 setAccessibilitySelection(start, end); 7870 notifyViewAccessibilityStateChangedIfNeeded( 7871 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7872 return true; 7873 } 7874 } break; 7875 } 7876 return false; 7877 } 7878 7879 private boolean traverseAtGranularity(int granularity, boolean forward, 7880 boolean extendSelection) { 7881 CharSequence text = getIterableTextForAccessibility(); 7882 if (text == null || text.length() == 0) { 7883 return false; 7884 } 7885 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 7886 if (iterator == null) { 7887 return false; 7888 } 7889 int current = getAccessibilitySelectionEnd(); 7890 if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 7891 current = forward ? 0 : text.length(); 7892 } 7893 final int[] range = forward ? iterator.following(current) : iterator.preceding(current); 7894 if (range == null) { 7895 return false; 7896 } 7897 final int segmentStart = range[0]; 7898 final int segmentEnd = range[1]; 7899 int selectionStart; 7900 int selectionEnd; 7901 if (extendSelection && isAccessibilitySelectionExtendable()) { 7902 selectionStart = getAccessibilitySelectionStart(); 7903 if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 7904 selectionStart = forward ? segmentStart : segmentEnd; 7905 } 7906 selectionEnd = forward ? segmentEnd : segmentStart; 7907 } else { 7908 selectionStart = selectionEnd= forward ? segmentEnd : segmentStart; 7909 } 7910 setAccessibilitySelection(selectionStart, selectionEnd); 7911 final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY 7912 : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY; 7913 sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd); 7914 return true; 7915 } 7916 7917 /** 7918 * Gets the text reported for accessibility purposes. 7919 * 7920 * @return The accessibility text. 7921 * 7922 * @hide 7923 */ 7924 public CharSequence getIterableTextForAccessibility() { 7925 return getContentDescription(); 7926 } 7927 7928 /** 7929 * Gets whether accessibility selection can be extended. 7930 * 7931 * @return If selection is extensible. 7932 * 7933 * @hide 7934 */ 7935 public boolean isAccessibilitySelectionExtendable() { 7936 return false; 7937 } 7938 7939 /** 7940 * @hide 7941 */ 7942 public int getAccessibilitySelectionStart() { 7943 return mAccessibilityCursorPosition; 7944 } 7945 7946 /** 7947 * @hide 7948 */ 7949 public int getAccessibilitySelectionEnd() { 7950 return getAccessibilitySelectionStart(); 7951 } 7952 7953 /** 7954 * @hide 7955 */ 7956 public void setAccessibilitySelection(int start, int end) { 7957 if (start == end && end == mAccessibilityCursorPosition) { 7958 return; 7959 } 7960 if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) { 7961 mAccessibilityCursorPosition = start; 7962 } else { 7963 mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 7964 } 7965 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); 7966 } 7967 7968 private void sendViewTextTraversedAtGranularityEvent(int action, int granularity, 7969 int fromIndex, int toIndex) { 7970 if (mParent == null) { 7971 return; 7972 } 7973 AccessibilityEvent event = AccessibilityEvent.obtain( 7974 AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY); 7975 onInitializeAccessibilityEvent(event); 7976 onPopulateAccessibilityEvent(event); 7977 event.setFromIndex(fromIndex); 7978 event.setToIndex(toIndex); 7979 event.setAction(action); 7980 event.setMovementGranularity(granularity); 7981 mParent.requestSendAccessibilityEvent(this, event); 7982 } 7983 7984 /** 7985 * @hide 7986 */ 7987 public TextSegmentIterator getIteratorForGranularity(int granularity) { 7988 switch (granularity) { 7989 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { 7990 CharSequence text = getIterableTextForAccessibility(); 7991 if (text != null && text.length() > 0) { 7992 CharacterTextSegmentIterator iterator = 7993 CharacterTextSegmentIterator.getInstance( 7994 mContext.getResources().getConfiguration().locale); 7995 iterator.initialize(text.toString()); 7996 return iterator; 7997 } 7998 } break; 7999 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: { 8000 CharSequence text = getIterableTextForAccessibility(); 8001 if (text != null && text.length() > 0) { 8002 WordTextSegmentIterator iterator = 8003 WordTextSegmentIterator.getInstance( 8004 mContext.getResources().getConfiguration().locale); 8005 iterator.initialize(text.toString()); 8006 return iterator; 8007 } 8008 } break; 8009 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: { 8010 CharSequence text = getIterableTextForAccessibility(); 8011 if (text != null && text.length() > 0) { 8012 ParagraphTextSegmentIterator iterator = 8013 ParagraphTextSegmentIterator.getInstance(); 8014 iterator.initialize(text.toString()); 8015 return iterator; 8016 } 8017 } break; 8018 } 8019 return null; 8020 } 8021 8022 /** 8023 * @hide 8024 */ 8025 public void dispatchStartTemporaryDetach() { 8026 onStartTemporaryDetach(); 8027 } 8028 8029 /** 8030 * This is called when a container is going to temporarily detach a child, with 8031 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 8032 * It will either be followed by {@link #onFinishTemporaryDetach()} or 8033 * {@link #onDetachedFromWindow()} when the container is done. 8034 */ 8035 public void onStartTemporaryDetach() { 8036 removeUnsetPressCallback(); 8037 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 8038 } 8039 8040 /** 8041 * @hide 8042 */ 8043 public void dispatchFinishTemporaryDetach() { 8044 onFinishTemporaryDetach(); 8045 } 8046 8047 /** 8048 * Called after {@link #onStartTemporaryDetach} when the container is done 8049 * changing the view. 8050 */ 8051 public void onFinishTemporaryDetach() { 8052 } 8053 8054 /** 8055 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 8056 * for this view's window. Returns null if the view is not currently attached 8057 * to the window. Normally you will not need to use this directly, but 8058 * just use the standard high-level event callbacks like 8059 * {@link #onKeyDown(int, KeyEvent)}. 8060 */ 8061 public KeyEvent.DispatcherState getKeyDispatcherState() { 8062 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 8063 } 8064 8065 /** 8066 * Dispatch a key event before it is processed by any input method 8067 * associated with the view hierarchy. This can be used to intercept 8068 * key events in special situations before the IME consumes them; a 8069 * typical example would be handling the BACK key to update the application's 8070 * UI instead of allowing the IME to see it and close itself. 8071 * 8072 * @param event The key event to be dispatched. 8073 * @return True if the event was handled, false otherwise. 8074 */ 8075 public boolean dispatchKeyEventPreIme(KeyEvent event) { 8076 return onKeyPreIme(event.getKeyCode(), event); 8077 } 8078 8079 /** 8080 * Dispatch a key event to the next view on the focus path. This path runs 8081 * from the top of the view tree down to the currently focused view. If this 8082 * view has focus, it will dispatch to itself. Otherwise it will dispatch 8083 * the next node down the focus path. This method also fires any key 8084 * listeners. 8085 * 8086 * @param event The key event to be dispatched. 8087 * @return True if the event was handled, false otherwise. 8088 */ 8089 public boolean dispatchKeyEvent(KeyEvent event) { 8090 if (mInputEventConsistencyVerifier != null) { 8091 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 8092 } 8093 8094 // Give any attached key listener a first crack at the event. 8095 //noinspection SimplifiableIfStatement 8096 ListenerInfo li = mListenerInfo; 8097 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 8098 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 8099 return true; 8100 } 8101 8102 if (event.dispatch(this, mAttachInfo != null 8103 ? mAttachInfo.mKeyDispatchState : null, this)) { 8104 return true; 8105 } 8106 8107 if (mInputEventConsistencyVerifier != null) { 8108 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8109 } 8110 return false; 8111 } 8112 8113 /** 8114 * Dispatches a key shortcut event. 8115 * 8116 * @param event The key event to be dispatched. 8117 * @return True if the event was handled by the view, false otherwise. 8118 */ 8119 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 8120 return onKeyShortcut(event.getKeyCode(), event); 8121 } 8122 8123 /** 8124 * Pass the touch screen motion event down to the target view, or this 8125 * view if it is the target. 8126 * 8127 * @param event The motion event to be dispatched. 8128 * @return True if the event was handled by the view, false otherwise. 8129 */ 8130 public boolean dispatchTouchEvent(MotionEvent event) { 8131 boolean result = false; 8132 8133 if (mInputEventConsistencyVerifier != null) { 8134 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 8135 } 8136 8137 final int actionMasked = event.getActionMasked(); 8138 if (actionMasked == MotionEvent.ACTION_DOWN) { 8139 // Defensive cleanup for new gesture 8140 stopNestedScroll(); 8141 } 8142 8143 if (onFilterTouchEventForSecurity(event)) { 8144 //noinspection SimplifiableIfStatement 8145 ListenerInfo li = mListenerInfo; 8146 if (li != null && li.mOnTouchListener != null 8147 && (mViewFlags & ENABLED_MASK) == ENABLED 8148 && li.mOnTouchListener.onTouch(this, event)) { 8149 result = true; 8150 } 8151 8152 if (!result && onTouchEvent(event)) { 8153 result = true; 8154 } 8155 } 8156 8157 if (!result && mInputEventConsistencyVerifier != null) { 8158 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8159 } 8160 8161 // Clean up after nested scrolls if this is the end of a gesture; 8162 // also cancel it if we tried an ACTION_DOWN but we didn't want the rest 8163 // of the gesture. 8164 if (actionMasked == MotionEvent.ACTION_UP || 8165 actionMasked == MotionEvent.ACTION_CANCEL || 8166 (actionMasked == MotionEvent.ACTION_DOWN && !result)) { 8167 stopNestedScroll(); 8168 } 8169 8170 return result; 8171 } 8172 8173 /** 8174 * Filter the touch event to apply security policies. 8175 * 8176 * @param event The motion event to be filtered. 8177 * @return True if the event should be dispatched, false if the event should be dropped. 8178 * 8179 * @see #getFilterTouchesWhenObscured 8180 */ 8181 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 8182 //noinspection RedundantIfStatement 8183 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 8184 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 8185 // Window is obscured, drop this touch. 8186 return false; 8187 } 8188 return true; 8189 } 8190 8191 /** 8192 * Pass a trackball motion event down to the focused view. 8193 * 8194 * @param event The motion event to be dispatched. 8195 * @return True if the event was handled by the view, false otherwise. 8196 */ 8197 public boolean dispatchTrackballEvent(MotionEvent event) { 8198 if (mInputEventConsistencyVerifier != null) { 8199 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 8200 } 8201 8202 return onTrackballEvent(event); 8203 } 8204 8205 /** 8206 * Dispatch a generic motion event. 8207 * <p> 8208 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 8209 * are delivered to the view under the pointer. All other generic motion events are 8210 * delivered to the focused view. Hover events are handled specially and are delivered 8211 * to {@link #onHoverEvent(MotionEvent)}. 8212 * </p> 8213 * 8214 * @param event The motion event to be dispatched. 8215 * @return True if the event was handled by the view, false otherwise. 8216 */ 8217 public boolean dispatchGenericMotionEvent(MotionEvent event) { 8218 if (mInputEventConsistencyVerifier != null) { 8219 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 8220 } 8221 8222 final int source = event.getSource(); 8223 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 8224 final int action = event.getAction(); 8225 if (action == MotionEvent.ACTION_HOVER_ENTER 8226 || action == MotionEvent.ACTION_HOVER_MOVE 8227 || action == MotionEvent.ACTION_HOVER_EXIT) { 8228 if (dispatchHoverEvent(event)) { 8229 return true; 8230 } 8231 } else if (dispatchGenericPointerEvent(event)) { 8232 return true; 8233 } 8234 } else if (dispatchGenericFocusedEvent(event)) { 8235 return true; 8236 } 8237 8238 if (dispatchGenericMotionEventInternal(event)) { 8239 return true; 8240 } 8241 8242 if (mInputEventConsistencyVerifier != null) { 8243 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8244 } 8245 return false; 8246 } 8247 8248 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 8249 //noinspection SimplifiableIfStatement 8250 ListenerInfo li = mListenerInfo; 8251 if (li != null && li.mOnGenericMotionListener != null 8252 && (mViewFlags & ENABLED_MASK) == ENABLED 8253 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 8254 return true; 8255 } 8256 8257 if (onGenericMotionEvent(event)) { 8258 return true; 8259 } 8260 8261 if (mInputEventConsistencyVerifier != null) { 8262 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8263 } 8264 return false; 8265 } 8266 8267 /** 8268 * Dispatch a hover event. 8269 * <p> 8270 * Do not call this method directly. 8271 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8272 * </p> 8273 * 8274 * @param event The motion event to be dispatched. 8275 * @return True if the event was handled by the view, false otherwise. 8276 */ 8277 protected boolean dispatchHoverEvent(MotionEvent event) { 8278 ListenerInfo li = mListenerInfo; 8279 //noinspection SimplifiableIfStatement 8280 if (li != null && li.mOnHoverListener != null 8281 && (mViewFlags & ENABLED_MASK) == ENABLED 8282 && li.mOnHoverListener.onHover(this, event)) { 8283 return true; 8284 } 8285 8286 return onHoverEvent(event); 8287 } 8288 8289 /** 8290 * Returns true if the view has a child to which it has recently sent 8291 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 8292 * it does not have a hovered child, then it must be the innermost hovered view. 8293 * @hide 8294 */ 8295 protected boolean hasHoveredChild() { 8296 return false; 8297 } 8298 8299 /** 8300 * Dispatch a generic motion event to the view under the first pointer. 8301 * <p> 8302 * Do not call this method directly. 8303 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8304 * </p> 8305 * 8306 * @param event The motion event to be dispatched. 8307 * @return True if the event was handled by the view, false otherwise. 8308 */ 8309 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 8310 return false; 8311 } 8312 8313 /** 8314 * Dispatch a generic motion event to the currently focused view. 8315 * <p> 8316 * Do not call this method directly. 8317 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8318 * </p> 8319 * 8320 * @param event The motion event to be dispatched. 8321 * @return True if the event was handled by the view, false otherwise. 8322 */ 8323 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 8324 return false; 8325 } 8326 8327 /** 8328 * Dispatch a pointer event. 8329 * <p> 8330 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 8331 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 8332 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 8333 * and should not be expected to handle other pointing device features. 8334 * </p> 8335 * 8336 * @param event The motion event to be dispatched. 8337 * @return True if the event was handled by the view, false otherwise. 8338 * @hide 8339 */ 8340 public final boolean dispatchPointerEvent(MotionEvent event) { 8341 if (event.isTouchEvent()) { 8342 return dispatchTouchEvent(event); 8343 } else { 8344 return dispatchGenericMotionEvent(event); 8345 } 8346 } 8347 8348 /** 8349 * Called when the window containing this view gains or loses window focus. 8350 * ViewGroups should override to route to their children. 8351 * 8352 * @param hasFocus True if the window containing this view now has focus, 8353 * false otherwise. 8354 */ 8355 public void dispatchWindowFocusChanged(boolean hasFocus) { 8356 onWindowFocusChanged(hasFocus); 8357 } 8358 8359 /** 8360 * Called when the window containing this view gains or loses focus. Note 8361 * that this is separate from view focus: to receive key events, both 8362 * your view and its window must have focus. If a window is displayed 8363 * on top of yours that takes input focus, then your own window will lose 8364 * focus but the view focus will remain unchanged. 8365 * 8366 * @param hasWindowFocus True if the window containing this view now has 8367 * focus, false otherwise. 8368 */ 8369 public void onWindowFocusChanged(boolean hasWindowFocus) { 8370 InputMethodManager imm = InputMethodManager.peekInstance(); 8371 if (!hasWindowFocus) { 8372 if (isPressed()) { 8373 setPressed(false); 8374 } 8375 if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 8376 imm.focusOut(this); 8377 } 8378 removeLongPressCallback(); 8379 removeTapCallback(); 8380 onFocusLost(); 8381 } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 8382 imm.focusIn(this); 8383 } 8384 refreshDrawableState(); 8385 } 8386 8387 /** 8388 * Returns true if this view is in a window that currently has window focus. 8389 * Note that this is not the same as the view itself having focus. 8390 * 8391 * @return True if this view is in a window that currently has window focus. 8392 */ 8393 public boolean hasWindowFocus() { 8394 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 8395 } 8396 8397 /** 8398 * Dispatch a view visibility change down the view hierarchy. 8399 * ViewGroups should override to route to their children. 8400 * @param changedView The view whose visibility changed. Could be 'this' or 8401 * an ancestor view. 8402 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 8403 * {@link #INVISIBLE} or {@link #GONE}. 8404 */ 8405 protected void dispatchVisibilityChanged(@NonNull View changedView, 8406 @Visibility int visibility) { 8407 onVisibilityChanged(changedView, visibility); 8408 } 8409 8410 /** 8411 * Called when the visibility of the view or an ancestor of the view is changed. 8412 * @param changedView The view whose visibility changed. Could be 'this' or 8413 * an ancestor view. 8414 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 8415 * {@link #INVISIBLE} or {@link #GONE}. 8416 */ 8417 protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) { 8418 if (visibility == VISIBLE) { 8419 if (mAttachInfo != null) { 8420 initialAwakenScrollBars(); 8421 } else { 8422 mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 8423 } 8424 } 8425 } 8426 8427 /** 8428 * Dispatch a hint about whether this view is displayed. For instance, when 8429 * a View moves out of the screen, it might receives a display hint indicating 8430 * the view is not displayed. Applications should not <em>rely</em> on this hint 8431 * as there is no guarantee that they will receive one. 8432 * 8433 * @param hint A hint about whether or not this view is displayed: 8434 * {@link #VISIBLE} or {@link #INVISIBLE}. 8435 */ 8436 public void dispatchDisplayHint(@Visibility int hint) { 8437 onDisplayHint(hint); 8438 } 8439 8440 /** 8441 * Gives this view a hint about whether is displayed or not. For instance, when 8442 * a View moves out of the screen, it might receives a display hint indicating 8443 * the view is not displayed. Applications should not <em>rely</em> on this hint 8444 * as there is no guarantee that they will receive one. 8445 * 8446 * @param hint A hint about whether or not this view is displayed: 8447 * {@link #VISIBLE} or {@link #INVISIBLE}. 8448 */ 8449 protected void onDisplayHint(@Visibility int hint) { 8450 } 8451 8452 /** 8453 * Dispatch a window visibility change down the view hierarchy. 8454 * ViewGroups should override to route to their children. 8455 * 8456 * @param visibility The new visibility of the window. 8457 * 8458 * @see #onWindowVisibilityChanged(int) 8459 */ 8460 public void dispatchWindowVisibilityChanged(@Visibility int visibility) { 8461 onWindowVisibilityChanged(visibility); 8462 } 8463 8464 /** 8465 * Called when the window containing has change its visibility 8466 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 8467 * that this tells you whether or not your window is being made visible 8468 * to the window manager; this does <em>not</em> tell you whether or not 8469 * your window is obscured by other windows on the screen, even if it 8470 * is itself visible. 8471 * 8472 * @param visibility The new visibility of the window. 8473 */ 8474 protected void onWindowVisibilityChanged(@Visibility int visibility) { 8475 if (visibility == VISIBLE) { 8476 initialAwakenScrollBars(); 8477 } 8478 } 8479 8480 /** 8481 * Returns the current visibility of the window this view is attached to 8482 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 8483 * 8484 * @return Returns the current visibility of the view's window. 8485 */ 8486 @Visibility 8487 public int getWindowVisibility() { 8488 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 8489 } 8490 8491 /** 8492 * Retrieve the overall visible display size in which the window this view is 8493 * attached to has been positioned in. This takes into account screen 8494 * decorations above the window, for both cases where the window itself 8495 * is being position inside of them or the window is being placed under 8496 * then and covered insets are used for the window to position its content 8497 * inside. In effect, this tells you the available area where content can 8498 * be placed and remain visible to users. 8499 * 8500 * <p>This function requires an IPC back to the window manager to retrieve 8501 * the requested information, so should not be used in performance critical 8502 * code like drawing. 8503 * 8504 * @param outRect Filled in with the visible display frame. If the view 8505 * is not attached to a window, this is simply the raw display size. 8506 */ 8507 public void getWindowVisibleDisplayFrame(Rect outRect) { 8508 if (mAttachInfo != null) { 8509 try { 8510 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 8511 } catch (RemoteException e) { 8512 return; 8513 } 8514 // XXX This is really broken, and probably all needs to be done 8515 // in the window manager, and we need to know more about whether 8516 // we want the area behind or in front of the IME. 8517 final Rect insets = mAttachInfo.mVisibleInsets; 8518 outRect.left += insets.left; 8519 outRect.top += insets.top; 8520 outRect.right -= insets.right; 8521 outRect.bottom -= insets.bottom; 8522 return; 8523 } 8524 // The view is not attached to a display so we don't have a context. 8525 // Make a best guess about the display size. 8526 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 8527 d.getRectSize(outRect); 8528 } 8529 8530 /** 8531 * Dispatch a notification about a resource configuration change down 8532 * the view hierarchy. 8533 * ViewGroups should override to route to their children. 8534 * 8535 * @param newConfig The new resource configuration. 8536 * 8537 * @see #onConfigurationChanged(android.content.res.Configuration) 8538 */ 8539 public void dispatchConfigurationChanged(Configuration newConfig) { 8540 onConfigurationChanged(newConfig); 8541 } 8542 8543 /** 8544 * Called when the current configuration of the resources being used 8545 * by the application have changed. You can use this to decide when 8546 * to reload resources that can changed based on orientation and other 8547 * configuration characterstics. You only need to use this if you are 8548 * not relying on the normal {@link android.app.Activity} mechanism of 8549 * recreating the activity instance upon a configuration change. 8550 * 8551 * @param newConfig The new resource configuration. 8552 */ 8553 protected void onConfigurationChanged(Configuration newConfig) { 8554 } 8555 8556 /** 8557 * Private function to aggregate all per-view attributes in to the view 8558 * root. 8559 */ 8560 void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) { 8561 performCollectViewAttributes(attachInfo, visibility); 8562 } 8563 8564 void performCollectViewAttributes(AttachInfo attachInfo, int visibility) { 8565 if ((visibility & VISIBILITY_MASK) == VISIBLE) { 8566 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 8567 attachInfo.mKeepScreenOn = true; 8568 } 8569 attachInfo.mSystemUiVisibility |= mSystemUiVisibility; 8570 ListenerInfo li = mListenerInfo; 8571 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 8572 attachInfo.mHasSystemUiListeners = true; 8573 } 8574 } 8575 } 8576 8577 void needGlobalAttributesUpdate(boolean force) { 8578 final AttachInfo ai = mAttachInfo; 8579 if (ai != null && !ai.mRecomputeGlobalAttributes) { 8580 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 8581 || ai.mHasSystemUiListeners) { 8582 ai.mRecomputeGlobalAttributes = true; 8583 } 8584 } 8585 } 8586 8587 /** 8588 * Returns whether the device is currently in touch mode. Touch mode is entered 8589 * once the user begins interacting with the device by touch, and affects various 8590 * things like whether focus is always visible to the user. 8591 * 8592 * @return Whether the device is in touch mode. 8593 */ 8594 @ViewDebug.ExportedProperty 8595 public boolean isInTouchMode() { 8596 if (mAttachInfo != null) { 8597 return mAttachInfo.mInTouchMode; 8598 } else { 8599 return ViewRootImpl.isInTouchMode(); 8600 } 8601 } 8602 8603 /** 8604 * Returns the context the view is running in, through which it can 8605 * access the current theme, resources, etc. 8606 * 8607 * @return The view's Context. 8608 */ 8609 @ViewDebug.CapturedViewProperty 8610 public final Context getContext() { 8611 return mContext; 8612 } 8613 8614 /** 8615 * Handle a key event before it is processed by any input method 8616 * associated with the view hierarchy. This can be used to intercept 8617 * key events in special situations before the IME consumes them; a 8618 * typical example would be handling the BACK key to update the application's 8619 * UI instead of allowing the IME to see it and close itself. 8620 * 8621 * @param keyCode The value in event.getKeyCode(). 8622 * @param event Description of the key event. 8623 * @return If you handled the event, return true. If you want to allow the 8624 * event to be handled by the next receiver, return false. 8625 */ 8626 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 8627 return false; 8628 } 8629 8630 /** 8631 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 8632 * KeyEvent.Callback.onKeyDown()}: perform press of the view 8633 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 8634 * is released, if the view is enabled and clickable. 8635 * 8636 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8637 * although some may elect to do so in some situations. Do not rely on this to 8638 * catch software key presses. 8639 * 8640 * @param keyCode A key code that represents the button pressed, from 8641 * {@link android.view.KeyEvent}. 8642 * @param event The KeyEvent object that defines the button action. 8643 */ 8644 public boolean onKeyDown(int keyCode, KeyEvent event) { 8645 boolean result = false; 8646 8647 if (KeyEvent.isConfirmKey(keyCode)) { 8648 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 8649 return true; 8650 } 8651 // Long clickable items don't necessarily have to be clickable 8652 if (((mViewFlags & CLICKABLE) == CLICKABLE || 8653 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 8654 (event.getRepeatCount() == 0)) { 8655 setPressed(true); 8656 checkForLongClick(0); 8657 return true; 8658 } 8659 } 8660 return result; 8661 } 8662 8663 /** 8664 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 8665 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 8666 * the event). 8667 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8668 * although some may elect to do so in some situations. Do not rely on this to 8669 * catch software key presses. 8670 */ 8671 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 8672 return false; 8673 } 8674 8675 /** 8676 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 8677 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 8678 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 8679 * {@link KeyEvent#KEYCODE_ENTER} is released. 8680 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8681 * although some may elect to do so in some situations. Do not rely on this to 8682 * catch software key presses. 8683 * 8684 * @param keyCode A key code that represents the button pressed, from 8685 * {@link android.view.KeyEvent}. 8686 * @param event The KeyEvent object that defines the button action. 8687 */ 8688 public boolean onKeyUp(int keyCode, KeyEvent event) { 8689 if (KeyEvent.isConfirmKey(keyCode)) { 8690 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 8691 return true; 8692 } 8693 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 8694 setPressed(false); 8695 8696 if (!mHasPerformedLongPress) { 8697 // This is a tap, so remove the longpress check 8698 removeLongPressCallback(); 8699 return performClick(); 8700 } 8701 } 8702 } 8703 return false; 8704 } 8705 8706 /** 8707 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 8708 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 8709 * the event). 8710 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8711 * although some may elect to do so in some situations. Do not rely on this to 8712 * catch software key presses. 8713 * 8714 * @param keyCode A key code that represents the button pressed, from 8715 * {@link android.view.KeyEvent}. 8716 * @param repeatCount The number of times the action was made. 8717 * @param event The KeyEvent object that defines the button action. 8718 */ 8719 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 8720 return false; 8721 } 8722 8723 /** 8724 * Called on the focused view when a key shortcut event is not handled. 8725 * Override this method to implement local key shortcuts for the View. 8726 * Key shortcuts can also be implemented by setting the 8727 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 8728 * 8729 * @param keyCode The value in event.getKeyCode(). 8730 * @param event Description of the key event. 8731 * @return If you handled the event, return true. If you want to allow the 8732 * event to be handled by the next receiver, return false. 8733 */ 8734 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 8735 return false; 8736 } 8737 8738 /** 8739 * Check whether the called view is a text editor, in which case it 8740 * would make sense to automatically display a soft input window for 8741 * it. Subclasses should override this if they implement 8742 * {@link #onCreateInputConnection(EditorInfo)} to return true if 8743 * a call on that method would return a non-null InputConnection, and 8744 * they are really a first-class editor that the user would normally 8745 * start typing on when the go into a window containing your view. 8746 * 8747 * <p>The default implementation always returns false. This does 8748 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 8749 * will not be called or the user can not otherwise perform edits on your 8750 * view; it is just a hint to the system that this is not the primary 8751 * purpose of this view. 8752 * 8753 * @return Returns true if this view is a text editor, else false. 8754 */ 8755 public boolean onCheckIsTextEditor() { 8756 return false; 8757 } 8758 8759 /** 8760 * Create a new InputConnection for an InputMethod to interact 8761 * with the view. The default implementation returns null, since it doesn't 8762 * support input methods. You can override this to implement such support. 8763 * This is only needed for views that take focus and text input. 8764 * 8765 * <p>When implementing this, you probably also want to implement 8766 * {@link #onCheckIsTextEditor()} to indicate you will return a 8767 * non-null InputConnection.</p> 8768 * 8769 * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo} 8770 * object correctly and in its entirety, so that the connected IME can rely 8771 * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart} 8772 * and {@link android.view.inputmethod.EditorInfo#initialSelEnd} members 8773 * must be filled in with the correct cursor position for IMEs to work correctly 8774 * with your application.</p> 8775 * 8776 * @param outAttrs Fill in with attribute information about the connection. 8777 */ 8778 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 8779 return null; 8780 } 8781 8782 /** 8783 * Called by the {@link android.view.inputmethod.InputMethodManager} 8784 * when a view who is not the current 8785 * input connection target is trying to make a call on the manager. The 8786 * default implementation returns false; you can override this to return 8787 * true for certain views if you are performing InputConnection proxying 8788 * to them. 8789 * @param view The View that is making the InputMethodManager call. 8790 * @return Return true to allow the call, false to reject. 8791 */ 8792 public boolean checkInputConnectionProxy(View view) { 8793 return false; 8794 } 8795 8796 /** 8797 * Show the context menu for this view. It is not safe to hold on to the 8798 * menu after returning from this method. 8799 * 8800 * You should normally not overload this method. Overload 8801 * {@link #onCreateContextMenu(ContextMenu)} or define an 8802 * {@link OnCreateContextMenuListener} to add items to the context menu. 8803 * 8804 * @param menu The context menu to populate 8805 */ 8806 public void createContextMenu(ContextMenu menu) { 8807 ContextMenuInfo menuInfo = getContextMenuInfo(); 8808 8809 // Sets the current menu info so all items added to menu will have 8810 // my extra info set. 8811 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 8812 8813 onCreateContextMenu(menu); 8814 ListenerInfo li = mListenerInfo; 8815 if (li != null && li.mOnCreateContextMenuListener != null) { 8816 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 8817 } 8818 8819 // Clear the extra information so subsequent items that aren't mine don't 8820 // have my extra info. 8821 ((MenuBuilder)menu).setCurrentMenuInfo(null); 8822 8823 if (mParent != null) { 8824 mParent.createContextMenu(menu); 8825 } 8826 } 8827 8828 /** 8829 * Views should implement this if they have extra information to associate 8830 * with the context menu. The return result is supplied as a parameter to 8831 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 8832 * callback. 8833 * 8834 * @return Extra information about the item for which the context menu 8835 * should be shown. This information will vary across different 8836 * subclasses of View. 8837 */ 8838 protected ContextMenuInfo getContextMenuInfo() { 8839 return null; 8840 } 8841 8842 /** 8843 * Views should implement this if the view itself is going to add items to 8844 * the context menu. 8845 * 8846 * @param menu the context menu to populate 8847 */ 8848 protected void onCreateContextMenu(ContextMenu menu) { 8849 } 8850 8851 /** 8852 * Implement this method to handle trackball motion events. The 8853 * <em>relative</em> movement of the trackball since the last event 8854 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 8855 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 8856 * that a movement of 1 corresponds to the user pressing one DPAD key (so 8857 * they will often be fractional values, representing the more fine-grained 8858 * movement information available from a trackball). 8859 * 8860 * @param event The motion event. 8861 * @return True if the event was handled, false otherwise. 8862 */ 8863 public boolean onTrackballEvent(MotionEvent event) { 8864 return false; 8865 } 8866 8867 /** 8868 * Implement this method to handle generic motion events. 8869 * <p> 8870 * Generic motion events describe joystick movements, mouse hovers, track pad 8871 * touches, scroll wheel movements and other input events. The 8872 * {@link MotionEvent#getSource() source} of the motion event specifies 8873 * the class of input that was received. Implementations of this method 8874 * must examine the bits in the source before processing the event. 8875 * The following code example shows how this is done. 8876 * </p><p> 8877 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 8878 * are delivered to the view under the pointer. All other generic motion events are 8879 * delivered to the focused view. 8880 * </p> 8881 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 8882 * if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) { 8883 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 8884 * // process the joystick movement... 8885 * return true; 8886 * } 8887 * } 8888 * if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) { 8889 * switch (event.getAction()) { 8890 * case MotionEvent.ACTION_HOVER_MOVE: 8891 * // process the mouse hover movement... 8892 * return true; 8893 * case MotionEvent.ACTION_SCROLL: 8894 * // process the scroll wheel movement... 8895 * return true; 8896 * } 8897 * } 8898 * return super.onGenericMotionEvent(event); 8899 * }</pre> 8900 * 8901 * @param event The generic motion event being processed. 8902 * @return True if the event was handled, false otherwise. 8903 */ 8904 public boolean onGenericMotionEvent(MotionEvent event) { 8905 return false; 8906 } 8907 8908 /** 8909 * Implement this method to handle hover events. 8910 * <p> 8911 * This method is called whenever a pointer is hovering into, over, or out of the 8912 * bounds of a view and the view is not currently being touched. 8913 * Hover events are represented as pointer events with action 8914 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 8915 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 8916 * </p> 8917 * <ul> 8918 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 8919 * when the pointer enters the bounds of the view.</li> 8920 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 8921 * when the pointer has already entered the bounds of the view and has moved.</li> 8922 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 8923 * when the pointer has exited the bounds of the view or when the pointer is 8924 * about to go down due to a button click, tap, or similar user action that 8925 * causes the view to be touched.</li> 8926 * </ul> 8927 * <p> 8928 * The view should implement this method to return true to indicate that it is 8929 * handling the hover event, such as by changing its drawable state. 8930 * </p><p> 8931 * The default implementation calls {@link #setHovered} to update the hovered state 8932 * of the view when a hover enter or hover exit event is received, if the view 8933 * is enabled and is clickable. The default implementation also sends hover 8934 * accessibility events. 8935 * </p> 8936 * 8937 * @param event The motion event that describes the hover. 8938 * @return True if the view handled the hover event. 8939 * 8940 * @see #isHovered 8941 * @see #setHovered 8942 * @see #onHoverChanged 8943 */ 8944 public boolean onHoverEvent(MotionEvent event) { 8945 // The root view may receive hover (or touch) events that are outside the bounds of 8946 // the window. This code ensures that we only send accessibility events for 8947 // hovers that are actually within the bounds of the root view. 8948 final int action = event.getActionMasked(); 8949 if (!mSendingHoverAccessibilityEvents) { 8950 if ((action == MotionEvent.ACTION_HOVER_ENTER 8951 || action == MotionEvent.ACTION_HOVER_MOVE) 8952 && !hasHoveredChild() 8953 && pointInView(event.getX(), event.getY())) { 8954 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 8955 mSendingHoverAccessibilityEvents = true; 8956 } 8957 } else { 8958 if (action == MotionEvent.ACTION_HOVER_EXIT 8959 || (action == MotionEvent.ACTION_MOVE 8960 && !pointInView(event.getX(), event.getY()))) { 8961 mSendingHoverAccessibilityEvents = false; 8962 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 8963 } 8964 } 8965 8966 if (isHoverable()) { 8967 switch (action) { 8968 case MotionEvent.ACTION_HOVER_ENTER: 8969 setHovered(true); 8970 break; 8971 case MotionEvent.ACTION_HOVER_EXIT: 8972 setHovered(false); 8973 break; 8974 } 8975 8976 // Dispatch the event to onGenericMotionEvent before returning true. 8977 // This is to provide compatibility with existing applications that 8978 // handled HOVER_MOVE events in onGenericMotionEvent and that would 8979 // break because of the new default handling for hoverable views 8980 // in onHoverEvent. 8981 // Note that onGenericMotionEvent will be called by default when 8982 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 8983 dispatchGenericMotionEventInternal(event); 8984 // The event was already handled by calling setHovered(), so always 8985 // return true. 8986 return true; 8987 } 8988 8989 return false; 8990 } 8991 8992 /** 8993 * Returns true if the view should handle {@link #onHoverEvent} 8994 * by calling {@link #setHovered} to change its hovered state. 8995 * 8996 * @return True if the view is hoverable. 8997 */ 8998 private boolean isHoverable() { 8999 final int viewFlags = mViewFlags; 9000 if ((viewFlags & ENABLED_MASK) == DISABLED) { 9001 return false; 9002 } 9003 9004 return (viewFlags & CLICKABLE) == CLICKABLE 9005 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 9006 } 9007 9008 /** 9009 * Returns true if the view is currently hovered. 9010 * 9011 * @return True if the view is currently hovered. 9012 * 9013 * @see #setHovered 9014 * @see #onHoverChanged 9015 */ 9016 @ViewDebug.ExportedProperty 9017 public boolean isHovered() { 9018 return (mPrivateFlags & PFLAG_HOVERED) != 0; 9019 } 9020 9021 /** 9022 * Sets whether the view is currently hovered. 9023 * <p> 9024 * Calling this method also changes the drawable state of the view. This 9025 * enables the view to react to hover by using different drawable resources 9026 * to change its appearance. 9027 * </p><p> 9028 * The {@link #onHoverChanged} method is called when the hovered state changes. 9029 * </p> 9030 * 9031 * @param hovered True if the view is hovered. 9032 * 9033 * @see #isHovered 9034 * @see #onHoverChanged 9035 */ 9036 public void setHovered(boolean hovered) { 9037 if (hovered) { 9038 if ((mPrivateFlags & PFLAG_HOVERED) == 0) { 9039 mPrivateFlags |= PFLAG_HOVERED; 9040 refreshDrawableState(); 9041 onHoverChanged(true); 9042 } 9043 } else { 9044 if ((mPrivateFlags & PFLAG_HOVERED) != 0) { 9045 mPrivateFlags &= ~PFLAG_HOVERED; 9046 refreshDrawableState(); 9047 onHoverChanged(false); 9048 } 9049 } 9050 } 9051 9052 /** 9053 * Implement this method to handle hover state changes. 9054 * <p> 9055 * This method is called whenever the hover state changes as a result of a 9056 * call to {@link #setHovered}. 9057 * </p> 9058 * 9059 * @param hovered The current hover state, as returned by {@link #isHovered}. 9060 * 9061 * @see #isHovered 9062 * @see #setHovered 9063 */ 9064 public void onHoverChanged(boolean hovered) { 9065 } 9066 9067 /** 9068 * Implement this method to handle touch screen motion events. 9069 * <p> 9070 * If this method is used to detect click actions, it is recommended that 9071 * the actions be performed by implementing and calling 9072 * {@link #performClick()}. This will ensure consistent system behavior, 9073 * including: 9074 * <ul> 9075 * <li>obeying click sound preferences 9076 * <li>dispatching OnClickListener calls 9077 * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when 9078 * accessibility features are enabled 9079 * </ul> 9080 * 9081 * @param event The motion event. 9082 * @return True if the event was handled, false otherwise. 9083 */ 9084 public boolean onTouchEvent(MotionEvent event) { 9085 final float x = event.getX(); 9086 final float y = event.getY(); 9087 final int viewFlags = mViewFlags; 9088 9089 if ((viewFlags & ENABLED_MASK) == DISABLED) { 9090 if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { 9091 setPressed(false); 9092 } 9093 // A disabled view that is clickable still consumes the touch 9094 // events, it just doesn't respond to them. 9095 return (((viewFlags & CLICKABLE) == CLICKABLE || 9096 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); 9097 } 9098 9099 if (mTouchDelegate != null) { 9100 if (mTouchDelegate.onTouchEvent(event)) { 9101 return true; 9102 } 9103 } 9104 9105 if (((viewFlags & CLICKABLE) == CLICKABLE || 9106 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { 9107 switch (event.getAction()) { 9108 case MotionEvent.ACTION_UP: 9109 boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; 9110 if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { 9111 // take focus if we don't have it already and we should in 9112 // touch mode. 9113 boolean focusTaken = false; 9114 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 9115 focusTaken = requestFocus(); 9116 } 9117 9118 if (prepressed) { 9119 // The button is being released before we actually 9120 // showed it as pressed. Make it show the pressed 9121 // state now (before scheduling the click) to ensure 9122 // the user sees it. 9123 setPressed(true, x, y); 9124 } 9125 9126 if (!mHasPerformedLongPress) { 9127 // This is a tap, so remove the longpress check 9128 removeLongPressCallback(); 9129 9130 // Only perform take click actions if we were in the pressed state 9131 if (!focusTaken) { 9132 // Use a Runnable and post this rather than calling 9133 // performClick directly. This lets other visual state 9134 // of the view update before click actions start. 9135 if (mPerformClick == null) { 9136 mPerformClick = new PerformClick(); 9137 } 9138 if (!post(mPerformClick)) { 9139 performClick(); 9140 } 9141 } 9142 } 9143 9144 if (mUnsetPressedState == null) { 9145 mUnsetPressedState = new UnsetPressedState(); 9146 } 9147 9148 if (prepressed) { 9149 postDelayed(mUnsetPressedState, 9150 ViewConfiguration.getPressedStateDuration()); 9151 } else if (!post(mUnsetPressedState)) { 9152 // If the post failed, unpress right now 9153 mUnsetPressedState.run(); 9154 } 9155 9156 removeTapCallback(); 9157 } 9158 break; 9159 9160 case MotionEvent.ACTION_DOWN: 9161 mHasPerformedLongPress = false; 9162 9163 if (performButtonActionOnTouchDown(event)) { 9164 break; 9165 } 9166 9167 // Walk up the hierarchy to determine if we're inside a scrolling container. 9168 boolean isInScrollingContainer = isInScrollingContainer(); 9169 9170 // For views inside a scrolling container, delay the pressed feedback for 9171 // a short period in case this is a scroll. 9172 if (isInScrollingContainer) { 9173 mPrivateFlags |= PFLAG_PREPRESSED; 9174 if (mPendingCheckForTap == null) { 9175 mPendingCheckForTap = new CheckForTap(); 9176 } 9177 mPendingCheckForTap.x = event.getX(); 9178 mPendingCheckForTap.y = event.getY(); 9179 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 9180 } else { 9181 // Not inside a scrolling container, so show the feedback right away 9182 setPressed(true, x, y); 9183 checkForLongClick(0); 9184 } 9185 break; 9186 9187 case MotionEvent.ACTION_CANCEL: 9188 setPressed(false); 9189 removeTapCallback(); 9190 removeLongPressCallback(); 9191 break; 9192 9193 case MotionEvent.ACTION_MOVE: 9194 drawableHotspotChanged(x, y); 9195 9196 // Be lenient about moving outside of buttons 9197 if (!pointInView(x, y, mTouchSlop)) { 9198 // Outside button 9199 removeTapCallback(); 9200 if ((mPrivateFlags & PFLAG_PRESSED) != 0) { 9201 // Remove any future long press/tap checks 9202 removeLongPressCallback(); 9203 9204 setPressed(false); 9205 } 9206 } 9207 break; 9208 } 9209 9210 return true; 9211 } 9212 9213 return false; 9214 } 9215 9216 /** 9217 * @hide 9218 */ 9219 public boolean isInScrollingContainer() { 9220 ViewParent p = getParent(); 9221 while (p != null && p instanceof ViewGroup) { 9222 if (((ViewGroup) p).shouldDelayChildPressedState()) { 9223 return true; 9224 } 9225 p = p.getParent(); 9226 } 9227 return false; 9228 } 9229 9230 /** 9231 * Remove the longpress detection timer. 9232 */ 9233 private void removeLongPressCallback() { 9234 if (mPendingCheckForLongPress != null) { 9235 removeCallbacks(mPendingCheckForLongPress); 9236 } 9237 } 9238 9239 /** 9240 * Remove the pending click action 9241 */ 9242 private void removePerformClickCallback() { 9243 if (mPerformClick != null) { 9244 removeCallbacks(mPerformClick); 9245 } 9246 } 9247 9248 /** 9249 * Remove the prepress detection timer. 9250 */ 9251 private void removeUnsetPressCallback() { 9252 if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) { 9253 setPressed(false); 9254 removeCallbacks(mUnsetPressedState); 9255 } 9256 } 9257 9258 /** 9259 * Remove the tap detection timer. 9260 */ 9261 private void removeTapCallback() { 9262 if (mPendingCheckForTap != null) { 9263 mPrivateFlags &= ~PFLAG_PREPRESSED; 9264 removeCallbacks(mPendingCheckForTap); 9265 } 9266 } 9267 9268 /** 9269 * Cancels a pending long press. Your subclass can use this if you 9270 * want the context menu to come up if the user presses and holds 9271 * at the same place, but you don't want it to come up if they press 9272 * and then move around enough to cause scrolling. 9273 */ 9274 public void cancelLongPress() { 9275 removeLongPressCallback(); 9276 9277 /* 9278 * The prepressed state handled by the tap callback is a display 9279 * construct, but the tap callback will post a long press callback 9280 * less its own timeout. Remove it here. 9281 */ 9282 removeTapCallback(); 9283 } 9284 9285 /** 9286 * Remove the pending callback for sending a 9287 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 9288 */ 9289 private void removeSendViewScrolledAccessibilityEventCallback() { 9290 if (mSendViewScrolledAccessibilityEvent != null) { 9291 removeCallbacks(mSendViewScrolledAccessibilityEvent); 9292 mSendViewScrolledAccessibilityEvent.mIsPending = false; 9293 } 9294 } 9295 9296 /** 9297 * Sets the TouchDelegate for this View. 9298 */ 9299 public void setTouchDelegate(TouchDelegate delegate) { 9300 mTouchDelegate = delegate; 9301 } 9302 9303 /** 9304 * Gets the TouchDelegate for this View. 9305 */ 9306 public TouchDelegate getTouchDelegate() { 9307 return mTouchDelegate; 9308 } 9309 9310 /** 9311 * Request unbuffered dispatch of the given stream of MotionEvents to this View. 9312 * 9313 * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input 9314 * system not batch {@link MotionEvent}s but instead deliver them as soon as they're 9315 * available. This method should only be called for touch events. 9316 * 9317 * <p class="note">This api is not intended for most applications. Buffered dispatch 9318 * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent 9319 * streams will not improve your input latency. Side effects include: increased latency, 9320 * jittery scrolls and inability to take advantage of system resampling. Talk to your input 9321 * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for 9322 * you.</p> 9323 */ 9324 public final void requestUnbufferedDispatch(MotionEvent event) { 9325 final int action = event.getAction(); 9326 if (mAttachInfo == null 9327 || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE 9328 || !event.isTouchEvent()) { 9329 return; 9330 } 9331 mAttachInfo.mUnbufferedDispatchRequested = true; 9332 } 9333 9334 /** 9335 * Set flags controlling behavior of this view. 9336 * 9337 * @param flags Constant indicating the value which should be set 9338 * @param mask Constant indicating the bit range that should be changed 9339 */ 9340 void setFlags(int flags, int mask) { 9341 final boolean accessibilityEnabled = 9342 AccessibilityManager.getInstance(mContext).isEnabled(); 9343 final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility(); 9344 9345 int old = mViewFlags; 9346 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 9347 9348 int changed = mViewFlags ^ old; 9349 if (changed == 0) { 9350 return; 9351 } 9352 int privateFlags = mPrivateFlags; 9353 9354 /* Check if the FOCUSABLE bit has changed */ 9355 if (((changed & FOCUSABLE_MASK) != 0) && 9356 ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) { 9357 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 9358 && ((privateFlags & PFLAG_FOCUSED) != 0)) { 9359 /* Give up focus if we are no longer focusable */ 9360 clearFocus(); 9361 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 9362 && ((privateFlags & PFLAG_FOCUSED) == 0)) { 9363 /* 9364 * Tell the view system that we are now available to take focus 9365 * if no one else already has it. 9366 */ 9367 if (mParent != null) mParent.focusableViewAvailable(this); 9368 } 9369 } 9370 9371 final int newVisibility = flags & VISIBILITY_MASK; 9372 if (newVisibility == VISIBLE) { 9373 if ((changed & VISIBILITY_MASK) != 0) { 9374 /* 9375 * If this view is becoming visible, invalidate it in case it changed while 9376 * it was not visible. Marking it drawn ensures that the invalidation will 9377 * go through. 9378 */ 9379 mPrivateFlags |= PFLAG_DRAWN; 9380 invalidate(true); 9381 9382 needGlobalAttributesUpdate(true); 9383 9384 // a view becoming visible is worth notifying the parent 9385 // about in case nothing has focus. even if this specific view 9386 // isn't focusable, it may contain something that is, so let 9387 // the root view try to give this focus if nothing else does. 9388 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 9389 mParent.focusableViewAvailable(this); 9390 } 9391 } 9392 } 9393 9394 /* Check if the GONE bit has changed */ 9395 if ((changed & GONE) != 0) { 9396 needGlobalAttributesUpdate(false); 9397 requestLayout(); 9398 9399 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 9400 if (hasFocus()) clearFocus(); 9401 clearAccessibilityFocus(); 9402 destroyDrawingCache(); 9403 if (mParent instanceof View) { 9404 // GONE views noop invalidation, so invalidate the parent 9405 ((View) mParent).invalidate(true); 9406 } 9407 // Mark the view drawn to ensure that it gets invalidated properly the next 9408 // time it is visible and gets invalidated 9409 mPrivateFlags |= PFLAG_DRAWN; 9410 } 9411 if (mAttachInfo != null) { 9412 mAttachInfo.mViewVisibilityChanged = true; 9413 } 9414 } 9415 9416 /* Check if the VISIBLE bit has changed */ 9417 if ((changed & INVISIBLE) != 0) { 9418 needGlobalAttributesUpdate(false); 9419 /* 9420 * If this view is becoming invisible, set the DRAWN flag so that 9421 * the next invalidate() will not be skipped. 9422 */ 9423 mPrivateFlags |= PFLAG_DRAWN; 9424 9425 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) { 9426 // root view becoming invisible shouldn't clear focus and accessibility focus 9427 if (getRootView() != this) { 9428 if (hasFocus()) clearFocus(); 9429 clearAccessibilityFocus(); 9430 } 9431 } 9432 if (mAttachInfo != null) { 9433 mAttachInfo.mViewVisibilityChanged = true; 9434 } 9435 } 9436 9437 if ((changed & VISIBILITY_MASK) != 0) { 9438 // If the view is invisible, cleanup its display list to free up resources 9439 if (newVisibility != VISIBLE && mAttachInfo != null) { 9440 cleanupDraw(); 9441 } 9442 9443 if (mParent instanceof ViewGroup) { 9444 ((ViewGroup) mParent).onChildVisibilityChanged(this, 9445 (changed & VISIBILITY_MASK), newVisibility); 9446 ((View) mParent).invalidate(true); 9447 } else if (mParent != null) { 9448 mParent.invalidateChild(this, null); 9449 } 9450 dispatchVisibilityChanged(this, newVisibility); 9451 9452 notifySubtreeAccessibilityStateChangedIfNeeded(); 9453 } 9454 9455 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 9456 destroyDrawingCache(); 9457 } 9458 9459 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 9460 destroyDrawingCache(); 9461 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 9462 invalidateParentCaches(); 9463 } 9464 9465 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 9466 destroyDrawingCache(); 9467 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 9468 } 9469 9470 if ((changed & DRAW_MASK) != 0) { 9471 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 9472 if (mBackground != null) { 9473 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 9474 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 9475 } else { 9476 mPrivateFlags |= PFLAG_SKIP_DRAW; 9477 } 9478 } else { 9479 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 9480 } 9481 requestLayout(); 9482 invalidate(true); 9483 } 9484 9485 if ((changed & KEEP_SCREEN_ON) != 0) { 9486 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 9487 mParent.recomputeViewAttributes(this); 9488 } 9489 } 9490 9491 if (accessibilityEnabled) { 9492 if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0 9493 || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) { 9494 if (oldIncludeForAccessibility != includeForAccessibility()) { 9495 notifySubtreeAccessibilityStateChangedIfNeeded(); 9496 } else { 9497 notifyViewAccessibilityStateChangedIfNeeded( 9498 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9499 } 9500 } else if ((changed & ENABLED_MASK) != 0) { 9501 notifyViewAccessibilityStateChangedIfNeeded( 9502 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9503 } 9504 } 9505 } 9506 9507 /** 9508 * Change the view's z order in the tree, so it's on top of other sibling 9509 * views. This ordering change may affect layout, if the parent container 9510 * uses an order-dependent layout scheme (e.g., LinearLayout). Prior 9511 * to {@link android.os.Build.VERSION_CODES#KITKAT} this 9512 * method should be followed by calls to {@link #requestLayout()} and 9513 * {@link View#invalidate()} on the view's parent to force the parent to redraw 9514 * with the new child ordering. 9515 * 9516 * @see ViewGroup#bringChildToFront(View) 9517 */ 9518 public void bringToFront() { 9519 if (mParent != null) { 9520 mParent.bringChildToFront(this); 9521 } 9522 } 9523 9524 /** 9525 * This is called in response to an internal scroll in this view (i.e., the 9526 * view scrolled its own contents). This is typically as a result of 9527 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 9528 * called. 9529 * 9530 * @param l Current horizontal scroll origin. 9531 * @param t Current vertical scroll origin. 9532 * @param oldl Previous horizontal scroll origin. 9533 * @param oldt Previous vertical scroll origin. 9534 */ 9535 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 9536 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 9537 postSendViewScrolledAccessibilityEventCallback(); 9538 } 9539 9540 mBackgroundSizeChanged = true; 9541 9542 final AttachInfo ai = mAttachInfo; 9543 if (ai != null) { 9544 ai.mViewScrollChanged = true; 9545 } 9546 } 9547 9548 /** 9549 * Interface definition for a callback to be invoked when the layout bounds of a view 9550 * changes due to layout processing. 9551 */ 9552 public interface OnLayoutChangeListener { 9553 /** 9554 * Called when the layout bounds of a view changes due to layout processing. 9555 * 9556 * @param v The view whose bounds have changed. 9557 * @param left The new value of the view's left property. 9558 * @param top The new value of the view's top property. 9559 * @param right The new value of the view's right property. 9560 * @param bottom The new value of the view's bottom property. 9561 * @param oldLeft The previous value of the view's left property. 9562 * @param oldTop The previous value of the view's top property. 9563 * @param oldRight The previous value of the view's right property. 9564 * @param oldBottom The previous value of the view's bottom property. 9565 */ 9566 void onLayoutChange(View v, int left, int top, int right, int bottom, 9567 int oldLeft, int oldTop, int oldRight, int oldBottom); 9568 } 9569 9570 /** 9571 * This is called during layout when the size of this view has changed. If 9572 * you were just added to the view hierarchy, you're called with the old 9573 * values of 0. 9574 * 9575 * @param w Current width of this view. 9576 * @param h Current height of this view. 9577 * @param oldw Old width of this view. 9578 * @param oldh Old height of this view. 9579 */ 9580 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 9581 } 9582 9583 /** 9584 * Called by draw to draw the child views. This may be overridden 9585 * by derived classes to gain control just before its children are drawn 9586 * (but after its own view has been drawn). 9587 * @param canvas the canvas on which to draw the view 9588 */ 9589 protected void dispatchDraw(Canvas canvas) { 9590 9591 } 9592 9593 /** 9594 * Gets the parent of this view. Note that the parent is a 9595 * ViewParent and not necessarily a View. 9596 * 9597 * @return Parent of this view. 9598 */ 9599 public final ViewParent getParent() { 9600 return mParent; 9601 } 9602 9603 /** 9604 * Set the horizontal scrolled position of your view. This will cause a call to 9605 * {@link #onScrollChanged(int, int, int, int)} and the view will be 9606 * invalidated. 9607 * @param value the x position to scroll to 9608 */ 9609 public void setScrollX(int value) { 9610 scrollTo(value, mScrollY); 9611 } 9612 9613 /** 9614 * Set the vertical scrolled position of your view. This will cause a call to 9615 * {@link #onScrollChanged(int, int, int, int)} and the view will be 9616 * invalidated. 9617 * @param value the y position to scroll to 9618 */ 9619 public void setScrollY(int value) { 9620 scrollTo(mScrollX, value); 9621 } 9622 9623 /** 9624 * Return the scrolled left position of this view. This is the left edge of 9625 * the displayed part of your view. You do not need to draw any pixels 9626 * farther left, since those are outside of the frame of your view on 9627 * screen. 9628 * 9629 * @return The left edge of the displayed part of your view, in pixels. 9630 */ 9631 public final int getScrollX() { 9632 return mScrollX; 9633 } 9634 9635 /** 9636 * Return the scrolled top position of this view. This is the top edge of 9637 * the displayed part of your view. You do not need to draw any pixels above 9638 * it, since those are outside of the frame of your view on screen. 9639 * 9640 * @return The top edge of the displayed part of your view, in pixels. 9641 */ 9642 public final int getScrollY() { 9643 return mScrollY; 9644 } 9645 9646 /** 9647 * Return the width of the your view. 9648 * 9649 * @return The width of your view, in pixels. 9650 */ 9651 @ViewDebug.ExportedProperty(category = "layout") 9652 public final int getWidth() { 9653 return mRight - mLeft; 9654 } 9655 9656 /** 9657 * Return the height of your view. 9658 * 9659 * @return The height of your view, in pixels. 9660 */ 9661 @ViewDebug.ExportedProperty(category = "layout") 9662 public final int getHeight() { 9663 return mBottom - mTop; 9664 } 9665 9666 /** 9667 * Return the visible drawing bounds of your view. Fills in the output 9668 * rectangle with the values from getScrollX(), getScrollY(), 9669 * getWidth(), and getHeight(). These bounds do not account for any 9670 * transformation properties currently set on the view, such as 9671 * {@link #setScaleX(float)} or {@link #setRotation(float)}. 9672 * 9673 * @param outRect The (scrolled) drawing bounds of the view. 9674 */ 9675 public void getDrawingRect(Rect outRect) { 9676 outRect.left = mScrollX; 9677 outRect.top = mScrollY; 9678 outRect.right = mScrollX + (mRight - mLeft); 9679 outRect.bottom = mScrollY + (mBottom - mTop); 9680 } 9681 9682 /** 9683 * Like {@link #getMeasuredWidthAndState()}, but only returns the 9684 * raw width component (that is the result is masked by 9685 * {@link #MEASURED_SIZE_MASK}). 9686 * 9687 * @return The raw measured width of this view. 9688 */ 9689 public final int getMeasuredWidth() { 9690 return mMeasuredWidth & MEASURED_SIZE_MASK; 9691 } 9692 9693 /** 9694 * Return the full width measurement information for this view as computed 9695 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 9696 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 9697 * This should be used during measurement and layout calculations only. Use 9698 * {@link #getWidth()} to see how wide a view is after layout. 9699 * 9700 * @return The measured width of this view as a bit mask. 9701 */ 9702 public final int getMeasuredWidthAndState() { 9703 return mMeasuredWidth; 9704 } 9705 9706 /** 9707 * Like {@link #getMeasuredHeightAndState()}, but only returns the 9708 * raw width component (that is the result is masked by 9709 * {@link #MEASURED_SIZE_MASK}). 9710 * 9711 * @return The raw measured height of this view. 9712 */ 9713 public final int getMeasuredHeight() { 9714 return mMeasuredHeight & MEASURED_SIZE_MASK; 9715 } 9716 9717 /** 9718 * Return the full height measurement information for this view as computed 9719 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 9720 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 9721 * This should be used during measurement and layout calculations only. Use 9722 * {@link #getHeight()} to see how wide a view is after layout. 9723 * 9724 * @return The measured width of this view as a bit mask. 9725 */ 9726 public final int getMeasuredHeightAndState() { 9727 return mMeasuredHeight; 9728 } 9729 9730 /** 9731 * Return only the state bits of {@link #getMeasuredWidthAndState()} 9732 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 9733 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 9734 * and the height component is at the shifted bits 9735 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 9736 */ 9737 public final int getMeasuredState() { 9738 return (mMeasuredWidth&MEASURED_STATE_MASK) 9739 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 9740 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 9741 } 9742 9743 /** 9744 * The transform matrix of this view, which is calculated based on the current 9745 * rotation, scale, and pivot properties. 9746 * 9747 * @see #getRotation() 9748 * @see #getScaleX() 9749 * @see #getScaleY() 9750 * @see #getPivotX() 9751 * @see #getPivotY() 9752 * @return The current transform matrix for the view 9753 */ 9754 public Matrix getMatrix() { 9755 ensureTransformationInfo(); 9756 final Matrix matrix = mTransformationInfo.mMatrix; 9757 mRenderNode.getMatrix(matrix); 9758 return matrix; 9759 } 9760 9761 /** 9762 * Returns true if the transform matrix is the identity matrix. 9763 * Recomputes the matrix if necessary. 9764 * 9765 * @return True if the transform matrix is the identity matrix, false otherwise. 9766 */ 9767 final boolean hasIdentityMatrix() { 9768 return mRenderNode.hasIdentityMatrix(); 9769 } 9770 9771 void ensureTransformationInfo() { 9772 if (mTransformationInfo == null) { 9773 mTransformationInfo = new TransformationInfo(); 9774 } 9775 } 9776 9777 /** 9778 * Utility method to retrieve the inverse of the current mMatrix property. 9779 * We cache the matrix to avoid recalculating it when transform properties 9780 * have not changed. 9781 * 9782 * @return The inverse of the current matrix of this view. 9783 */ 9784 final Matrix getInverseMatrix() { 9785 ensureTransformationInfo(); 9786 if (mTransformationInfo.mInverseMatrix == null) { 9787 mTransformationInfo.mInverseMatrix = new Matrix(); 9788 } 9789 final Matrix matrix = mTransformationInfo.mInverseMatrix; 9790 mRenderNode.getInverseMatrix(matrix); 9791 return matrix; 9792 } 9793 9794 /** 9795 * Gets the distance along the Z axis from the camera to this view. 9796 * 9797 * @see #setCameraDistance(float) 9798 * 9799 * @return The distance along the Z axis. 9800 */ 9801 public float getCameraDistance() { 9802 final float dpi = mResources.getDisplayMetrics().densityDpi; 9803 return -(mRenderNode.getCameraDistance() * dpi); 9804 } 9805 9806 /** 9807 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 9808 * views are drawn) from the camera to this view. The camera's distance 9809 * affects 3D transformations, for instance rotations around the X and Y 9810 * axis. If the rotationX or rotationY properties are changed and this view is 9811 * large (more than half the size of the screen), it is recommended to always 9812 * use a camera distance that's greater than the height (X axis rotation) or 9813 * the width (Y axis rotation) of this view.</p> 9814 * 9815 * <p>The distance of the camera from the view plane can have an affect on the 9816 * perspective distortion of the view when it is rotated around the x or y axis. 9817 * For example, a large distance will result in a large viewing angle, and there 9818 * will not be much perspective distortion of the view as it rotates. A short 9819 * distance may cause much more perspective distortion upon rotation, and can 9820 * also result in some drawing artifacts if the rotated view ends up partially 9821 * behind the camera (which is why the recommendation is to use a distance at 9822 * least as far as the size of the view, if the view is to be rotated.)</p> 9823 * 9824 * <p>The distance is expressed in "depth pixels." The default distance depends 9825 * on the screen density. For instance, on a medium density display, the 9826 * default distance is 1280. On a high density display, the default distance 9827 * is 1920.</p> 9828 * 9829 * <p>If you want to specify a distance that leads to visually consistent 9830 * results across various densities, use the following formula:</p> 9831 * <pre> 9832 * float scale = context.getResources().getDisplayMetrics().density; 9833 * view.setCameraDistance(distance * scale); 9834 * </pre> 9835 * 9836 * <p>The density scale factor of a high density display is 1.5, 9837 * and 1920 = 1280 * 1.5.</p> 9838 * 9839 * @param distance The distance in "depth pixels", if negative the opposite 9840 * value is used 9841 * 9842 * @see #setRotationX(float) 9843 * @see #setRotationY(float) 9844 */ 9845 public void setCameraDistance(float distance) { 9846 final float dpi = mResources.getDisplayMetrics().densityDpi; 9847 9848 invalidateViewProperty(true, false); 9849 mRenderNode.setCameraDistance(-Math.abs(distance) / dpi); 9850 invalidateViewProperty(false, false); 9851 9852 invalidateParentIfNeededAndWasQuickRejected(); 9853 } 9854 9855 /** 9856 * The degrees that the view is rotated around the pivot point. 9857 * 9858 * @see #setRotation(float) 9859 * @see #getPivotX() 9860 * @see #getPivotY() 9861 * 9862 * @return The degrees of rotation. 9863 */ 9864 @ViewDebug.ExportedProperty(category = "drawing") 9865 public float getRotation() { 9866 return mRenderNode.getRotation(); 9867 } 9868 9869 /** 9870 * Sets the degrees that the view is rotated around the pivot point. Increasing values 9871 * result in clockwise rotation. 9872 * 9873 * @param rotation The degrees of rotation. 9874 * 9875 * @see #getRotation() 9876 * @see #getPivotX() 9877 * @see #getPivotY() 9878 * @see #setRotationX(float) 9879 * @see #setRotationY(float) 9880 * 9881 * @attr ref android.R.styleable#View_rotation 9882 */ 9883 public void setRotation(float rotation) { 9884 if (rotation != getRotation()) { 9885 // Double-invalidation is necessary to capture view's old and new areas 9886 invalidateViewProperty(true, false); 9887 mRenderNode.setRotation(rotation); 9888 invalidateViewProperty(false, true); 9889 9890 invalidateParentIfNeededAndWasQuickRejected(); 9891 notifySubtreeAccessibilityStateChangedIfNeeded(); 9892 } 9893 } 9894 9895 /** 9896 * The degrees that the view is rotated around the vertical axis through the pivot point. 9897 * 9898 * @see #getPivotX() 9899 * @see #getPivotY() 9900 * @see #setRotationY(float) 9901 * 9902 * @return The degrees of Y rotation. 9903 */ 9904 @ViewDebug.ExportedProperty(category = "drawing") 9905 public float getRotationY() { 9906 return mRenderNode.getRotationY(); 9907 } 9908 9909 /** 9910 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 9911 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 9912 * down the y axis. 9913 * 9914 * When rotating large views, it is recommended to adjust the camera distance 9915 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 9916 * 9917 * @param rotationY The degrees of Y rotation. 9918 * 9919 * @see #getRotationY() 9920 * @see #getPivotX() 9921 * @see #getPivotY() 9922 * @see #setRotation(float) 9923 * @see #setRotationX(float) 9924 * @see #setCameraDistance(float) 9925 * 9926 * @attr ref android.R.styleable#View_rotationY 9927 */ 9928 public void setRotationY(float rotationY) { 9929 if (rotationY != getRotationY()) { 9930 invalidateViewProperty(true, false); 9931 mRenderNode.setRotationY(rotationY); 9932 invalidateViewProperty(false, true); 9933 9934 invalidateParentIfNeededAndWasQuickRejected(); 9935 notifySubtreeAccessibilityStateChangedIfNeeded(); 9936 } 9937 } 9938 9939 /** 9940 * The degrees that the view is rotated around the horizontal axis through the pivot point. 9941 * 9942 * @see #getPivotX() 9943 * @see #getPivotY() 9944 * @see #setRotationX(float) 9945 * 9946 * @return The degrees of X rotation. 9947 */ 9948 @ViewDebug.ExportedProperty(category = "drawing") 9949 public float getRotationX() { 9950 return mRenderNode.getRotationX(); 9951 } 9952 9953 /** 9954 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 9955 * Increasing values result in clockwise rotation from the viewpoint of looking down the 9956 * x axis. 9957 * 9958 * When rotating large views, it is recommended to adjust the camera distance 9959 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 9960 * 9961 * @param rotationX The degrees of X rotation. 9962 * 9963 * @see #getRotationX() 9964 * @see #getPivotX() 9965 * @see #getPivotY() 9966 * @see #setRotation(float) 9967 * @see #setRotationY(float) 9968 * @see #setCameraDistance(float) 9969 * 9970 * @attr ref android.R.styleable#View_rotationX 9971 */ 9972 public void setRotationX(float rotationX) { 9973 if (rotationX != getRotationX()) { 9974 invalidateViewProperty(true, false); 9975 mRenderNode.setRotationX(rotationX); 9976 invalidateViewProperty(false, true); 9977 9978 invalidateParentIfNeededAndWasQuickRejected(); 9979 notifySubtreeAccessibilityStateChangedIfNeeded(); 9980 } 9981 } 9982 9983 /** 9984 * The amount that the view is scaled in x around the pivot point, as a proportion of 9985 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 9986 * 9987 * <p>By default, this is 1.0f. 9988 * 9989 * @see #getPivotX() 9990 * @see #getPivotY() 9991 * @return The scaling factor. 9992 */ 9993 @ViewDebug.ExportedProperty(category = "drawing") 9994 public float getScaleX() { 9995 return mRenderNode.getScaleX(); 9996 } 9997 9998 /** 9999 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 10000 * the view's unscaled width. A value of 1 means that no scaling is applied. 10001 * 10002 * @param scaleX The scaling factor. 10003 * @see #getPivotX() 10004 * @see #getPivotY() 10005 * 10006 * @attr ref android.R.styleable#View_scaleX 10007 */ 10008 public void setScaleX(float scaleX) { 10009 if (scaleX != getScaleX()) { 10010 invalidateViewProperty(true, false); 10011 mRenderNode.setScaleX(scaleX); 10012 invalidateViewProperty(false, true); 10013 10014 invalidateParentIfNeededAndWasQuickRejected(); 10015 notifySubtreeAccessibilityStateChangedIfNeeded(); 10016 } 10017 } 10018 10019 /** 10020 * The amount that the view is scaled in y around the pivot point, as a proportion of 10021 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 10022 * 10023 * <p>By default, this is 1.0f. 10024 * 10025 * @see #getPivotX() 10026 * @see #getPivotY() 10027 * @return The scaling factor. 10028 */ 10029 @ViewDebug.ExportedProperty(category = "drawing") 10030 public float getScaleY() { 10031 return mRenderNode.getScaleY(); 10032 } 10033 10034 /** 10035 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 10036 * the view's unscaled width. A value of 1 means that no scaling is applied. 10037 * 10038 * @param scaleY The scaling factor. 10039 * @see #getPivotX() 10040 * @see #getPivotY() 10041 * 10042 * @attr ref android.R.styleable#View_scaleY 10043 */ 10044 public void setScaleY(float scaleY) { 10045 if (scaleY != getScaleY()) { 10046 invalidateViewProperty(true, false); 10047 mRenderNode.setScaleY(scaleY); 10048 invalidateViewProperty(false, true); 10049 10050 invalidateParentIfNeededAndWasQuickRejected(); 10051 notifySubtreeAccessibilityStateChangedIfNeeded(); 10052 } 10053 } 10054 10055 /** 10056 * The x location of the point around which the view is {@link #setRotation(float) rotated} 10057 * and {@link #setScaleX(float) scaled}. 10058 * 10059 * @see #getRotation() 10060 * @see #getScaleX() 10061 * @see #getScaleY() 10062 * @see #getPivotY() 10063 * @return The x location of the pivot point. 10064 * 10065 * @attr ref android.R.styleable#View_transformPivotX 10066 */ 10067 @ViewDebug.ExportedProperty(category = "drawing") 10068 public float getPivotX() { 10069 return mRenderNode.getPivotX(); 10070 } 10071 10072 /** 10073 * Sets the x location of the point around which the view is 10074 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 10075 * By default, the pivot point is centered on the object. 10076 * Setting this property disables this behavior and causes the view to use only the 10077 * explicitly set pivotX and pivotY values. 10078 * 10079 * @param pivotX The x location of the pivot point. 10080 * @see #getRotation() 10081 * @see #getScaleX() 10082 * @see #getScaleY() 10083 * @see #getPivotY() 10084 * 10085 * @attr ref android.R.styleable#View_transformPivotX 10086 */ 10087 public void setPivotX(float pivotX) { 10088 if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) { 10089 invalidateViewProperty(true, false); 10090 mRenderNode.setPivotX(pivotX); 10091 invalidateViewProperty(false, true); 10092 10093 invalidateParentIfNeededAndWasQuickRejected(); 10094 } 10095 } 10096 10097 /** 10098 * The y location of the point around which the view is {@link #setRotation(float) rotated} 10099 * and {@link #setScaleY(float) scaled}. 10100 * 10101 * @see #getRotation() 10102 * @see #getScaleX() 10103 * @see #getScaleY() 10104 * @see #getPivotY() 10105 * @return The y location of the pivot point. 10106 * 10107 * @attr ref android.R.styleable#View_transformPivotY 10108 */ 10109 @ViewDebug.ExportedProperty(category = "drawing") 10110 public float getPivotY() { 10111 return mRenderNode.getPivotY(); 10112 } 10113 10114 /** 10115 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 10116 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 10117 * Setting this property disables this behavior and causes the view to use only the 10118 * explicitly set pivotX and pivotY values. 10119 * 10120 * @param pivotY The y location of the pivot point. 10121 * @see #getRotation() 10122 * @see #getScaleX() 10123 * @see #getScaleY() 10124 * @see #getPivotY() 10125 * 10126 * @attr ref android.R.styleable#View_transformPivotY 10127 */ 10128 public void setPivotY(float pivotY) { 10129 if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) { 10130 invalidateViewProperty(true, false); 10131 mRenderNode.setPivotY(pivotY); 10132 invalidateViewProperty(false, true); 10133 10134 invalidateParentIfNeededAndWasQuickRejected(); 10135 } 10136 } 10137 10138 /** 10139 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 10140 * completely transparent and 1 means the view is completely opaque. 10141 * 10142 * <p>By default this is 1.0f. 10143 * @return The opacity of the view. 10144 */ 10145 @ViewDebug.ExportedProperty(category = "drawing") 10146 public float getAlpha() { 10147 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 10148 } 10149 10150 /** 10151 * Returns whether this View has content which overlaps. 10152 * 10153 * <p>This function, intended to be overridden by specific View types, is an optimization when 10154 * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to 10155 * an offscreen buffer and then composited into place, which can be expensive. If the view has 10156 * no overlapping rendering, the view can draw each primitive with the appropriate alpha value 10157 * directly. An example of overlapping rendering is a TextView with a background image, such as 10158 * a Button. An example of non-overlapping rendering is a TextView with no background, or an 10159 * ImageView with only the foreground image. The default implementation returns true; subclasses 10160 * should override if they have cases which can be optimized.</p> 10161 * 10162 * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas} 10163 * necessitates that a View return true if it uses the methods internally without passing the 10164 * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p> 10165 * 10166 * @return true if the content in this view might overlap, false otherwise. 10167 */ 10168 public boolean hasOverlappingRendering() { 10169 return true; 10170 } 10171 10172 /** 10173 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is 10174 * completely transparent and 1 means the view is completely opaque.</p> 10175 * 10176 * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant 10177 * performance implications, especially for large views. It is best to use the alpha property 10178 * sparingly and transiently, as in the case of fading animations.</p> 10179 * 10180 * <p>For a view with a frequently changing alpha, such as during a fading animation, it is 10181 * strongly recommended for performance reasons to either override 10182 * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a 10183 * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p> 10184 * 10185 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 10186 * responsible for applying the opacity itself.</p> 10187 * 10188 * <p>Note that if the view is backed by a 10189 * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a 10190 * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than 10191 * 1.0 will supercede the alpha of the layer paint.</p> 10192 * 10193 * @param alpha The opacity of the view. 10194 * 10195 * @see #hasOverlappingRendering() 10196 * @see #setLayerType(int, android.graphics.Paint) 10197 * 10198 * @attr ref android.R.styleable#View_alpha 10199 */ 10200 public void setAlpha(float alpha) { 10201 ensureTransformationInfo(); 10202 if (mTransformationInfo.mAlpha != alpha) { 10203 mTransformationInfo.mAlpha = alpha; 10204 if (onSetAlpha((int) (alpha * 255))) { 10205 mPrivateFlags |= PFLAG_ALPHA_SET; 10206 // subclass is handling alpha - don't optimize rendering cache invalidation 10207 invalidateParentCaches(); 10208 invalidate(true); 10209 } else { 10210 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10211 invalidateViewProperty(true, false); 10212 mRenderNode.setAlpha(getFinalAlpha()); 10213 notifyViewAccessibilityStateChangedIfNeeded( 10214 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 10215 } 10216 } 10217 } 10218 10219 /** 10220 * Faster version of setAlpha() which performs the same steps except there are 10221 * no calls to invalidate(). The caller of this function should perform proper invalidation 10222 * on the parent and this object. The return value indicates whether the subclass handles 10223 * alpha (the return value for onSetAlpha()). 10224 * 10225 * @param alpha The new value for the alpha property 10226 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 10227 * the new value for the alpha property is different from the old value 10228 */ 10229 boolean setAlphaNoInvalidation(float alpha) { 10230 ensureTransformationInfo(); 10231 if (mTransformationInfo.mAlpha != alpha) { 10232 mTransformationInfo.mAlpha = alpha; 10233 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 10234 if (subclassHandlesAlpha) { 10235 mPrivateFlags |= PFLAG_ALPHA_SET; 10236 return true; 10237 } else { 10238 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10239 mRenderNode.setAlpha(getFinalAlpha()); 10240 } 10241 } 10242 return false; 10243 } 10244 10245 /** 10246 * This property is hidden and intended only for use by the Fade transition, which 10247 * animates it to produce a visual translucency that does not side-effect (or get 10248 * affected by) the real alpha property. This value is composited with the other 10249 * alpha value (and the AlphaAnimation value, when that is present) to produce 10250 * a final visual translucency result, which is what is passed into the DisplayList. 10251 * 10252 * @hide 10253 */ 10254 public void setTransitionAlpha(float alpha) { 10255 ensureTransformationInfo(); 10256 if (mTransformationInfo.mTransitionAlpha != alpha) { 10257 mTransformationInfo.mTransitionAlpha = alpha; 10258 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10259 invalidateViewProperty(true, false); 10260 mRenderNode.setAlpha(getFinalAlpha()); 10261 } 10262 } 10263 10264 /** 10265 * Calculates the visual alpha of this view, which is a combination of the actual 10266 * alpha value and the transitionAlpha value (if set). 10267 */ 10268 private float getFinalAlpha() { 10269 if (mTransformationInfo != null) { 10270 return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha; 10271 } 10272 return 1; 10273 } 10274 10275 /** 10276 * This property is hidden and intended only for use by the Fade transition, which 10277 * animates it to produce a visual translucency that does not side-effect (or get 10278 * affected by) the real alpha property. This value is composited with the other 10279 * alpha value (and the AlphaAnimation value, when that is present) to produce 10280 * a final visual translucency result, which is what is passed into the DisplayList. 10281 * 10282 * @hide 10283 */ 10284 public float getTransitionAlpha() { 10285 return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1; 10286 } 10287 10288 /** 10289 * Top position of this view relative to its parent. 10290 * 10291 * @return The top of this view, in pixels. 10292 */ 10293 @ViewDebug.CapturedViewProperty 10294 public final int getTop() { 10295 return mTop; 10296 } 10297 10298 /** 10299 * Sets the top position of this view relative to its parent. This method is meant to be called 10300 * by the layout system and should not generally be called otherwise, because the property 10301 * may be changed at any time by the layout. 10302 * 10303 * @param top The top of this view, in pixels. 10304 */ 10305 public final void setTop(int top) { 10306 if (top != mTop) { 10307 final boolean matrixIsIdentity = hasIdentityMatrix(); 10308 if (matrixIsIdentity) { 10309 if (mAttachInfo != null) { 10310 int minTop; 10311 int yLoc; 10312 if (top < mTop) { 10313 minTop = top; 10314 yLoc = top - mTop; 10315 } else { 10316 minTop = mTop; 10317 yLoc = 0; 10318 } 10319 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 10320 } 10321 } else { 10322 // Double-invalidation is necessary to capture view's old and new areas 10323 invalidate(true); 10324 } 10325 10326 int width = mRight - mLeft; 10327 int oldHeight = mBottom - mTop; 10328 10329 mTop = top; 10330 mRenderNode.setTop(mTop); 10331 10332 sizeChange(width, mBottom - mTop, width, oldHeight); 10333 10334 if (!matrixIsIdentity) { 10335 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10336 invalidate(true); 10337 } 10338 mBackgroundSizeChanged = true; 10339 invalidateParentIfNeeded(); 10340 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10341 // View was rejected last time it was drawn by its parent; this may have changed 10342 invalidateParentIfNeeded(); 10343 } 10344 } 10345 } 10346 10347 /** 10348 * Bottom position of this view relative to its parent. 10349 * 10350 * @return The bottom of this view, in pixels. 10351 */ 10352 @ViewDebug.CapturedViewProperty 10353 public final int getBottom() { 10354 return mBottom; 10355 } 10356 10357 /** 10358 * True if this view has changed since the last time being drawn. 10359 * 10360 * @return The dirty state of this view. 10361 */ 10362 public boolean isDirty() { 10363 return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0; 10364 } 10365 10366 /** 10367 * Sets the bottom position of this view relative to its parent. This method is meant to be 10368 * called by the layout system and should not generally be called otherwise, because the 10369 * property may be changed at any time by the layout. 10370 * 10371 * @param bottom The bottom of this view, in pixels. 10372 */ 10373 public final void setBottom(int bottom) { 10374 if (bottom != mBottom) { 10375 final boolean matrixIsIdentity = hasIdentityMatrix(); 10376 if (matrixIsIdentity) { 10377 if (mAttachInfo != null) { 10378 int maxBottom; 10379 if (bottom < mBottom) { 10380 maxBottom = mBottom; 10381 } else { 10382 maxBottom = bottom; 10383 } 10384 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 10385 } 10386 } else { 10387 // Double-invalidation is necessary to capture view's old and new areas 10388 invalidate(true); 10389 } 10390 10391 int width = mRight - mLeft; 10392 int oldHeight = mBottom - mTop; 10393 10394 mBottom = bottom; 10395 mRenderNode.setBottom(mBottom); 10396 10397 sizeChange(width, mBottom - mTop, width, oldHeight); 10398 10399 if (!matrixIsIdentity) { 10400 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10401 invalidate(true); 10402 } 10403 mBackgroundSizeChanged = true; 10404 invalidateParentIfNeeded(); 10405 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10406 // View was rejected last time it was drawn by its parent; this may have changed 10407 invalidateParentIfNeeded(); 10408 } 10409 } 10410 } 10411 10412 /** 10413 * Left position of this view relative to its parent. 10414 * 10415 * @return The left edge of this view, in pixels. 10416 */ 10417 @ViewDebug.CapturedViewProperty 10418 public final int getLeft() { 10419 return mLeft; 10420 } 10421 10422 /** 10423 * Sets the left position of this view relative to its parent. This method is meant to be called 10424 * by the layout system and should not generally be called otherwise, because the property 10425 * may be changed at any time by the layout. 10426 * 10427 * @param left The left of this view, in pixels. 10428 */ 10429 public final void setLeft(int left) { 10430 if (left != mLeft) { 10431 final boolean matrixIsIdentity = hasIdentityMatrix(); 10432 if (matrixIsIdentity) { 10433 if (mAttachInfo != null) { 10434 int minLeft; 10435 int xLoc; 10436 if (left < mLeft) { 10437 minLeft = left; 10438 xLoc = left - mLeft; 10439 } else { 10440 minLeft = mLeft; 10441 xLoc = 0; 10442 } 10443 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 10444 } 10445 } else { 10446 // Double-invalidation is necessary to capture view's old and new areas 10447 invalidate(true); 10448 } 10449 10450 int oldWidth = mRight - mLeft; 10451 int height = mBottom - mTop; 10452 10453 mLeft = left; 10454 mRenderNode.setLeft(left); 10455 10456 sizeChange(mRight - mLeft, height, oldWidth, height); 10457 10458 if (!matrixIsIdentity) { 10459 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10460 invalidate(true); 10461 } 10462 mBackgroundSizeChanged = true; 10463 invalidateParentIfNeeded(); 10464 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10465 // View was rejected last time it was drawn by its parent; this may have changed 10466 invalidateParentIfNeeded(); 10467 } 10468 } 10469 } 10470 10471 /** 10472 * Right position of this view relative to its parent. 10473 * 10474 * @return The right edge of this view, in pixels. 10475 */ 10476 @ViewDebug.CapturedViewProperty 10477 public final int getRight() { 10478 return mRight; 10479 } 10480 10481 /** 10482 * Sets the right position of this view relative to its parent. This method is meant to be called 10483 * by the layout system and should not generally be called otherwise, because the property 10484 * may be changed at any time by the layout. 10485 * 10486 * @param right The right of this view, in pixels. 10487 */ 10488 public final void setRight(int right) { 10489 if (right != mRight) { 10490 final boolean matrixIsIdentity = hasIdentityMatrix(); 10491 if (matrixIsIdentity) { 10492 if (mAttachInfo != null) { 10493 int maxRight; 10494 if (right < mRight) { 10495 maxRight = mRight; 10496 } else { 10497 maxRight = right; 10498 } 10499 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 10500 } 10501 } else { 10502 // Double-invalidation is necessary to capture view's old and new areas 10503 invalidate(true); 10504 } 10505 10506 int oldWidth = mRight - mLeft; 10507 int height = mBottom - mTop; 10508 10509 mRight = right; 10510 mRenderNode.setRight(mRight); 10511 10512 sizeChange(mRight - mLeft, height, oldWidth, height); 10513 10514 if (!matrixIsIdentity) { 10515 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10516 invalidate(true); 10517 } 10518 mBackgroundSizeChanged = true; 10519 invalidateParentIfNeeded(); 10520 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10521 // View was rejected last time it was drawn by its parent; this may have changed 10522 invalidateParentIfNeeded(); 10523 } 10524 } 10525 } 10526 10527 /** 10528 * The visual x position of this view, in pixels. This is equivalent to the 10529 * {@link #setTranslationX(float) translationX} property plus the current 10530 * {@link #getLeft() left} property. 10531 * 10532 * @return The visual x position of this view, in pixels. 10533 */ 10534 @ViewDebug.ExportedProperty(category = "drawing") 10535 public float getX() { 10536 return mLeft + getTranslationX(); 10537 } 10538 10539 /** 10540 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 10541 * {@link #setTranslationX(float) translationX} property to be the difference between 10542 * the x value passed in and the current {@link #getLeft() left} property. 10543 * 10544 * @param x The visual x position of this view, in pixels. 10545 */ 10546 public void setX(float x) { 10547 setTranslationX(x - mLeft); 10548 } 10549 10550 /** 10551 * The visual y position of this view, in pixels. This is equivalent to the 10552 * {@link #setTranslationY(float) translationY} property plus the current 10553 * {@link #getTop() top} property. 10554 * 10555 * @return The visual y position of this view, in pixels. 10556 */ 10557 @ViewDebug.ExportedProperty(category = "drawing") 10558 public float getY() { 10559 return mTop + getTranslationY(); 10560 } 10561 10562 /** 10563 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 10564 * {@link #setTranslationY(float) translationY} property to be the difference between 10565 * the y value passed in and the current {@link #getTop() top} property. 10566 * 10567 * @param y The visual y position of this view, in pixels. 10568 */ 10569 public void setY(float y) { 10570 setTranslationY(y - mTop); 10571 } 10572 10573 /** 10574 * The visual z position of this view, in pixels. This is equivalent to the 10575 * {@link #setTranslationZ(float) translationZ} property plus the current 10576 * {@link #getElevation() elevation} property. 10577 * 10578 * @return The visual z position of this view, in pixels. 10579 */ 10580 @ViewDebug.ExportedProperty(category = "drawing") 10581 public float getZ() { 10582 return getElevation() + getTranslationZ(); 10583 } 10584 10585 /** 10586 * Sets the visual z position of this view, in pixels. This is equivalent to setting the 10587 * {@link #setTranslationZ(float) translationZ} property to be the difference between 10588 * the x value passed in and the current {@link #getElevation() elevation} property. 10589 * 10590 * @param z The visual z position of this view, in pixels. 10591 */ 10592 public void setZ(float z) { 10593 setTranslationZ(z - getElevation()); 10594 } 10595 10596 /** 10597 * The base elevation of this view relative to its parent, in pixels. 10598 * 10599 * @return The base depth position of the view, in pixels. 10600 */ 10601 @ViewDebug.ExportedProperty(category = "drawing") 10602 public float getElevation() { 10603 return mRenderNode.getElevation(); 10604 } 10605 10606 /** 10607 * Sets the base elevation of this view, in pixels. 10608 * 10609 * @attr ref android.R.styleable#View_elevation 10610 */ 10611 public void setElevation(float elevation) { 10612 if (elevation != getElevation()) { 10613 invalidateViewProperty(true, false); 10614 mRenderNode.setElevation(elevation); 10615 invalidateViewProperty(false, true); 10616 10617 invalidateParentIfNeededAndWasQuickRejected(); 10618 } 10619 } 10620 10621 /** 10622 * The horizontal location of this view relative to its {@link #getLeft() left} position. 10623 * This position is post-layout, in addition to wherever the object's 10624 * layout placed it. 10625 * 10626 * @return The horizontal position of this view relative to its left position, in pixels. 10627 */ 10628 @ViewDebug.ExportedProperty(category = "drawing") 10629 public float getTranslationX() { 10630 return mRenderNode.getTranslationX(); 10631 } 10632 10633 /** 10634 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 10635 * This effectively positions the object post-layout, in addition to wherever the object's 10636 * layout placed it. 10637 * 10638 * @param translationX The horizontal position of this view relative to its left position, 10639 * in pixels. 10640 * 10641 * @attr ref android.R.styleable#View_translationX 10642 */ 10643 public void setTranslationX(float translationX) { 10644 if (translationX != getTranslationX()) { 10645 invalidateViewProperty(true, false); 10646 mRenderNode.setTranslationX(translationX); 10647 invalidateViewProperty(false, true); 10648 10649 invalidateParentIfNeededAndWasQuickRejected(); 10650 notifySubtreeAccessibilityStateChangedIfNeeded(); 10651 } 10652 } 10653 10654 /** 10655 * The vertical location of this view relative to its {@link #getTop() top} position. 10656 * This position is post-layout, in addition to wherever the object's 10657 * layout placed it. 10658 * 10659 * @return The vertical position of this view relative to its top position, 10660 * in pixels. 10661 */ 10662 @ViewDebug.ExportedProperty(category = "drawing") 10663 public float getTranslationY() { 10664 return mRenderNode.getTranslationY(); 10665 } 10666 10667 /** 10668 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 10669 * This effectively positions the object post-layout, in addition to wherever the object's 10670 * layout placed it. 10671 * 10672 * @param translationY The vertical position of this view relative to its top position, 10673 * in pixels. 10674 * 10675 * @attr ref android.R.styleable#View_translationY 10676 */ 10677 public void setTranslationY(float translationY) { 10678 if (translationY != getTranslationY()) { 10679 invalidateViewProperty(true, false); 10680 mRenderNode.setTranslationY(translationY); 10681 invalidateViewProperty(false, true); 10682 10683 invalidateParentIfNeededAndWasQuickRejected(); 10684 } 10685 } 10686 10687 /** 10688 * The depth location of this view relative to its {@link #getElevation() elevation}. 10689 * 10690 * @return The depth of this view relative to its elevation. 10691 */ 10692 @ViewDebug.ExportedProperty(category = "drawing") 10693 public float getTranslationZ() { 10694 return mRenderNode.getTranslationZ(); 10695 } 10696 10697 /** 10698 * Sets the depth location of this view relative to its {@link #getElevation() elevation}. 10699 * 10700 * @attr ref android.R.styleable#View_translationZ 10701 */ 10702 public void setTranslationZ(float translationZ) { 10703 if (translationZ != getTranslationZ()) { 10704 invalidateViewProperty(true, false); 10705 mRenderNode.setTranslationZ(translationZ); 10706 invalidateViewProperty(false, true); 10707 10708 invalidateParentIfNeededAndWasQuickRejected(); 10709 } 10710 } 10711 10712 /** 10713 * Returns a ValueAnimator which can animate a clearing circle. 10714 * <p> 10715 * The View is prevented from drawing within the circle, so the content 10716 * behind the View shows through. 10717 * 10718 * @param centerX The x coordinate of the center of the animating circle. 10719 * @param centerY The y coordinate of the center of the animating circle. 10720 * @param startRadius The starting radius of the animating circle. 10721 * @param endRadius The ending radius of the animating circle. 10722 * 10723 * @hide 10724 */ 10725 public final ValueAnimator createClearCircleAnimator(int centerX, int centerY, 10726 float startRadius, float endRadius) { 10727 return RevealAnimator.ofRevealCircle(this, centerX, centerY, 10728 startRadius, endRadius, true); 10729 } 10730 10731 /** 10732 * Returns the current StateListAnimator if exists. 10733 * 10734 * @return StateListAnimator or null if it does not exists 10735 * @see #setStateListAnimator(android.animation.StateListAnimator) 10736 */ 10737 public StateListAnimator getStateListAnimator() { 10738 return mStateListAnimator; 10739 } 10740 10741 /** 10742 * Attaches the provided StateListAnimator to this View. 10743 * <p> 10744 * Any previously attached StateListAnimator will be detached. 10745 * 10746 * @param stateListAnimator The StateListAnimator to update the view 10747 * @see {@link android.animation.StateListAnimator} 10748 */ 10749 public void setStateListAnimator(StateListAnimator stateListAnimator) { 10750 if (mStateListAnimator == stateListAnimator) { 10751 return; 10752 } 10753 if (mStateListAnimator != null) { 10754 mStateListAnimator.setTarget(null); 10755 } 10756 mStateListAnimator = stateListAnimator; 10757 if (stateListAnimator != null) { 10758 stateListAnimator.setTarget(this); 10759 if (isAttachedToWindow()) { 10760 stateListAnimator.setState(getDrawableState()); 10761 } 10762 } 10763 } 10764 10765 /** Deprecated, pending removal */ 10766 @Deprecated 10767 public void setOutline(@Nullable Outline outline) {} 10768 10769 /** 10770 * Returns whether the Outline should be used to clip the contents of the View. 10771 * <p> 10772 * Note that this flag will only be respected if the View's Outline returns true from 10773 * {@link Outline#canClip()}. 10774 * 10775 * @see #setOutlineProvider(ViewOutlineProvider) 10776 * @see #setClipToOutline(boolean) 10777 */ 10778 public final boolean getClipToOutline() { 10779 return mRenderNode.getClipToOutline(); 10780 } 10781 10782 /** 10783 * Sets whether the View's Outline should be used to clip the contents of the View. 10784 * <p> 10785 * Note that this flag will only be respected if the View's Outline returns true from 10786 * {@link Outline#canClip()}. 10787 * 10788 * @see #setOutlineProvider(ViewOutlineProvider) 10789 * @see #getClipToOutline() 10790 */ 10791 public void setClipToOutline(boolean clipToOutline) { 10792 damageInParent(); 10793 if (getClipToOutline() != clipToOutline) { 10794 mRenderNode.setClipToOutline(clipToOutline); 10795 } 10796 } 10797 10798 /** 10799 * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines 10800 * the shape of the shadow it casts, and enables outline clipping. 10801 * <p> 10802 * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline 10803 * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the 10804 * outline provider with this method allows this behavior to be overridden. 10805 * <p> 10806 * If the ViewOutlineProvider is null, if querying it for an outline returns false, 10807 * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast. 10808 * <p> 10809 * Only outlines that return true from {@link Outline#canClip()} may be used for clipping. 10810 * 10811 * @see #setClipToOutline(boolean) 10812 * @see #getClipToOutline() 10813 * @see #getOutlineProvider() 10814 */ 10815 public void setOutlineProvider(ViewOutlineProvider provider) { 10816 mOutlineProvider = provider; 10817 invalidateOutline(); 10818 } 10819 10820 /** 10821 * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline 10822 * that defines the shape of the shadow it casts, and enables outline clipping. 10823 * 10824 * @see #setOutlineProvider(ViewOutlineProvider) 10825 */ 10826 public ViewOutlineProvider getOutlineProvider() { 10827 return mOutlineProvider; 10828 } 10829 10830 /** 10831 * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider} 10832 * 10833 * @see #setOutlineProvider(ViewOutlineProvider) 10834 */ 10835 public void invalidateOutline() { 10836 // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow() 10837 if (mAttachInfo == null) return; 10838 10839 final Outline outline = mAttachInfo.mTmpOutline; 10840 outline.setEmpty(); 10841 10842 if (mOutlineProvider == null) { 10843 // no provider, remove outline 10844 mRenderNode.setOutline(null); 10845 } else { 10846 if (mOutlineProvider.getOutline(this, outline)) { 10847 if (outline.isEmpty()) { 10848 throw new IllegalStateException("Outline provider failed to build outline"); 10849 } 10850 // provider has provided 10851 mRenderNode.setOutline(outline); 10852 } else { 10853 // provider failed to provide 10854 mRenderNode.setOutline(null); 10855 } 10856 } 10857 10858 notifySubtreeAccessibilityStateChangedIfNeeded(); 10859 invalidateViewProperty(false, false); 10860 } 10861 10862 /** 10863 * Private API to be used for reveal animation 10864 * 10865 * @hide 10866 */ 10867 public void setRevealClip(boolean shouldClip, boolean inverseClip, 10868 float x, float y, float radius) { 10869 mRenderNode.setRevealClip(shouldClip, inverseClip, x, y, radius); 10870 // TODO: Handle this invalidate in a better way, or purely in native. 10871 invalidate(); 10872 } 10873 10874 /** 10875 * Hit rectangle in parent's coordinates 10876 * 10877 * @param outRect The hit rectangle of the view. 10878 */ 10879 public void getHitRect(Rect outRect) { 10880 if (hasIdentityMatrix() || mAttachInfo == null) { 10881 outRect.set(mLeft, mTop, mRight, mBottom); 10882 } else { 10883 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 10884 tmpRect.set(0, 0, getWidth(), getHeight()); 10885 getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect) 10886 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 10887 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 10888 } 10889 } 10890 10891 /** 10892 * Determines whether the given point, in local coordinates is inside the view. 10893 */ 10894 /*package*/ final boolean pointInView(float localX, float localY) { 10895 return localX >= 0 && localX < (mRight - mLeft) 10896 && localY >= 0 && localY < (mBottom - mTop); 10897 } 10898 10899 /** 10900 * Utility method to determine whether the given point, in local coordinates, 10901 * is inside the view, where the area of the view is expanded by the slop factor. 10902 * This method is called while processing touch-move events to determine if the event 10903 * is still within the view. 10904 * 10905 * @hide 10906 */ 10907 public boolean pointInView(float localX, float localY, float slop) { 10908 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 10909 localY < ((mBottom - mTop) + slop); 10910 } 10911 10912 /** 10913 * When a view has focus and the user navigates away from it, the next view is searched for 10914 * starting from the rectangle filled in by this method. 10915 * 10916 * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)}) 10917 * of the view. However, if your view maintains some idea of internal selection, 10918 * such as a cursor, or a selected row or column, you should override this method and 10919 * fill in a more specific rectangle. 10920 * 10921 * @param r The rectangle to fill in, in this view's coordinates. 10922 */ 10923 public void getFocusedRect(Rect r) { 10924 getDrawingRect(r); 10925 } 10926 10927 /** 10928 * If some part of this view is not clipped by any of its parents, then 10929 * return that area in r in global (root) coordinates. To convert r to local 10930 * coordinates (without taking possible View rotations into account), offset 10931 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 10932 * If the view is completely clipped or translated out, return false. 10933 * 10934 * @param r If true is returned, r holds the global coordinates of the 10935 * visible portion of this view. 10936 * @param globalOffset If true is returned, globalOffset holds the dx,dy 10937 * between this view and its root. globalOffet may be null. 10938 * @return true if r is non-empty (i.e. part of the view is visible at the 10939 * root level. 10940 */ 10941 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 10942 int width = mRight - mLeft; 10943 int height = mBottom - mTop; 10944 if (width > 0 && height > 0) { 10945 r.set(0, 0, width, height); 10946 if (globalOffset != null) { 10947 globalOffset.set(-mScrollX, -mScrollY); 10948 } 10949 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 10950 } 10951 return false; 10952 } 10953 10954 public final boolean getGlobalVisibleRect(Rect r) { 10955 return getGlobalVisibleRect(r, null); 10956 } 10957 10958 public final boolean getLocalVisibleRect(Rect r) { 10959 final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point(); 10960 if (getGlobalVisibleRect(r, offset)) { 10961 r.offset(-offset.x, -offset.y); // make r local 10962 return true; 10963 } 10964 return false; 10965 } 10966 10967 /** 10968 * Offset this view's vertical location by the specified number of pixels. 10969 * 10970 * @param offset the number of pixels to offset the view by 10971 */ 10972 public void offsetTopAndBottom(int offset) { 10973 if (offset != 0) { 10974 final boolean matrixIsIdentity = hasIdentityMatrix(); 10975 if (matrixIsIdentity) { 10976 if (isHardwareAccelerated()) { 10977 invalidateViewProperty(false, false); 10978 } else { 10979 final ViewParent p = mParent; 10980 if (p != null && mAttachInfo != null) { 10981 final Rect r = mAttachInfo.mTmpInvalRect; 10982 int minTop; 10983 int maxBottom; 10984 int yLoc; 10985 if (offset < 0) { 10986 minTop = mTop + offset; 10987 maxBottom = mBottom; 10988 yLoc = offset; 10989 } else { 10990 minTop = mTop; 10991 maxBottom = mBottom + offset; 10992 yLoc = 0; 10993 } 10994 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 10995 p.invalidateChild(this, r); 10996 } 10997 } 10998 } else { 10999 invalidateViewProperty(false, false); 11000 } 11001 11002 mTop += offset; 11003 mBottom += offset; 11004 mRenderNode.offsetTopAndBottom(offset); 11005 if (isHardwareAccelerated()) { 11006 invalidateViewProperty(false, false); 11007 } else { 11008 if (!matrixIsIdentity) { 11009 invalidateViewProperty(false, true); 11010 } 11011 invalidateParentIfNeeded(); 11012 } 11013 notifySubtreeAccessibilityStateChangedIfNeeded(); 11014 } 11015 } 11016 11017 /** 11018 * Offset this view's horizontal location by the specified amount of pixels. 11019 * 11020 * @param offset the number of pixels to offset the view by 11021 */ 11022 public void offsetLeftAndRight(int offset) { 11023 if (offset != 0) { 11024 final boolean matrixIsIdentity = hasIdentityMatrix(); 11025 if (matrixIsIdentity) { 11026 if (isHardwareAccelerated()) { 11027 invalidateViewProperty(false, false); 11028 } else { 11029 final ViewParent p = mParent; 11030 if (p != null && mAttachInfo != null) { 11031 final Rect r = mAttachInfo.mTmpInvalRect; 11032 int minLeft; 11033 int maxRight; 11034 if (offset < 0) { 11035 minLeft = mLeft + offset; 11036 maxRight = mRight; 11037 } else { 11038 minLeft = mLeft; 11039 maxRight = mRight + offset; 11040 } 11041 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 11042 p.invalidateChild(this, r); 11043 } 11044 } 11045 } else { 11046 invalidateViewProperty(false, false); 11047 } 11048 11049 mLeft += offset; 11050 mRight += offset; 11051 mRenderNode.offsetLeftAndRight(offset); 11052 if (isHardwareAccelerated()) { 11053 invalidateViewProperty(false, false); 11054 } else { 11055 if (!matrixIsIdentity) { 11056 invalidateViewProperty(false, true); 11057 } 11058 invalidateParentIfNeeded(); 11059 } 11060 notifySubtreeAccessibilityStateChangedIfNeeded(); 11061 } 11062 } 11063 11064 /** 11065 * Get the LayoutParams associated with this view. All views should have 11066 * layout parameters. These supply parameters to the <i>parent</i> of this 11067 * view specifying how it should be arranged. There are many subclasses of 11068 * ViewGroup.LayoutParams, and these correspond to the different subclasses 11069 * of ViewGroup that are responsible for arranging their children. 11070 * 11071 * This method may return null if this View is not attached to a parent 11072 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 11073 * was not invoked successfully. When a View is attached to a parent 11074 * ViewGroup, this method must not return null. 11075 * 11076 * @return The LayoutParams associated with this view, or null if no 11077 * parameters have been set yet 11078 */ 11079 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 11080 public ViewGroup.LayoutParams getLayoutParams() { 11081 return mLayoutParams; 11082 } 11083 11084 /** 11085 * Set the layout parameters associated with this view. These supply 11086 * parameters to the <i>parent</i> of this view specifying how it should be 11087 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 11088 * correspond to the different subclasses of ViewGroup that are responsible 11089 * for arranging their children. 11090 * 11091 * @param params The layout parameters for this view, cannot be null 11092 */ 11093 public void setLayoutParams(ViewGroup.LayoutParams params) { 11094 if (params == null) { 11095 throw new NullPointerException("Layout parameters cannot be null"); 11096 } 11097 mLayoutParams = params; 11098 resolveLayoutParams(); 11099 if (mParent instanceof ViewGroup) { 11100 ((ViewGroup) mParent).onSetLayoutParams(this, params); 11101 } 11102 requestLayout(); 11103 } 11104 11105 /** 11106 * Resolve the layout parameters depending on the resolved layout direction 11107 * 11108 * @hide 11109 */ 11110 public void resolveLayoutParams() { 11111 if (mLayoutParams != null) { 11112 mLayoutParams.resolveLayoutDirection(getLayoutDirection()); 11113 } 11114 } 11115 11116 /** 11117 * Set the scrolled position of your view. This will cause a call to 11118 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11119 * invalidated. 11120 * @param x the x position to scroll to 11121 * @param y the y position to scroll to 11122 */ 11123 public void scrollTo(int x, int y) { 11124 if (mScrollX != x || mScrollY != y) { 11125 int oldX = mScrollX; 11126 int oldY = mScrollY; 11127 mScrollX = x; 11128 mScrollY = y; 11129 invalidateParentCaches(); 11130 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 11131 if (!awakenScrollBars()) { 11132 postInvalidateOnAnimation(); 11133 } 11134 } 11135 } 11136 11137 /** 11138 * Move the scrolled position of your view. This will cause a call to 11139 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11140 * invalidated. 11141 * @param x the amount of pixels to scroll by horizontally 11142 * @param y the amount of pixels to scroll by vertically 11143 */ 11144 public void scrollBy(int x, int y) { 11145 scrollTo(mScrollX + x, mScrollY + y); 11146 } 11147 11148 /** 11149 * <p>Trigger the scrollbars to draw. When invoked this method starts an 11150 * animation to fade the scrollbars out after a default delay. If a subclass 11151 * provides animated scrolling, the start delay should equal the duration 11152 * of the scrolling animation.</p> 11153 * 11154 * <p>The animation starts only if at least one of the scrollbars is 11155 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 11156 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11157 * this method returns true, and false otherwise. If the animation is 11158 * started, this method calls {@link #invalidate()}; in that case the 11159 * caller should not call {@link #invalidate()}.</p> 11160 * 11161 * <p>This method should be invoked every time a subclass directly updates 11162 * the scroll parameters.</p> 11163 * 11164 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 11165 * and {@link #scrollTo(int, int)}.</p> 11166 * 11167 * @return true if the animation is played, false otherwise 11168 * 11169 * @see #awakenScrollBars(int) 11170 * @see #scrollBy(int, int) 11171 * @see #scrollTo(int, int) 11172 * @see #isHorizontalScrollBarEnabled() 11173 * @see #isVerticalScrollBarEnabled() 11174 * @see #setHorizontalScrollBarEnabled(boolean) 11175 * @see #setVerticalScrollBarEnabled(boolean) 11176 */ 11177 protected boolean awakenScrollBars() { 11178 return mScrollCache != null && 11179 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 11180 } 11181 11182 /** 11183 * Trigger the scrollbars to draw. 11184 * This method differs from awakenScrollBars() only in its default duration. 11185 * initialAwakenScrollBars() will show the scroll bars for longer than 11186 * usual to give the user more of a chance to notice them. 11187 * 11188 * @return true if the animation is played, false otherwise. 11189 */ 11190 private boolean initialAwakenScrollBars() { 11191 return mScrollCache != null && 11192 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 11193 } 11194 11195 /** 11196 * <p> 11197 * Trigger the scrollbars to draw. When invoked this method starts an 11198 * animation to fade the scrollbars out after a fixed delay. If a subclass 11199 * provides animated scrolling, the start delay should equal the duration of 11200 * the scrolling animation. 11201 * </p> 11202 * 11203 * <p> 11204 * The animation starts only if at least one of the scrollbars is enabled, 11205 * as specified by {@link #isHorizontalScrollBarEnabled()} and 11206 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11207 * this method returns true, and false otherwise. If the animation is 11208 * started, this method calls {@link #invalidate()}; in that case the caller 11209 * should not call {@link #invalidate()}. 11210 * </p> 11211 * 11212 * <p> 11213 * This method should be invoked everytime a subclass directly updates the 11214 * scroll parameters. 11215 * </p> 11216 * 11217 * @param startDelay the delay, in milliseconds, after which the animation 11218 * should start; when the delay is 0, the animation starts 11219 * immediately 11220 * @return true if the animation is played, false otherwise 11221 * 11222 * @see #scrollBy(int, int) 11223 * @see #scrollTo(int, int) 11224 * @see #isHorizontalScrollBarEnabled() 11225 * @see #isVerticalScrollBarEnabled() 11226 * @see #setHorizontalScrollBarEnabled(boolean) 11227 * @see #setVerticalScrollBarEnabled(boolean) 11228 */ 11229 protected boolean awakenScrollBars(int startDelay) { 11230 return awakenScrollBars(startDelay, true); 11231 } 11232 11233 /** 11234 * <p> 11235 * Trigger the scrollbars to draw. When invoked this method starts an 11236 * animation to fade the scrollbars out after a fixed delay. If a subclass 11237 * provides animated scrolling, the start delay should equal the duration of 11238 * the scrolling animation. 11239 * </p> 11240 * 11241 * <p> 11242 * The animation starts only if at least one of the scrollbars is enabled, 11243 * as specified by {@link #isHorizontalScrollBarEnabled()} and 11244 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11245 * this method returns true, and false otherwise. If the animation is 11246 * started, this method calls {@link #invalidate()} if the invalidate parameter 11247 * is set to true; in that case the caller 11248 * should not call {@link #invalidate()}. 11249 * </p> 11250 * 11251 * <p> 11252 * This method should be invoked everytime a subclass directly updates the 11253 * scroll parameters. 11254 * </p> 11255 * 11256 * @param startDelay the delay, in milliseconds, after which the animation 11257 * should start; when the delay is 0, the animation starts 11258 * immediately 11259 * 11260 * @param invalidate Wheter this method should call invalidate 11261 * 11262 * @return true if the animation is played, false otherwise 11263 * 11264 * @see #scrollBy(int, int) 11265 * @see #scrollTo(int, int) 11266 * @see #isHorizontalScrollBarEnabled() 11267 * @see #isVerticalScrollBarEnabled() 11268 * @see #setHorizontalScrollBarEnabled(boolean) 11269 * @see #setVerticalScrollBarEnabled(boolean) 11270 */ 11271 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 11272 final ScrollabilityCache scrollCache = mScrollCache; 11273 11274 if (scrollCache == null || !scrollCache.fadeScrollBars) { 11275 return false; 11276 } 11277 11278 if (scrollCache.scrollBar == null) { 11279 scrollCache.scrollBar = new ScrollBarDrawable(); 11280 } 11281 11282 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 11283 11284 if (invalidate) { 11285 // Invalidate to show the scrollbars 11286 postInvalidateOnAnimation(); 11287 } 11288 11289 if (scrollCache.state == ScrollabilityCache.OFF) { 11290 // FIXME: this is copied from WindowManagerService. 11291 // We should get this value from the system when it 11292 // is possible to do so. 11293 final int KEY_REPEAT_FIRST_DELAY = 750; 11294 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 11295 } 11296 11297 // Tell mScrollCache when we should start fading. This may 11298 // extend the fade start time if one was already scheduled 11299 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 11300 scrollCache.fadeStartTime = fadeStartTime; 11301 scrollCache.state = ScrollabilityCache.ON; 11302 11303 // Schedule our fader to run, unscheduling any old ones first 11304 if (mAttachInfo != null) { 11305 mAttachInfo.mHandler.removeCallbacks(scrollCache); 11306 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 11307 } 11308 11309 return true; 11310 } 11311 11312 return false; 11313 } 11314 11315 /** 11316 * Do not invalidate views which are not visible and which are not running an animation. They 11317 * will not get drawn and they should not set dirty flags as if they will be drawn 11318 */ 11319 private boolean skipInvalidate() { 11320 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 11321 (!(mParent instanceof ViewGroup) || 11322 !((ViewGroup) mParent).isViewTransitioning(this)); 11323 } 11324 11325 /** 11326 * Mark the area defined by dirty as needing to be drawn. If the view is 11327 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 11328 * point in the future. 11329 * <p> 11330 * This must be called from a UI thread. To call from a non-UI thread, call 11331 * {@link #postInvalidate()}. 11332 * <p> 11333 * <b>WARNING:</b> In API 19 and below, this method may be destructive to 11334 * {@code dirty}. 11335 * 11336 * @param dirty the rectangle representing the bounds of the dirty region 11337 */ 11338 public void invalidate(Rect dirty) { 11339 final int scrollX = mScrollX; 11340 final int scrollY = mScrollY; 11341 invalidateInternal(dirty.left - scrollX, dirty.top - scrollY, 11342 dirty.right - scrollX, dirty.bottom - scrollY, true, false); 11343 } 11344 11345 /** 11346 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The 11347 * coordinates of the dirty rect are relative to the view. If the view is 11348 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 11349 * point in the future. 11350 * <p> 11351 * This must be called from a UI thread. To call from a non-UI thread, call 11352 * {@link #postInvalidate()}. 11353 * 11354 * @param l the left position of the dirty region 11355 * @param t the top position of the dirty region 11356 * @param r the right position of the dirty region 11357 * @param b the bottom position of the dirty region 11358 */ 11359 public void invalidate(int l, int t, int r, int b) { 11360 final int scrollX = mScrollX; 11361 final int scrollY = mScrollY; 11362 invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false); 11363 } 11364 11365 /** 11366 * Invalidate the whole view. If the view is visible, 11367 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 11368 * the future. 11369 * <p> 11370 * This must be called from a UI thread. To call from a non-UI thread, call 11371 * {@link #postInvalidate()}. 11372 */ 11373 public void invalidate() { 11374 invalidate(true); 11375 } 11376 11377 /** 11378 * This is where the invalidate() work actually happens. A full invalidate() 11379 * causes the drawing cache to be invalidated, but this function can be 11380 * called with invalidateCache set to false to skip that invalidation step 11381 * for cases that do not need it (for example, a component that remains at 11382 * the same dimensions with the same content). 11383 * 11384 * @param invalidateCache Whether the drawing cache for this view should be 11385 * invalidated as well. This is usually true for a full 11386 * invalidate, but may be set to false if the View's contents or 11387 * dimensions have not changed. 11388 */ 11389 void invalidate(boolean invalidateCache) { 11390 invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true); 11391 } 11392 11393 void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache, 11394 boolean fullInvalidate) { 11395 if (skipInvalidate()) { 11396 return; 11397 } 11398 11399 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) 11400 || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) 11401 || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED 11402 || (fullInvalidate && isOpaque() != mLastIsOpaque)) { 11403 if (fullInvalidate) { 11404 mLastIsOpaque = isOpaque(); 11405 mPrivateFlags &= ~PFLAG_DRAWN; 11406 } 11407 11408 mPrivateFlags |= PFLAG_DIRTY; 11409 11410 if (invalidateCache) { 11411 mPrivateFlags |= PFLAG_INVALIDATED; 11412 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 11413 } 11414 11415 // Propagate the damage rectangle to the parent view. 11416 final AttachInfo ai = mAttachInfo; 11417 final ViewParent p = mParent; 11418 if (p != null && ai != null && l < r && t < b) { 11419 final Rect damage = ai.mTmpInvalRect; 11420 damage.set(l, t, r, b); 11421 p.invalidateChild(this, damage); 11422 } 11423 11424 // Damage the entire projection receiver, if necessary. 11425 if (mBackground != null && mBackground.isProjected()) { 11426 final View receiver = getProjectionReceiver(); 11427 if (receiver != null) { 11428 receiver.damageInParent(); 11429 } 11430 } 11431 11432 // Damage the entire IsolatedZVolume recieving this view's shadow. 11433 if (isHardwareAccelerated() && getZ() != 0) { 11434 damageShadowReceiver(); 11435 } 11436 } 11437 } 11438 11439 /** 11440 * @return this view's projection receiver, or {@code null} if none exists 11441 */ 11442 private View getProjectionReceiver() { 11443 ViewParent p = getParent(); 11444 while (p != null && p instanceof View) { 11445 final View v = (View) p; 11446 if (v.isProjectionReceiver()) { 11447 return v; 11448 } 11449 p = p.getParent(); 11450 } 11451 11452 return null; 11453 } 11454 11455 /** 11456 * @return whether the view is a projection receiver 11457 */ 11458 private boolean isProjectionReceiver() { 11459 return mBackground != null; 11460 } 11461 11462 /** 11463 * Damage area of the screen that can be covered by this View's shadow. 11464 * 11465 * This method will guarantee that any changes to shadows cast by a View 11466 * are damaged on the screen for future redraw. 11467 */ 11468 private void damageShadowReceiver() { 11469 final AttachInfo ai = mAttachInfo; 11470 if (ai != null) { 11471 ViewParent p = getParent(); 11472 if (p != null && p instanceof ViewGroup) { 11473 final ViewGroup vg = (ViewGroup) p; 11474 vg.damageInParent(); 11475 } 11476 } 11477 } 11478 11479 /** 11480 * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to 11481 * set any flags or handle all of the cases handled by the default invalidation methods. 11482 * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate 11483 * dirty rect. This method calls into fast invalidation methods in ViewGroup that 11484 * walk up the hierarchy, transforming the dirty rect as necessary. 11485 * 11486 * The method also handles normal invalidation logic if display list properties are not 11487 * being used in this view. The invalidateParent and forceRedraw flags are used by that 11488 * backup approach, to handle these cases used in the various property-setting methods. 11489 * 11490 * @param invalidateParent Force a call to invalidateParentCaches() if display list properties 11491 * are not being used in this view 11492 * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display 11493 * list properties are not being used in this view 11494 */ 11495 void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) { 11496 if (!isHardwareAccelerated() 11497 || !mRenderNode.isValid() 11498 || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) { 11499 if (invalidateParent) { 11500 invalidateParentCaches(); 11501 } 11502 if (forceRedraw) { 11503 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 11504 } 11505 invalidate(false); 11506 } else { 11507 damageInParent(); 11508 } 11509 if (isHardwareAccelerated() && invalidateParent && getZ() != 0) { 11510 damageShadowReceiver(); 11511 } 11512 } 11513 11514 /** 11515 * Tells the parent view to damage this view's bounds. 11516 * 11517 * @hide 11518 */ 11519 protected void damageInParent() { 11520 final AttachInfo ai = mAttachInfo; 11521 final ViewParent p = mParent; 11522 if (p != null && ai != null) { 11523 final Rect r = ai.mTmpInvalRect; 11524 r.set(0, 0, mRight - mLeft, mBottom - mTop); 11525 if (mParent instanceof ViewGroup) { 11526 ((ViewGroup) mParent).damageChild(this, r); 11527 } else { 11528 mParent.invalidateChild(this, r); 11529 } 11530 } 11531 } 11532 11533 /** 11534 * Utility method to transform a given Rect by the current matrix of this view. 11535 */ 11536 void transformRect(final Rect rect) { 11537 if (!getMatrix().isIdentity()) { 11538 RectF boundingRect = mAttachInfo.mTmpTransformRect; 11539 boundingRect.set(rect); 11540 getMatrix().mapRect(boundingRect); 11541 rect.set((int) Math.floor(boundingRect.left), 11542 (int) Math.floor(boundingRect.top), 11543 (int) Math.ceil(boundingRect.right), 11544 (int) Math.ceil(boundingRect.bottom)); 11545 } 11546 } 11547 11548 /** 11549 * Used to indicate that the parent of this view should clear its caches. This functionality 11550 * is used to force the parent to rebuild its display list (when hardware-accelerated), 11551 * which is necessary when various parent-managed properties of the view change, such as 11552 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 11553 * clears the parent caches and does not causes an invalidate event. 11554 * 11555 * @hide 11556 */ 11557 protected void invalidateParentCaches() { 11558 if (mParent instanceof View) { 11559 ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED; 11560 } 11561 } 11562 11563 /** 11564 * Used to indicate that the parent of this view should be invalidated. This functionality 11565 * is used to force the parent to rebuild its display list (when hardware-accelerated), 11566 * which is necessary when various parent-managed properties of the view change, such as 11567 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 11568 * an invalidation event to the parent. 11569 * 11570 * @hide 11571 */ 11572 protected void invalidateParentIfNeeded() { 11573 if (isHardwareAccelerated() && mParent instanceof View) { 11574 ((View) mParent).invalidate(true); 11575 } 11576 } 11577 11578 /** 11579 * @hide 11580 */ 11581 protected void invalidateParentIfNeededAndWasQuickRejected() { 11582 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) { 11583 // View was rejected last time it was drawn by its parent; this may have changed 11584 invalidateParentIfNeeded(); 11585 } 11586 } 11587 11588 /** 11589 * Indicates whether this View is opaque. An opaque View guarantees that it will 11590 * draw all the pixels overlapping its bounds using a fully opaque color. 11591 * 11592 * Subclasses of View should override this method whenever possible to indicate 11593 * whether an instance is opaque. Opaque Views are treated in a special way by 11594 * the View hierarchy, possibly allowing it to perform optimizations during 11595 * invalidate/draw passes. 11596 * 11597 * @return True if this View is guaranteed to be fully opaque, false otherwise. 11598 */ 11599 @ViewDebug.ExportedProperty(category = "drawing") 11600 public boolean isOpaque() { 11601 return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK && 11602 getFinalAlpha() >= 1.0f; 11603 } 11604 11605 /** 11606 * @hide 11607 */ 11608 protected void computeOpaqueFlags() { 11609 // Opaque if: 11610 // - Has a background 11611 // - Background is opaque 11612 // - Doesn't have scrollbars or scrollbars overlay 11613 11614 if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) { 11615 mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND; 11616 } else { 11617 mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND; 11618 } 11619 11620 final int flags = mViewFlags; 11621 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 11622 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY || 11623 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) { 11624 mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS; 11625 } else { 11626 mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS; 11627 } 11628 } 11629 11630 /** 11631 * @hide 11632 */ 11633 protected boolean hasOpaqueScrollbars() { 11634 return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS; 11635 } 11636 11637 /** 11638 * @return A handler associated with the thread running the View. This 11639 * handler can be used to pump events in the UI events queue. 11640 */ 11641 public Handler getHandler() { 11642 final AttachInfo attachInfo = mAttachInfo; 11643 if (attachInfo != null) { 11644 return attachInfo.mHandler; 11645 } 11646 return null; 11647 } 11648 11649 /** 11650 * Gets the view root associated with the View. 11651 * @return The view root, or null if none. 11652 * @hide 11653 */ 11654 public ViewRootImpl getViewRootImpl() { 11655 if (mAttachInfo != null) { 11656 return mAttachInfo.mViewRootImpl; 11657 } 11658 return null; 11659 } 11660 11661 /** 11662 * @hide 11663 */ 11664 public HardwareRenderer getHardwareRenderer() { 11665 return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null; 11666 } 11667 11668 /** 11669 * <p>Causes the Runnable to be added to the message queue. 11670 * The runnable will be run on the user interface thread.</p> 11671 * 11672 * @param action The Runnable that will be executed. 11673 * 11674 * @return Returns true if the Runnable was successfully placed in to the 11675 * message queue. Returns false on failure, usually because the 11676 * looper processing the message queue is exiting. 11677 * 11678 * @see #postDelayed 11679 * @see #removeCallbacks 11680 */ 11681 public boolean post(Runnable action) { 11682 final AttachInfo attachInfo = mAttachInfo; 11683 if (attachInfo != null) { 11684 return attachInfo.mHandler.post(action); 11685 } 11686 // Assume that post will succeed later 11687 ViewRootImpl.getRunQueue().post(action); 11688 return true; 11689 } 11690 11691 /** 11692 * <p>Causes the Runnable to be added to the message queue, to be run 11693 * after the specified amount of time elapses. 11694 * The runnable will be run on the user interface thread.</p> 11695 * 11696 * @param action The Runnable that will be executed. 11697 * @param delayMillis The delay (in milliseconds) until the Runnable 11698 * will be executed. 11699 * 11700 * @return true if the Runnable was successfully placed in to the 11701 * message queue. Returns false on failure, usually because the 11702 * looper processing the message queue is exiting. Note that a 11703 * result of true does not mean the Runnable will be processed -- 11704 * if the looper is quit before the delivery time of the message 11705 * occurs then the message will be dropped. 11706 * 11707 * @see #post 11708 * @see #removeCallbacks 11709 */ 11710 public boolean postDelayed(Runnable action, long delayMillis) { 11711 final AttachInfo attachInfo = mAttachInfo; 11712 if (attachInfo != null) { 11713 return attachInfo.mHandler.postDelayed(action, delayMillis); 11714 } 11715 // Assume that post will succeed later 11716 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 11717 return true; 11718 } 11719 11720 /** 11721 * <p>Causes the Runnable to execute on the next animation time step. 11722 * The runnable will be run on the user interface thread.</p> 11723 * 11724 * @param action The Runnable that will be executed. 11725 * 11726 * @see #postOnAnimationDelayed 11727 * @see #removeCallbacks 11728 */ 11729 public void postOnAnimation(Runnable action) { 11730 final AttachInfo attachInfo = mAttachInfo; 11731 if (attachInfo != null) { 11732 attachInfo.mViewRootImpl.mChoreographer.postCallback( 11733 Choreographer.CALLBACK_ANIMATION, action, null); 11734 } else { 11735 // Assume that post will succeed later 11736 ViewRootImpl.getRunQueue().post(action); 11737 } 11738 } 11739 11740 /** 11741 * <p>Causes the Runnable to execute on the next animation time step, 11742 * after the specified amount of time elapses. 11743 * The runnable will be run on the user interface thread.</p> 11744 * 11745 * @param action The Runnable that will be executed. 11746 * @param delayMillis The delay (in milliseconds) until the Runnable 11747 * will be executed. 11748 * 11749 * @see #postOnAnimation 11750 * @see #removeCallbacks 11751 */ 11752 public void postOnAnimationDelayed(Runnable action, long delayMillis) { 11753 final AttachInfo attachInfo = mAttachInfo; 11754 if (attachInfo != null) { 11755 attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 11756 Choreographer.CALLBACK_ANIMATION, action, null, delayMillis); 11757 } else { 11758 // Assume that post will succeed later 11759 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 11760 } 11761 } 11762 11763 /** 11764 * <p>Removes the specified Runnable from the message queue.</p> 11765 * 11766 * @param action The Runnable to remove from the message handling queue 11767 * 11768 * @return true if this view could ask the Handler to remove the Runnable, 11769 * false otherwise. When the returned value is true, the Runnable 11770 * may or may not have been actually removed from the message queue 11771 * (for instance, if the Runnable was not in the queue already.) 11772 * 11773 * @see #post 11774 * @see #postDelayed 11775 * @see #postOnAnimation 11776 * @see #postOnAnimationDelayed 11777 */ 11778 public boolean removeCallbacks(Runnable action) { 11779 if (action != null) { 11780 final AttachInfo attachInfo = mAttachInfo; 11781 if (attachInfo != null) { 11782 attachInfo.mHandler.removeCallbacks(action); 11783 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 11784 Choreographer.CALLBACK_ANIMATION, action, null); 11785 } 11786 // Assume that post will succeed later 11787 ViewRootImpl.getRunQueue().removeCallbacks(action); 11788 } 11789 return true; 11790 } 11791 11792 /** 11793 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 11794 * Use this to invalidate the View from a non-UI thread.</p> 11795 * 11796 * <p>This method can be invoked from outside of the UI thread 11797 * only when this View is attached to a window.</p> 11798 * 11799 * @see #invalidate() 11800 * @see #postInvalidateDelayed(long) 11801 */ 11802 public void postInvalidate() { 11803 postInvalidateDelayed(0); 11804 } 11805 11806 /** 11807 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 11808 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 11809 * 11810 * <p>This method can be invoked from outside of the UI thread 11811 * only when this View is attached to a window.</p> 11812 * 11813 * @param left The left coordinate of the rectangle to invalidate. 11814 * @param top The top coordinate of the rectangle to invalidate. 11815 * @param right The right coordinate of the rectangle to invalidate. 11816 * @param bottom The bottom coordinate of the rectangle to invalidate. 11817 * 11818 * @see #invalidate(int, int, int, int) 11819 * @see #invalidate(Rect) 11820 * @see #postInvalidateDelayed(long, int, int, int, int) 11821 */ 11822 public void postInvalidate(int left, int top, int right, int bottom) { 11823 postInvalidateDelayed(0, left, top, right, bottom); 11824 } 11825 11826 /** 11827 * <p>Cause an invalidate to happen on a subsequent cycle through the event 11828 * loop. Waits for the specified amount of time.</p> 11829 * 11830 * <p>This method can be invoked from outside of the UI thread 11831 * only when this View is attached to a window.</p> 11832 * 11833 * @param delayMilliseconds the duration in milliseconds to delay the 11834 * invalidation by 11835 * 11836 * @see #invalidate() 11837 * @see #postInvalidate() 11838 */ 11839 public void postInvalidateDelayed(long delayMilliseconds) { 11840 // We try only with the AttachInfo because there's no point in invalidating 11841 // if we are not attached to our window 11842 final AttachInfo attachInfo = mAttachInfo; 11843 if (attachInfo != null) { 11844 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); 11845 } 11846 } 11847 11848 /** 11849 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 11850 * through the event loop. Waits for the specified amount of time.</p> 11851 * 11852 * <p>This method can be invoked from outside of the UI thread 11853 * only when this View is attached to a window.</p> 11854 * 11855 * @param delayMilliseconds the duration in milliseconds to delay the 11856 * invalidation by 11857 * @param left The left coordinate of the rectangle to invalidate. 11858 * @param top The top coordinate of the rectangle to invalidate. 11859 * @param right The right coordinate of the rectangle to invalidate. 11860 * @param bottom The bottom coordinate of the rectangle to invalidate. 11861 * 11862 * @see #invalidate(int, int, int, int) 11863 * @see #invalidate(Rect) 11864 * @see #postInvalidate(int, int, int, int) 11865 */ 11866 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 11867 int right, int bottom) { 11868 11869 // We try only with the AttachInfo because there's no point in invalidating 11870 // if we are not attached to our window 11871 final AttachInfo attachInfo = mAttachInfo; 11872 if (attachInfo != null) { 11873 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 11874 info.target = this; 11875 info.left = left; 11876 info.top = top; 11877 info.right = right; 11878 info.bottom = bottom; 11879 11880 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); 11881 } 11882 } 11883 11884 /** 11885 * <p>Cause an invalidate to happen on the next animation time step, typically the 11886 * next display frame.</p> 11887 * 11888 * <p>This method can be invoked from outside of the UI thread 11889 * only when this View is attached to a window.</p> 11890 * 11891 * @see #invalidate() 11892 */ 11893 public void postInvalidateOnAnimation() { 11894 // We try only with the AttachInfo because there's no point in invalidating 11895 // if we are not attached to our window 11896 final AttachInfo attachInfo = mAttachInfo; 11897 if (attachInfo != null) { 11898 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); 11899 } 11900 } 11901 11902 /** 11903 * <p>Cause an invalidate of the specified area to happen on the next animation 11904 * time step, typically the next display frame.</p> 11905 * 11906 * <p>This method can be invoked from outside of the UI thread 11907 * only when this View is attached to a window.</p> 11908 * 11909 * @param left The left coordinate of the rectangle to invalidate. 11910 * @param top The top coordinate of the rectangle to invalidate. 11911 * @param right The right coordinate of the rectangle to invalidate. 11912 * @param bottom The bottom coordinate of the rectangle to invalidate. 11913 * 11914 * @see #invalidate(int, int, int, int) 11915 * @see #invalidate(Rect) 11916 */ 11917 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { 11918 // We try only with the AttachInfo because there's no point in invalidating 11919 // if we are not attached to our window 11920 final AttachInfo attachInfo = mAttachInfo; 11921 if (attachInfo != null) { 11922 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 11923 info.target = this; 11924 info.left = left; 11925 info.top = top; 11926 info.right = right; 11927 info.bottom = bottom; 11928 11929 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); 11930 } 11931 } 11932 11933 /** 11934 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 11935 * This event is sent at most once every 11936 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 11937 */ 11938 private void postSendViewScrolledAccessibilityEventCallback() { 11939 if (mSendViewScrolledAccessibilityEvent == null) { 11940 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 11941 } 11942 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 11943 mSendViewScrolledAccessibilityEvent.mIsPending = true; 11944 postDelayed(mSendViewScrolledAccessibilityEvent, 11945 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 11946 } 11947 } 11948 11949 /** 11950 * Called by a parent to request that a child update its values for mScrollX 11951 * and mScrollY if necessary. This will typically be done if the child is 11952 * animating a scroll using a {@link android.widget.Scroller Scroller} 11953 * object. 11954 */ 11955 public void computeScroll() { 11956 } 11957 11958 /** 11959 * <p>Indicate whether the horizontal edges are faded when the view is 11960 * scrolled horizontally.</p> 11961 * 11962 * @return true if the horizontal edges should are faded on scroll, false 11963 * otherwise 11964 * 11965 * @see #setHorizontalFadingEdgeEnabled(boolean) 11966 * 11967 * @attr ref android.R.styleable#View_requiresFadingEdge 11968 */ 11969 public boolean isHorizontalFadingEdgeEnabled() { 11970 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 11971 } 11972 11973 /** 11974 * <p>Define whether the horizontal edges should be faded when this view 11975 * is scrolled horizontally.</p> 11976 * 11977 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 11978 * be faded when the view is scrolled 11979 * horizontally 11980 * 11981 * @see #isHorizontalFadingEdgeEnabled() 11982 * 11983 * @attr ref android.R.styleable#View_requiresFadingEdge 11984 */ 11985 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 11986 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 11987 if (horizontalFadingEdgeEnabled) { 11988 initScrollCache(); 11989 } 11990 11991 mViewFlags ^= FADING_EDGE_HORIZONTAL; 11992 } 11993 } 11994 11995 /** 11996 * <p>Indicate whether the vertical edges are faded when the view is 11997 * scrolled horizontally.</p> 11998 * 11999 * @return true if the vertical edges should are faded on scroll, false 12000 * otherwise 12001 * 12002 * @see #setVerticalFadingEdgeEnabled(boolean) 12003 * 12004 * @attr ref android.R.styleable#View_requiresFadingEdge 12005 */ 12006 public boolean isVerticalFadingEdgeEnabled() { 12007 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 12008 } 12009 12010 /** 12011 * <p>Define whether the vertical edges should be faded when this view 12012 * is scrolled vertically.</p> 12013 * 12014 * @param verticalFadingEdgeEnabled true if the vertical edges should 12015 * be faded when the view is scrolled 12016 * vertically 12017 * 12018 * @see #isVerticalFadingEdgeEnabled() 12019 * 12020 * @attr ref android.R.styleable#View_requiresFadingEdge 12021 */ 12022 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 12023 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 12024 if (verticalFadingEdgeEnabled) { 12025 initScrollCache(); 12026 } 12027 12028 mViewFlags ^= FADING_EDGE_VERTICAL; 12029 } 12030 } 12031 12032 /** 12033 * Returns the strength, or intensity, of the top faded edge. The strength is 12034 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12035 * returns 0.0 or 1.0 but no value in between. 12036 * 12037 * Subclasses should override this method to provide a smoother fade transition 12038 * when scrolling occurs. 12039 * 12040 * @return the intensity of the top fade as a float between 0.0f and 1.0f 12041 */ 12042 protected float getTopFadingEdgeStrength() { 12043 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 12044 } 12045 12046 /** 12047 * Returns the strength, or intensity, of the bottom faded edge. The strength is 12048 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12049 * returns 0.0 or 1.0 but no value in between. 12050 * 12051 * Subclasses should override this method to provide a smoother fade transition 12052 * when scrolling occurs. 12053 * 12054 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 12055 */ 12056 protected float getBottomFadingEdgeStrength() { 12057 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 12058 computeVerticalScrollRange() ? 1.0f : 0.0f; 12059 } 12060 12061 /** 12062 * Returns the strength, or intensity, of the left faded edge. The strength is 12063 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12064 * returns 0.0 or 1.0 but no value in between. 12065 * 12066 * Subclasses should override this method to provide a smoother fade transition 12067 * when scrolling occurs. 12068 * 12069 * @return the intensity of the left fade as a float between 0.0f and 1.0f 12070 */ 12071 protected float getLeftFadingEdgeStrength() { 12072 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 12073 } 12074 12075 /** 12076 * Returns the strength, or intensity, of the right faded edge. The strength is 12077 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12078 * returns 0.0 or 1.0 but no value in between. 12079 * 12080 * Subclasses should override this method to provide a smoother fade transition 12081 * when scrolling occurs. 12082 * 12083 * @return the intensity of the right fade as a float between 0.0f and 1.0f 12084 */ 12085 protected float getRightFadingEdgeStrength() { 12086 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 12087 computeHorizontalScrollRange() ? 1.0f : 0.0f; 12088 } 12089 12090 /** 12091 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 12092 * scrollbar is not drawn by default.</p> 12093 * 12094 * @return true if the horizontal scrollbar should be painted, false 12095 * otherwise 12096 * 12097 * @see #setHorizontalScrollBarEnabled(boolean) 12098 */ 12099 public boolean isHorizontalScrollBarEnabled() { 12100 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 12101 } 12102 12103 /** 12104 * <p>Define whether the horizontal scrollbar should be drawn or not. The 12105 * scrollbar is not drawn by default.</p> 12106 * 12107 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 12108 * be painted 12109 * 12110 * @see #isHorizontalScrollBarEnabled() 12111 */ 12112 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 12113 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 12114 mViewFlags ^= SCROLLBARS_HORIZONTAL; 12115 computeOpaqueFlags(); 12116 resolvePadding(); 12117 } 12118 } 12119 12120 /** 12121 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 12122 * scrollbar is not drawn by default.</p> 12123 * 12124 * @return true if the vertical scrollbar should be painted, false 12125 * otherwise 12126 * 12127 * @see #setVerticalScrollBarEnabled(boolean) 12128 */ 12129 public boolean isVerticalScrollBarEnabled() { 12130 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 12131 } 12132 12133 /** 12134 * <p>Define whether the vertical scrollbar should be drawn or not. The 12135 * scrollbar is not drawn by default.</p> 12136 * 12137 * @param verticalScrollBarEnabled true if the vertical scrollbar should 12138 * be painted 12139 * 12140 * @see #isVerticalScrollBarEnabled() 12141 */ 12142 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 12143 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 12144 mViewFlags ^= SCROLLBARS_VERTICAL; 12145 computeOpaqueFlags(); 12146 resolvePadding(); 12147 } 12148 } 12149 12150 /** 12151 * @hide 12152 */ 12153 protected void recomputePadding() { 12154 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 12155 } 12156 12157 /** 12158 * Define whether scrollbars will fade when the view is not scrolling. 12159 * 12160 * @param fadeScrollbars wheter to enable fading 12161 * 12162 * @attr ref android.R.styleable#View_fadeScrollbars 12163 */ 12164 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 12165 initScrollCache(); 12166 final ScrollabilityCache scrollabilityCache = mScrollCache; 12167 scrollabilityCache.fadeScrollBars = fadeScrollbars; 12168 if (fadeScrollbars) { 12169 scrollabilityCache.state = ScrollabilityCache.OFF; 12170 } else { 12171 scrollabilityCache.state = ScrollabilityCache.ON; 12172 } 12173 } 12174 12175 /** 12176 * 12177 * Returns true if scrollbars will fade when this view is not scrolling 12178 * 12179 * @return true if scrollbar fading is enabled 12180 * 12181 * @attr ref android.R.styleable#View_fadeScrollbars 12182 */ 12183 public boolean isScrollbarFadingEnabled() { 12184 return mScrollCache != null && mScrollCache.fadeScrollBars; 12185 } 12186 12187 /** 12188 * 12189 * Returns the delay before scrollbars fade. 12190 * 12191 * @return the delay before scrollbars fade 12192 * 12193 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 12194 */ 12195 public int getScrollBarDefaultDelayBeforeFade() { 12196 return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() : 12197 mScrollCache.scrollBarDefaultDelayBeforeFade; 12198 } 12199 12200 /** 12201 * Define the delay before scrollbars fade. 12202 * 12203 * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade 12204 * 12205 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 12206 */ 12207 public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) { 12208 getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade; 12209 } 12210 12211 /** 12212 * 12213 * Returns the scrollbar fade duration. 12214 * 12215 * @return the scrollbar fade duration 12216 * 12217 * @attr ref android.R.styleable#View_scrollbarFadeDuration 12218 */ 12219 public int getScrollBarFadeDuration() { 12220 return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() : 12221 mScrollCache.scrollBarFadeDuration; 12222 } 12223 12224 /** 12225 * Define the scrollbar fade duration. 12226 * 12227 * @param scrollBarFadeDuration - the scrollbar fade duration 12228 * 12229 * @attr ref android.R.styleable#View_scrollbarFadeDuration 12230 */ 12231 public void setScrollBarFadeDuration(int scrollBarFadeDuration) { 12232 getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration; 12233 } 12234 12235 /** 12236 * 12237 * Returns the scrollbar size. 12238 * 12239 * @return the scrollbar size 12240 * 12241 * @attr ref android.R.styleable#View_scrollbarSize 12242 */ 12243 public int getScrollBarSize() { 12244 return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() : 12245 mScrollCache.scrollBarSize; 12246 } 12247 12248 /** 12249 * Define the scrollbar size. 12250 * 12251 * @param scrollBarSize - the scrollbar size 12252 * 12253 * @attr ref android.R.styleable#View_scrollbarSize 12254 */ 12255 public void setScrollBarSize(int scrollBarSize) { 12256 getScrollCache().scrollBarSize = scrollBarSize; 12257 } 12258 12259 /** 12260 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 12261 * inset. When inset, they add to the padding of the view. And the scrollbars 12262 * can be drawn inside the padding area or on the edge of the view. For example, 12263 * if a view has a background drawable and you want to draw the scrollbars 12264 * inside the padding specified by the drawable, you can use 12265 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 12266 * appear at the edge of the view, ignoring the padding, then you can use 12267 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 12268 * @param style the style of the scrollbars. Should be one of 12269 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 12270 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 12271 * @see #SCROLLBARS_INSIDE_OVERLAY 12272 * @see #SCROLLBARS_INSIDE_INSET 12273 * @see #SCROLLBARS_OUTSIDE_OVERLAY 12274 * @see #SCROLLBARS_OUTSIDE_INSET 12275 * 12276 * @attr ref android.R.styleable#View_scrollbarStyle 12277 */ 12278 public void setScrollBarStyle(@ScrollBarStyle int style) { 12279 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 12280 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 12281 computeOpaqueFlags(); 12282 resolvePadding(); 12283 } 12284 } 12285 12286 /** 12287 * <p>Returns the current scrollbar style.</p> 12288 * @return the current scrollbar style 12289 * @see #SCROLLBARS_INSIDE_OVERLAY 12290 * @see #SCROLLBARS_INSIDE_INSET 12291 * @see #SCROLLBARS_OUTSIDE_OVERLAY 12292 * @see #SCROLLBARS_OUTSIDE_INSET 12293 * 12294 * @attr ref android.R.styleable#View_scrollbarStyle 12295 */ 12296 @ViewDebug.ExportedProperty(mapping = { 12297 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 12298 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 12299 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 12300 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 12301 }) 12302 @ScrollBarStyle 12303 public int getScrollBarStyle() { 12304 return mViewFlags & SCROLLBARS_STYLE_MASK; 12305 } 12306 12307 /** 12308 * <p>Compute the horizontal range that the horizontal scrollbar 12309 * represents.</p> 12310 * 12311 * <p>The range is expressed in arbitrary units that must be the same as the 12312 * units used by {@link #computeHorizontalScrollExtent()} and 12313 * {@link #computeHorizontalScrollOffset()}.</p> 12314 * 12315 * <p>The default range is the drawing width of this view.</p> 12316 * 12317 * @return the total horizontal range represented by the horizontal 12318 * scrollbar 12319 * 12320 * @see #computeHorizontalScrollExtent() 12321 * @see #computeHorizontalScrollOffset() 12322 * @see android.widget.ScrollBarDrawable 12323 */ 12324 protected int computeHorizontalScrollRange() { 12325 return getWidth(); 12326 } 12327 12328 /** 12329 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 12330 * within the horizontal range. This value is used to compute the position 12331 * of the thumb within the scrollbar's track.</p> 12332 * 12333 * <p>The range is expressed in arbitrary units that must be the same as the 12334 * units used by {@link #computeHorizontalScrollRange()} and 12335 * {@link #computeHorizontalScrollExtent()}.</p> 12336 * 12337 * <p>The default offset is the scroll offset of this view.</p> 12338 * 12339 * @return the horizontal offset of the scrollbar's thumb 12340 * 12341 * @see #computeHorizontalScrollRange() 12342 * @see #computeHorizontalScrollExtent() 12343 * @see android.widget.ScrollBarDrawable 12344 */ 12345 protected int computeHorizontalScrollOffset() { 12346 return mScrollX; 12347 } 12348 12349 /** 12350 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 12351 * within the horizontal range. This value is used to compute the length 12352 * of the thumb within the scrollbar's track.</p> 12353 * 12354 * <p>The range is expressed in arbitrary units that must be the same as the 12355 * units used by {@link #computeHorizontalScrollRange()} and 12356 * {@link #computeHorizontalScrollOffset()}.</p> 12357 * 12358 * <p>The default extent is the drawing width of this view.</p> 12359 * 12360 * @return the horizontal extent of the scrollbar's thumb 12361 * 12362 * @see #computeHorizontalScrollRange() 12363 * @see #computeHorizontalScrollOffset() 12364 * @see android.widget.ScrollBarDrawable 12365 */ 12366 protected int computeHorizontalScrollExtent() { 12367 return getWidth(); 12368 } 12369 12370 /** 12371 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 12372 * 12373 * <p>The range is expressed in arbitrary units that must be the same as the 12374 * units used by {@link #computeVerticalScrollExtent()} and 12375 * {@link #computeVerticalScrollOffset()}.</p> 12376 * 12377 * @return the total vertical range represented by the vertical scrollbar 12378 * 12379 * <p>The default range is the drawing height of this view.</p> 12380 * 12381 * @see #computeVerticalScrollExtent() 12382 * @see #computeVerticalScrollOffset() 12383 * @see android.widget.ScrollBarDrawable 12384 */ 12385 protected int computeVerticalScrollRange() { 12386 return getHeight(); 12387 } 12388 12389 /** 12390 * <p>Compute the vertical offset of the vertical scrollbar's thumb 12391 * within the horizontal range. This value is used to compute the position 12392 * of the thumb within the scrollbar's track.</p> 12393 * 12394 * <p>The range is expressed in arbitrary units that must be the same as the 12395 * units used by {@link #computeVerticalScrollRange()} and 12396 * {@link #computeVerticalScrollExtent()}.</p> 12397 * 12398 * <p>The default offset is the scroll offset of this view.</p> 12399 * 12400 * @return the vertical offset of the scrollbar's thumb 12401 * 12402 * @see #computeVerticalScrollRange() 12403 * @see #computeVerticalScrollExtent() 12404 * @see android.widget.ScrollBarDrawable 12405 */ 12406 protected int computeVerticalScrollOffset() { 12407 return mScrollY; 12408 } 12409 12410 /** 12411 * <p>Compute the vertical extent of the vertical scrollbar's thumb 12412 * within the vertical range. This value is used to compute the length 12413 * of the thumb within the scrollbar's track.</p> 12414 * 12415 * <p>The range is expressed in arbitrary units that must be the same as the 12416 * units used by {@link #computeVerticalScrollRange()} and 12417 * {@link #computeVerticalScrollOffset()}.</p> 12418 * 12419 * <p>The default extent is the drawing height of this view.</p> 12420 * 12421 * @return the vertical extent of the scrollbar's thumb 12422 * 12423 * @see #computeVerticalScrollRange() 12424 * @see #computeVerticalScrollOffset() 12425 * @see android.widget.ScrollBarDrawable 12426 */ 12427 protected int computeVerticalScrollExtent() { 12428 return getHeight(); 12429 } 12430 12431 /** 12432 * Check if this view can be scrolled horizontally in a certain direction. 12433 * 12434 * @param direction Negative to check scrolling left, positive to check scrolling right. 12435 * @return true if this view can be scrolled in the specified direction, false otherwise. 12436 */ 12437 public boolean canScrollHorizontally(int direction) { 12438 final int offset = computeHorizontalScrollOffset(); 12439 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 12440 if (range == 0) return false; 12441 if (direction < 0) { 12442 return offset > 0; 12443 } else { 12444 return offset < range - 1; 12445 } 12446 } 12447 12448 /** 12449 * Check if this view can be scrolled vertically in a certain direction. 12450 * 12451 * @param direction Negative to check scrolling up, positive to check scrolling down. 12452 * @return true if this view can be scrolled in the specified direction, false otherwise. 12453 */ 12454 public boolean canScrollVertically(int direction) { 12455 final int offset = computeVerticalScrollOffset(); 12456 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 12457 if (range == 0) return false; 12458 if (direction < 0) { 12459 return offset > 0; 12460 } else { 12461 return offset < range - 1; 12462 } 12463 } 12464 12465 /** 12466 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 12467 * scrollbars are painted only if they have been awakened first.</p> 12468 * 12469 * @param canvas the canvas on which to draw the scrollbars 12470 * 12471 * @see #awakenScrollBars(int) 12472 */ 12473 protected final void onDrawScrollBars(Canvas canvas) { 12474 // scrollbars are drawn only when the animation is running 12475 final ScrollabilityCache cache = mScrollCache; 12476 if (cache != null) { 12477 12478 int state = cache.state; 12479 12480 if (state == ScrollabilityCache.OFF) { 12481 return; 12482 } 12483 12484 boolean invalidate = false; 12485 12486 if (state == ScrollabilityCache.FADING) { 12487 // We're fading -- get our fade interpolation 12488 if (cache.interpolatorValues == null) { 12489 cache.interpolatorValues = new float[1]; 12490 } 12491 12492 float[] values = cache.interpolatorValues; 12493 12494 // Stops the animation if we're done 12495 if (cache.scrollBarInterpolator.timeToValues(values) == 12496 Interpolator.Result.FREEZE_END) { 12497 cache.state = ScrollabilityCache.OFF; 12498 } else { 12499 cache.scrollBar.setAlpha(Math.round(values[0])); 12500 } 12501 12502 // This will make the scroll bars inval themselves after 12503 // drawing. We only want this when we're fading so that 12504 // we prevent excessive redraws 12505 invalidate = true; 12506 } else { 12507 // We're just on -- but we may have been fading before so 12508 // reset alpha 12509 cache.scrollBar.setAlpha(255); 12510 } 12511 12512 12513 final int viewFlags = mViewFlags; 12514 12515 final boolean drawHorizontalScrollBar = 12516 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 12517 final boolean drawVerticalScrollBar = 12518 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 12519 && !isVerticalScrollBarHidden(); 12520 12521 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 12522 final int width = mRight - mLeft; 12523 final int height = mBottom - mTop; 12524 12525 final ScrollBarDrawable scrollBar = cache.scrollBar; 12526 12527 final int scrollX = mScrollX; 12528 final int scrollY = mScrollY; 12529 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 12530 12531 int left; 12532 int top; 12533 int right; 12534 int bottom; 12535 12536 if (drawHorizontalScrollBar) { 12537 int size = scrollBar.getSize(false); 12538 if (size <= 0) { 12539 size = cache.scrollBarSize; 12540 } 12541 12542 scrollBar.setParameters(computeHorizontalScrollRange(), 12543 computeHorizontalScrollOffset(), 12544 computeHorizontalScrollExtent(), false); 12545 final int verticalScrollBarGap = drawVerticalScrollBar ? 12546 getVerticalScrollbarWidth() : 0; 12547 top = scrollY + height - size - (mUserPaddingBottom & inside); 12548 left = scrollX + (mPaddingLeft & inside); 12549 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 12550 bottom = top + size; 12551 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 12552 if (invalidate) { 12553 invalidate(left, top, right, bottom); 12554 } 12555 } 12556 12557 if (drawVerticalScrollBar) { 12558 int size = scrollBar.getSize(true); 12559 if (size <= 0) { 12560 size = cache.scrollBarSize; 12561 } 12562 12563 scrollBar.setParameters(computeVerticalScrollRange(), 12564 computeVerticalScrollOffset(), 12565 computeVerticalScrollExtent(), true); 12566 int verticalScrollbarPosition = mVerticalScrollbarPosition; 12567 if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) { 12568 verticalScrollbarPosition = isLayoutRtl() ? 12569 SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT; 12570 } 12571 switch (verticalScrollbarPosition) { 12572 default: 12573 case SCROLLBAR_POSITION_RIGHT: 12574 left = scrollX + width - size - (mUserPaddingRight & inside); 12575 break; 12576 case SCROLLBAR_POSITION_LEFT: 12577 left = scrollX + (mUserPaddingLeft & inside); 12578 break; 12579 } 12580 top = scrollY + (mPaddingTop & inside); 12581 right = left + size; 12582 bottom = scrollY + height - (mUserPaddingBottom & inside); 12583 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 12584 if (invalidate) { 12585 invalidate(left, top, right, bottom); 12586 } 12587 } 12588 } 12589 } 12590 } 12591 12592 /** 12593 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 12594 * FastScroller is visible. 12595 * @return whether to temporarily hide the vertical scrollbar 12596 * @hide 12597 */ 12598 protected boolean isVerticalScrollBarHidden() { 12599 return false; 12600 } 12601 12602 /** 12603 * <p>Draw the horizontal scrollbar if 12604 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 12605 * 12606 * @param canvas the canvas on which to draw the scrollbar 12607 * @param scrollBar the scrollbar's drawable 12608 * 12609 * @see #isHorizontalScrollBarEnabled() 12610 * @see #computeHorizontalScrollRange() 12611 * @see #computeHorizontalScrollExtent() 12612 * @see #computeHorizontalScrollOffset() 12613 * @see android.widget.ScrollBarDrawable 12614 * @hide 12615 */ 12616 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 12617 int l, int t, int r, int b) { 12618 scrollBar.setBounds(l, t, r, b); 12619 scrollBar.draw(canvas); 12620 } 12621 12622 /** 12623 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 12624 * returns true.</p> 12625 * 12626 * @param canvas the canvas on which to draw the scrollbar 12627 * @param scrollBar the scrollbar's drawable 12628 * 12629 * @see #isVerticalScrollBarEnabled() 12630 * @see #computeVerticalScrollRange() 12631 * @see #computeVerticalScrollExtent() 12632 * @see #computeVerticalScrollOffset() 12633 * @see android.widget.ScrollBarDrawable 12634 * @hide 12635 */ 12636 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 12637 int l, int t, int r, int b) { 12638 scrollBar.setBounds(l, t, r, b); 12639 scrollBar.draw(canvas); 12640 } 12641 12642 /** 12643 * Implement this to do your drawing. 12644 * 12645 * @param canvas the canvas on which the background will be drawn 12646 */ 12647 protected void onDraw(Canvas canvas) { 12648 } 12649 12650 /* 12651 * Caller is responsible for calling requestLayout if necessary. 12652 * (This allows addViewInLayout to not request a new layout.) 12653 */ 12654 void assignParent(ViewParent parent) { 12655 if (mParent == null) { 12656 mParent = parent; 12657 } else if (parent == null) { 12658 mParent = null; 12659 } else { 12660 throw new RuntimeException("view " + this + " being added, but" 12661 + " it already has a parent"); 12662 } 12663 } 12664 12665 /** 12666 * This is called when the view is attached to a window. At this point it 12667 * has a Surface and will start drawing. Note that this function is 12668 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 12669 * however it may be called any time before the first onDraw -- including 12670 * before or after {@link #onMeasure(int, int)}. 12671 * 12672 * @see #onDetachedFromWindow() 12673 */ 12674 protected void onAttachedToWindow() { 12675 if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 12676 mParent.requestTransparentRegion(this); 12677 } 12678 12679 if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { 12680 initialAwakenScrollBars(); 12681 mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 12682 } 12683 12684 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 12685 12686 jumpDrawablesToCurrentState(); 12687 12688 resetSubtreeAccessibilityStateChanged(); 12689 12690 invalidateOutline(); 12691 12692 if (isFocused()) { 12693 InputMethodManager imm = InputMethodManager.peekInstance(); 12694 imm.focusIn(this); 12695 } 12696 } 12697 12698 /** 12699 * Resolve all RTL related properties. 12700 * 12701 * @return true if resolution of RTL properties has been done 12702 * 12703 * @hide 12704 */ 12705 public boolean resolveRtlPropertiesIfNeeded() { 12706 if (!needRtlPropertiesResolution()) return false; 12707 12708 // Order is important here: LayoutDirection MUST be resolved first 12709 if (!isLayoutDirectionResolved()) { 12710 resolveLayoutDirection(); 12711 resolveLayoutParams(); 12712 } 12713 // ... then we can resolve the others properties depending on the resolved LayoutDirection. 12714 if (!isTextDirectionResolved()) { 12715 resolveTextDirection(); 12716 } 12717 if (!isTextAlignmentResolved()) { 12718 resolveTextAlignment(); 12719 } 12720 // Should resolve Drawables before Padding because we need the layout direction of the 12721 // Drawable to correctly resolve Padding. 12722 if (!isDrawablesResolved()) { 12723 resolveDrawables(); 12724 } 12725 if (!isPaddingResolved()) { 12726 resolvePadding(); 12727 } 12728 onRtlPropertiesChanged(getLayoutDirection()); 12729 return true; 12730 } 12731 12732 /** 12733 * Reset resolution of all RTL related properties. 12734 * 12735 * @hide 12736 */ 12737 public void resetRtlProperties() { 12738 resetResolvedLayoutDirection(); 12739 resetResolvedTextDirection(); 12740 resetResolvedTextAlignment(); 12741 resetResolvedPadding(); 12742 resetResolvedDrawables(); 12743 } 12744 12745 /** 12746 * @see #onScreenStateChanged(int) 12747 */ 12748 void dispatchScreenStateChanged(int screenState) { 12749 onScreenStateChanged(screenState); 12750 } 12751 12752 /** 12753 * This method is called whenever the state of the screen this view is 12754 * attached to changes. A state change will usually occurs when the screen 12755 * turns on or off (whether it happens automatically or the user does it 12756 * manually.) 12757 * 12758 * @param screenState The new state of the screen. Can be either 12759 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF} 12760 */ 12761 public void onScreenStateChanged(int screenState) { 12762 } 12763 12764 /** 12765 * Return true if the application tag in the AndroidManifest has set "supportRtl" to true 12766 */ 12767 private boolean hasRtlSupport() { 12768 return mContext.getApplicationInfo().hasRtlSupport(); 12769 } 12770 12771 /** 12772 * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or 12773 * RTL not supported) 12774 */ 12775 private boolean isRtlCompatibilityMode() { 12776 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 12777 return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport(); 12778 } 12779 12780 /** 12781 * @return true if RTL properties need resolution. 12782 * 12783 */ 12784 private boolean needRtlPropertiesResolution() { 12785 return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED; 12786 } 12787 12788 /** 12789 * Called when any RTL property (layout direction or text direction or text alignment) has 12790 * been changed. 12791 * 12792 * Subclasses need to override this method to take care of cached information that depends on the 12793 * resolved layout direction, or to inform child views that inherit their layout direction. 12794 * 12795 * The default implementation does nothing. 12796 * 12797 * @param layoutDirection the direction of the layout 12798 * 12799 * @see #LAYOUT_DIRECTION_LTR 12800 * @see #LAYOUT_DIRECTION_RTL 12801 */ 12802 public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) { 12803 } 12804 12805 /** 12806 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 12807 * that the parent directionality can and will be resolved before its children. 12808 * 12809 * @return true if resolution has been done, false otherwise. 12810 * 12811 * @hide 12812 */ 12813 public boolean resolveLayoutDirection() { 12814 // Clear any previous layout direction resolution 12815 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 12816 12817 if (hasRtlSupport()) { 12818 // Set resolved depending on layout direction 12819 switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> 12820 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) { 12821 case LAYOUT_DIRECTION_INHERIT: 12822 // We cannot resolve yet. LTR is by default and let the resolution happen again 12823 // later to get the correct resolved value 12824 if (!canResolveLayoutDirection()) return false; 12825 12826 // Parent has not yet resolved, LTR is still the default 12827 try { 12828 if (!mParent.isLayoutDirectionResolved()) return false; 12829 12830 if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 12831 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12832 } 12833 } catch (AbstractMethodError e) { 12834 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 12835 " does not fully implement ViewParent", e); 12836 } 12837 break; 12838 case LAYOUT_DIRECTION_RTL: 12839 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12840 break; 12841 case LAYOUT_DIRECTION_LOCALE: 12842 if((LAYOUT_DIRECTION_RTL == 12843 TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) { 12844 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12845 } 12846 break; 12847 default: 12848 // Nothing to do, LTR by default 12849 } 12850 } 12851 12852 // Set to resolved 12853 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 12854 return true; 12855 } 12856 12857 /** 12858 * Check if layout direction resolution can be done. 12859 * 12860 * @return true if layout direction resolution can be done otherwise return false. 12861 */ 12862 public boolean canResolveLayoutDirection() { 12863 switch (getRawLayoutDirection()) { 12864 case LAYOUT_DIRECTION_INHERIT: 12865 if (mParent != null) { 12866 try { 12867 return mParent.canResolveLayoutDirection(); 12868 } catch (AbstractMethodError e) { 12869 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 12870 " does not fully implement ViewParent", e); 12871 } 12872 } 12873 return false; 12874 12875 default: 12876 return true; 12877 } 12878 } 12879 12880 /** 12881 * Reset the resolved layout direction. Layout direction will be resolved during a call to 12882 * {@link #onMeasure(int, int)}. 12883 * 12884 * @hide 12885 */ 12886 public void resetResolvedLayoutDirection() { 12887 // Reset the current resolved bits 12888 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 12889 } 12890 12891 /** 12892 * @return true if the layout direction is inherited. 12893 * 12894 * @hide 12895 */ 12896 public boolean isLayoutDirectionInherited() { 12897 return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT); 12898 } 12899 12900 /** 12901 * @return true if layout direction has been resolved. 12902 */ 12903 public boolean isLayoutDirectionResolved() { 12904 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED; 12905 } 12906 12907 /** 12908 * Return if padding has been resolved 12909 * 12910 * @hide 12911 */ 12912 boolean isPaddingResolved() { 12913 return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED; 12914 } 12915 12916 /** 12917 * Resolves padding depending on layout direction, if applicable, and 12918 * recomputes internal padding values to adjust for scroll bars. 12919 * 12920 * @hide 12921 */ 12922 public void resolvePadding() { 12923 final int resolvedLayoutDirection = getLayoutDirection(); 12924 12925 if (!isRtlCompatibilityMode()) { 12926 // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account. 12927 // If start / end padding are defined, they will be resolved (hence overriding) to 12928 // left / right or right / left depending on the resolved layout direction. 12929 // If start / end padding are not defined, use the left / right ones. 12930 if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) { 12931 Rect padding = sThreadLocal.get(); 12932 if (padding == null) { 12933 padding = new Rect(); 12934 sThreadLocal.set(padding); 12935 } 12936 mBackground.getPadding(padding); 12937 if (!mLeftPaddingDefined) { 12938 mUserPaddingLeftInitial = padding.left; 12939 } 12940 if (!mRightPaddingDefined) { 12941 mUserPaddingRightInitial = padding.right; 12942 } 12943 } 12944 switch (resolvedLayoutDirection) { 12945 case LAYOUT_DIRECTION_RTL: 12946 if (mUserPaddingStart != UNDEFINED_PADDING) { 12947 mUserPaddingRight = mUserPaddingStart; 12948 } else { 12949 mUserPaddingRight = mUserPaddingRightInitial; 12950 } 12951 if (mUserPaddingEnd != UNDEFINED_PADDING) { 12952 mUserPaddingLeft = mUserPaddingEnd; 12953 } else { 12954 mUserPaddingLeft = mUserPaddingLeftInitial; 12955 } 12956 break; 12957 case LAYOUT_DIRECTION_LTR: 12958 default: 12959 if (mUserPaddingStart != UNDEFINED_PADDING) { 12960 mUserPaddingLeft = mUserPaddingStart; 12961 } else { 12962 mUserPaddingLeft = mUserPaddingLeftInitial; 12963 } 12964 if (mUserPaddingEnd != UNDEFINED_PADDING) { 12965 mUserPaddingRight = mUserPaddingEnd; 12966 } else { 12967 mUserPaddingRight = mUserPaddingRightInitial; 12968 } 12969 } 12970 12971 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 12972 } 12973 12974 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 12975 onRtlPropertiesChanged(resolvedLayoutDirection); 12976 12977 mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED; 12978 } 12979 12980 /** 12981 * Reset the resolved layout direction. 12982 * 12983 * @hide 12984 */ 12985 public void resetResolvedPadding() { 12986 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 12987 } 12988 12989 /** 12990 * This is called when the view is detached from a window. At this point it 12991 * no longer has a surface for drawing. 12992 * 12993 * @see #onAttachedToWindow() 12994 */ 12995 protected void onDetachedFromWindow() { 12996 } 12997 12998 /** 12999 * This is a framework-internal mirror of onDetachedFromWindow() that's called 13000 * after onDetachedFromWindow(). 13001 * 13002 * If you override this you *MUST* call super.onDetachedFromWindowInternal()! 13003 * The super method should be called at the end of the overriden method to ensure 13004 * subclasses are destroyed first 13005 * 13006 * @hide 13007 */ 13008 protected void onDetachedFromWindowInternal() { 13009 mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT; 13010 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 13011 13012 removeUnsetPressCallback(); 13013 removeLongPressCallback(); 13014 removePerformClickCallback(); 13015 removeSendViewScrolledAccessibilityEventCallback(); 13016 stopNestedScroll(); 13017 13018 destroyDrawingCache(); 13019 13020 cleanupDraw(); 13021 mCurrentAnimation = null; 13022 } 13023 13024 private void cleanupDraw() { 13025 resetDisplayList(); 13026 if (mAttachInfo != null) { 13027 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 13028 } 13029 } 13030 13031 void invalidateInheritedLayoutMode(int layoutModeOfRoot) { 13032 } 13033 13034 /** 13035 * @return The number of times this view has been attached to a window 13036 */ 13037 protected int getWindowAttachCount() { 13038 return mWindowAttachCount; 13039 } 13040 13041 /** 13042 * Retrieve a unique token identifying the window this view is attached to. 13043 * @return Return the window's token for use in 13044 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 13045 */ 13046 public IBinder getWindowToken() { 13047 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 13048 } 13049 13050 /** 13051 * Retrieve the {@link WindowId} for the window this view is 13052 * currently attached to. 13053 */ 13054 public WindowId getWindowId() { 13055 if (mAttachInfo == null) { 13056 return null; 13057 } 13058 if (mAttachInfo.mWindowId == null) { 13059 try { 13060 mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId( 13061 mAttachInfo.mWindowToken); 13062 mAttachInfo.mWindowId = new WindowId( 13063 mAttachInfo.mIWindowId); 13064 } catch (RemoteException e) { 13065 } 13066 } 13067 return mAttachInfo.mWindowId; 13068 } 13069 13070 /** 13071 * Retrieve a unique token identifying the top-level "real" window of 13072 * the window that this view is attached to. That is, this is like 13073 * {@link #getWindowToken}, except if the window this view in is a panel 13074 * window (attached to another containing window), then the token of 13075 * the containing window is returned instead. 13076 * 13077 * @return Returns the associated window token, either 13078 * {@link #getWindowToken()} or the containing window's token. 13079 */ 13080 public IBinder getApplicationWindowToken() { 13081 AttachInfo ai = mAttachInfo; 13082 if (ai != null) { 13083 IBinder appWindowToken = ai.mPanelParentWindowToken; 13084 if (appWindowToken == null) { 13085 appWindowToken = ai.mWindowToken; 13086 } 13087 return appWindowToken; 13088 } 13089 return null; 13090 } 13091 13092 /** 13093 * Gets the logical display to which the view's window has been attached. 13094 * 13095 * @return The logical display, or null if the view is not currently attached to a window. 13096 */ 13097 public Display getDisplay() { 13098 return mAttachInfo != null ? mAttachInfo.mDisplay : null; 13099 } 13100 13101 /** 13102 * Retrieve private session object this view hierarchy is using to 13103 * communicate with the window manager. 13104 * @return the session object to communicate with the window manager 13105 */ 13106 /*package*/ IWindowSession getWindowSession() { 13107 return mAttachInfo != null ? mAttachInfo.mSession : null; 13108 } 13109 13110 /** 13111 * @param info the {@link android.view.View.AttachInfo} to associated with 13112 * this view 13113 */ 13114 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 13115 //System.out.println("Attached! " + this); 13116 mAttachInfo = info; 13117 if (mOverlay != null) { 13118 mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility); 13119 } 13120 mWindowAttachCount++; 13121 // We will need to evaluate the drawable state at least once. 13122 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 13123 if (mFloatingTreeObserver != null) { 13124 info.mTreeObserver.merge(mFloatingTreeObserver); 13125 mFloatingTreeObserver = null; 13126 } 13127 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) { 13128 mAttachInfo.mScrollContainers.add(this); 13129 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 13130 } 13131 performCollectViewAttributes(mAttachInfo, visibility); 13132 onAttachedToWindow(); 13133 13134 ListenerInfo li = mListenerInfo; 13135 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 13136 li != null ? li.mOnAttachStateChangeListeners : null; 13137 if (listeners != null && listeners.size() > 0) { 13138 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 13139 // perform the dispatching. The iterator is a safe guard against listeners that 13140 // could mutate the list by calling the various add/remove methods. This prevents 13141 // the array from being modified while we iterate it. 13142 for (OnAttachStateChangeListener listener : listeners) { 13143 listener.onViewAttachedToWindow(this); 13144 } 13145 } 13146 13147 int vis = info.mWindowVisibility; 13148 if (vis != GONE) { 13149 onWindowVisibilityChanged(vis); 13150 } 13151 if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) { 13152 // If nobody has evaluated the drawable state yet, then do it now. 13153 refreshDrawableState(); 13154 } 13155 needGlobalAttributesUpdate(false); 13156 } 13157 13158 void dispatchDetachedFromWindow() { 13159 AttachInfo info = mAttachInfo; 13160 if (info != null) { 13161 int vis = info.mWindowVisibility; 13162 if (vis != GONE) { 13163 onWindowVisibilityChanged(GONE); 13164 } 13165 } 13166 13167 onDetachedFromWindow(); 13168 onDetachedFromWindowInternal(); 13169 13170 ListenerInfo li = mListenerInfo; 13171 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 13172 li != null ? li.mOnAttachStateChangeListeners : null; 13173 if (listeners != null && listeners.size() > 0) { 13174 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 13175 // perform the dispatching. The iterator is a safe guard against listeners that 13176 // could mutate the list by calling the various add/remove methods. This prevents 13177 // the array from being modified while we iterate it. 13178 for (OnAttachStateChangeListener listener : listeners) { 13179 listener.onViewDetachedFromWindow(this); 13180 } 13181 } 13182 13183 if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 13184 mAttachInfo.mScrollContainers.remove(this); 13185 mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED; 13186 } 13187 13188 mAttachInfo = null; 13189 if (mOverlay != null) { 13190 mOverlay.getOverlayView().dispatchDetachedFromWindow(); 13191 } 13192 } 13193 13194 /** 13195 * Cancel any deferred high-level input events that were previously posted to the event queue. 13196 * 13197 * <p>Many views post high-level events such as click handlers to the event queue 13198 * to run deferred in order to preserve a desired user experience - clearing visible 13199 * pressed states before executing, etc. This method will abort any events of this nature 13200 * that are currently in flight.</p> 13201 * 13202 * <p>Custom views that generate their own high-level deferred input events should override 13203 * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p> 13204 * 13205 * <p>This will also cancel pending input events for any child views.</p> 13206 * 13207 * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases. 13208 * This will not impact newer events posted after this call that may occur as a result of 13209 * lower-level input events still waiting in the queue. If you are trying to prevent 13210 * double-submitted events for the duration of some sort of asynchronous transaction 13211 * you should also take other steps to protect against unexpected double inputs e.g. calling 13212 * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when 13213 * the transaction completes, tracking already submitted transaction IDs, etc.</p> 13214 */ 13215 public final void cancelPendingInputEvents() { 13216 dispatchCancelPendingInputEvents(); 13217 } 13218 13219 /** 13220 * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight. 13221 * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling. 13222 */ 13223 void dispatchCancelPendingInputEvents() { 13224 mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER; 13225 onCancelPendingInputEvents(); 13226 if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) { 13227 throw new SuperNotCalledException("View " + getClass().getSimpleName() + 13228 " did not call through to super.onCancelPendingInputEvents()"); 13229 } 13230 } 13231 13232 /** 13233 * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or 13234 * a parent view. 13235 * 13236 * <p>This method is responsible for removing any pending high-level input events that were 13237 * posted to the event queue to run later. Custom view classes that post their own deferred 13238 * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or 13239 * {@link android.os.Handler} should override this method, call 13240 * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate. 13241 * </p> 13242 */ 13243 public void onCancelPendingInputEvents() { 13244 removePerformClickCallback(); 13245 cancelLongPress(); 13246 mPrivateFlags3 |= PFLAG3_CALLED_SUPER; 13247 } 13248 13249 /** 13250 * Store this view hierarchy's frozen state into the given container. 13251 * 13252 * @param container The SparseArray in which to save the view's state. 13253 * 13254 * @see #restoreHierarchyState(android.util.SparseArray) 13255 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13256 * @see #onSaveInstanceState() 13257 */ 13258 public void saveHierarchyState(SparseArray<Parcelable> container) { 13259 dispatchSaveInstanceState(container); 13260 } 13261 13262 /** 13263 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 13264 * this view and its children. May be overridden to modify how freezing happens to a 13265 * view's children; for example, some views may want to not store state for their children. 13266 * 13267 * @param container The SparseArray in which to save the view's state. 13268 * 13269 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13270 * @see #saveHierarchyState(android.util.SparseArray) 13271 * @see #onSaveInstanceState() 13272 */ 13273 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 13274 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 13275 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 13276 Parcelable state = onSaveInstanceState(); 13277 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 13278 throw new IllegalStateException( 13279 "Derived class did not call super.onSaveInstanceState()"); 13280 } 13281 if (state != null) { 13282 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 13283 // + ": " + state); 13284 container.put(mID, state); 13285 } 13286 } 13287 } 13288 13289 /** 13290 * Hook allowing a view to generate a representation of its internal state 13291 * that can later be used to create a new instance with that same state. 13292 * This state should only contain information that is not persistent or can 13293 * not be reconstructed later. For example, you will never store your 13294 * current position on screen because that will be computed again when a 13295 * new instance of the view is placed in its view hierarchy. 13296 * <p> 13297 * Some examples of things you may store here: the current cursor position 13298 * in a text view (but usually not the text itself since that is stored in a 13299 * content provider or other persistent storage), the currently selected 13300 * item in a list view. 13301 * 13302 * @return Returns a Parcelable object containing the view's current dynamic 13303 * state, or null if there is nothing interesting to save. The 13304 * default implementation returns null. 13305 * @see #onRestoreInstanceState(android.os.Parcelable) 13306 * @see #saveHierarchyState(android.util.SparseArray) 13307 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13308 * @see #setSaveEnabled(boolean) 13309 */ 13310 protected Parcelable onSaveInstanceState() { 13311 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 13312 return BaseSavedState.EMPTY_STATE; 13313 } 13314 13315 /** 13316 * Restore this view hierarchy's frozen state from the given container. 13317 * 13318 * @param container The SparseArray which holds previously frozen states. 13319 * 13320 * @see #saveHierarchyState(android.util.SparseArray) 13321 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13322 * @see #onRestoreInstanceState(android.os.Parcelable) 13323 */ 13324 public void restoreHierarchyState(SparseArray<Parcelable> container) { 13325 dispatchRestoreInstanceState(container); 13326 } 13327 13328 /** 13329 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 13330 * state for this view and its children. May be overridden to modify how restoring 13331 * happens to a view's children; for example, some views may want to not store state 13332 * for their children. 13333 * 13334 * @param container The SparseArray which holds previously saved state. 13335 * 13336 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13337 * @see #restoreHierarchyState(android.util.SparseArray) 13338 * @see #onRestoreInstanceState(android.os.Parcelable) 13339 */ 13340 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 13341 if (mID != NO_ID) { 13342 Parcelable state = container.get(mID); 13343 if (state != null) { 13344 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 13345 // + ": " + state); 13346 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 13347 onRestoreInstanceState(state); 13348 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 13349 throw new IllegalStateException( 13350 "Derived class did not call super.onRestoreInstanceState()"); 13351 } 13352 } 13353 } 13354 } 13355 13356 /** 13357 * Hook allowing a view to re-apply a representation of its internal state that had previously 13358 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 13359 * null state. 13360 * 13361 * @param state The frozen state that had previously been returned by 13362 * {@link #onSaveInstanceState}. 13363 * 13364 * @see #onSaveInstanceState() 13365 * @see #restoreHierarchyState(android.util.SparseArray) 13366 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13367 */ 13368 protected void onRestoreInstanceState(Parcelable state) { 13369 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 13370 if (state != BaseSavedState.EMPTY_STATE && state != null) { 13371 throw new IllegalArgumentException("Wrong state class, expecting View State but " 13372 + "received " + state.getClass().toString() + " instead. This usually happens " 13373 + "when two views of different type have the same id in the same hierarchy. " 13374 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 13375 + "other views do not use the same id."); 13376 } 13377 } 13378 13379 /** 13380 * <p>Return the time at which the drawing of the view hierarchy started.</p> 13381 * 13382 * @return the drawing start time in milliseconds 13383 */ 13384 public long getDrawingTime() { 13385 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 13386 } 13387 13388 /** 13389 * <p>Enables or disables the duplication of the parent's state into this view. When 13390 * duplication is enabled, this view gets its drawable state from its parent rather 13391 * than from its own internal properties.</p> 13392 * 13393 * <p>Note: in the current implementation, setting this property to true after the 13394 * view was added to a ViewGroup might have no effect at all. This property should 13395 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 13396 * 13397 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 13398 * property is enabled, an exception will be thrown.</p> 13399 * 13400 * <p>Note: if the child view uses and updates additionnal states which are unknown to the 13401 * parent, these states should not be affected by this method.</p> 13402 * 13403 * @param enabled True to enable duplication of the parent's drawable state, false 13404 * to disable it. 13405 * 13406 * @see #getDrawableState() 13407 * @see #isDuplicateParentStateEnabled() 13408 */ 13409 public void setDuplicateParentStateEnabled(boolean enabled) { 13410 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 13411 } 13412 13413 /** 13414 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 13415 * 13416 * @return True if this view's drawable state is duplicated from the parent, 13417 * false otherwise 13418 * 13419 * @see #getDrawableState() 13420 * @see #setDuplicateParentStateEnabled(boolean) 13421 */ 13422 public boolean isDuplicateParentStateEnabled() { 13423 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 13424 } 13425 13426 /** 13427 * <p>Specifies the type of layer backing this view. The layer can be 13428 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13429 * {@link #LAYER_TYPE_HARDWARE}.</p> 13430 * 13431 * <p>A layer is associated with an optional {@link android.graphics.Paint} 13432 * instance that controls how the layer is composed on screen. The following 13433 * properties of the paint are taken into account when composing the layer:</p> 13434 * <ul> 13435 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 13436 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 13437 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 13438 * </ul> 13439 * 13440 * <p>If this view has an alpha value set to < 1.0 by calling 13441 * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded 13442 * by this view's alpha value.</p> 13443 * 13444 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE}, 13445 * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE} 13446 * for more information on when and how to use layers.</p> 13447 * 13448 * @param layerType The type of layer to use with this view, must be one of 13449 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13450 * {@link #LAYER_TYPE_HARDWARE} 13451 * @param paint The paint used to compose the layer. This argument is optional 13452 * and can be null. It is ignored when the layer type is 13453 * {@link #LAYER_TYPE_NONE} 13454 * 13455 * @see #getLayerType() 13456 * @see #LAYER_TYPE_NONE 13457 * @see #LAYER_TYPE_SOFTWARE 13458 * @see #LAYER_TYPE_HARDWARE 13459 * @see #setAlpha(float) 13460 * 13461 * @attr ref android.R.styleable#View_layerType 13462 */ 13463 public void setLayerType(int layerType, Paint paint) { 13464 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 13465 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 13466 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 13467 } 13468 13469 boolean typeChanged = mRenderNode.setLayerType(layerType); 13470 13471 if (!typeChanged) { 13472 setLayerPaint(paint); 13473 return; 13474 } 13475 13476 // Destroy any previous software drawing cache if needed 13477 if (mLayerType == LAYER_TYPE_SOFTWARE) { 13478 destroyDrawingCache(); 13479 } 13480 13481 mLayerType = layerType; 13482 final boolean layerDisabled = (mLayerType == LAYER_TYPE_NONE); 13483 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 13484 mRenderNode.setLayerPaint(mLayerPaint); 13485 13486 // draw() behaves differently if we are on a layer, so we need to 13487 // invalidate() here 13488 invalidateParentCaches(); 13489 invalidate(true); 13490 } 13491 13492 /** 13493 * Updates the {@link Paint} object used with the current layer (used only if the current 13494 * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint 13495 * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time 13496 * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to 13497 * ensure that the view gets redrawn immediately. 13498 * 13499 * <p>A layer is associated with an optional {@link android.graphics.Paint} 13500 * instance that controls how the layer is composed on screen. The following 13501 * properties of the paint are taken into account when composing the layer:</p> 13502 * <ul> 13503 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 13504 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 13505 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 13506 * </ul> 13507 * 13508 * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the 13509 * alpha value of the layer's paint is superceded by this view's alpha value.</p> 13510 * 13511 * @param paint The paint used to compose the layer. This argument is optional 13512 * and can be null. It is ignored when the layer type is 13513 * {@link #LAYER_TYPE_NONE} 13514 * 13515 * @see #setLayerType(int, android.graphics.Paint) 13516 */ 13517 public void setLayerPaint(Paint paint) { 13518 int layerType = getLayerType(); 13519 if (layerType != LAYER_TYPE_NONE) { 13520 mLayerPaint = paint == null ? new Paint() : paint; 13521 if (layerType == LAYER_TYPE_HARDWARE) { 13522 if (mRenderNode.setLayerPaint(mLayerPaint)) { 13523 invalidateViewProperty(false, false); 13524 } 13525 } else { 13526 invalidate(); 13527 } 13528 } 13529 } 13530 13531 /** 13532 * Indicates whether this view has a static layer. A view with layer type 13533 * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are 13534 * dynamic. 13535 */ 13536 boolean hasStaticLayer() { 13537 return true; 13538 } 13539 13540 /** 13541 * Indicates what type of layer is currently associated with this view. By default 13542 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 13543 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 13544 * for more information on the different types of layers. 13545 * 13546 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13547 * {@link #LAYER_TYPE_HARDWARE} 13548 * 13549 * @see #setLayerType(int, android.graphics.Paint) 13550 * @see #buildLayer() 13551 * @see #LAYER_TYPE_NONE 13552 * @see #LAYER_TYPE_SOFTWARE 13553 * @see #LAYER_TYPE_HARDWARE 13554 */ 13555 public int getLayerType() { 13556 return mLayerType; 13557 } 13558 13559 /** 13560 * Forces this view's layer to be created and this view to be rendered 13561 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 13562 * invoking this method will have no effect. 13563 * 13564 * This method can for instance be used to render a view into its layer before 13565 * starting an animation. If this view is complex, rendering into the layer 13566 * before starting the animation will avoid skipping frames. 13567 * 13568 * @throws IllegalStateException If this view is not attached to a window 13569 * 13570 * @see #setLayerType(int, android.graphics.Paint) 13571 */ 13572 public void buildLayer() { 13573 if (mLayerType == LAYER_TYPE_NONE) return; 13574 13575 final AttachInfo attachInfo = mAttachInfo; 13576 if (attachInfo == null) { 13577 throw new IllegalStateException("This view must be attached to a window first"); 13578 } 13579 13580 if (getWidth() == 0 || getHeight() == 0) { 13581 return; 13582 } 13583 13584 switch (mLayerType) { 13585 case LAYER_TYPE_HARDWARE: 13586 // The only part of a hardware layer we can build in response to 13587 // this call is to ensure the display list is up to date. 13588 // The actual rendering of the display list into the layer must 13589 // be done at playback time 13590 updateDisplayListIfDirty(); 13591 break; 13592 case LAYER_TYPE_SOFTWARE: 13593 buildDrawingCache(true); 13594 break; 13595 } 13596 } 13597 13598 /** 13599 * If this View draws with a HardwareLayer, returns it. 13600 * Otherwise returns null 13601 * 13602 * TODO: Only TextureView uses this, can we eliminate it? 13603 */ 13604 HardwareLayer getHardwareLayer() { 13605 return null; 13606 } 13607 13608 /** 13609 * Destroys all hardware rendering resources. This method is invoked 13610 * when the system needs to reclaim resources. Upon execution of this 13611 * method, you should free any OpenGL resources created by the view. 13612 * 13613 * Note: you <strong>must</strong> call 13614 * <code>super.destroyHardwareResources()</code> when overriding 13615 * this method. 13616 * 13617 * @hide 13618 */ 13619 protected void destroyHardwareResources() { 13620 // Although the Layer will be destroyed by RenderNode, we want to release 13621 // the staging display list, which is also a signal to RenderNode that it's 13622 // safe to free its copy of the display list as it knows that we will 13623 // push an updated DisplayList if we try to draw again 13624 resetDisplayList(); 13625 } 13626 13627 /** 13628 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 13629 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 13630 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 13631 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 13632 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 13633 * null.</p> 13634 * 13635 * <p>Enabling the drawing cache is similar to 13636 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 13637 * acceleration is turned off. When hardware acceleration is turned on, enabling the 13638 * drawing cache has no effect on rendering because the system uses a different mechanism 13639 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 13640 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 13641 * for information on how to enable software and hardware layers.</p> 13642 * 13643 * <p>This API can be used to manually generate 13644 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 13645 * {@link #getDrawingCache()}.</p> 13646 * 13647 * @param enabled true to enable the drawing cache, false otherwise 13648 * 13649 * @see #isDrawingCacheEnabled() 13650 * @see #getDrawingCache() 13651 * @see #buildDrawingCache() 13652 * @see #setLayerType(int, android.graphics.Paint) 13653 */ 13654 public void setDrawingCacheEnabled(boolean enabled) { 13655 mCachingFailed = false; 13656 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 13657 } 13658 13659 /** 13660 * <p>Indicates whether the drawing cache is enabled for this view.</p> 13661 * 13662 * @return true if the drawing cache is enabled 13663 * 13664 * @see #setDrawingCacheEnabled(boolean) 13665 * @see #getDrawingCache() 13666 */ 13667 @ViewDebug.ExportedProperty(category = "drawing") 13668 public boolean isDrawingCacheEnabled() { 13669 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 13670 } 13671 13672 /** 13673 * Debugging utility which recursively outputs the dirty state of a view and its 13674 * descendants. 13675 * 13676 * @hide 13677 */ 13678 @SuppressWarnings({"UnusedDeclaration"}) 13679 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 13680 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) + 13681 ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" + 13682 (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) + 13683 ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")"); 13684 if (clear) { 13685 mPrivateFlags &= clearMask; 13686 } 13687 if (this instanceof ViewGroup) { 13688 ViewGroup parent = (ViewGroup) this; 13689 final int count = parent.getChildCount(); 13690 for (int i = 0; i < count; i++) { 13691 final View child = parent.getChildAt(i); 13692 child.outputDirtyFlags(indent + " ", clear, clearMask); 13693 } 13694 } 13695 } 13696 13697 /** 13698 * This method is used by ViewGroup to cause its children to restore or recreate their 13699 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 13700 * to recreate its own display list, which would happen if it went through the normal 13701 * draw/dispatchDraw mechanisms. 13702 * 13703 * @hide 13704 */ 13705 protected void dispatchGetDisplayList() {} 13706 13707 /** 13708 * A view that is not attached or hardware accelerated cannot create a display list. 13709 * This method checks these conditions and returns the appropriate result. 13710 * 13711 * @return true if view has the ability to create a display list, false otherwise. 13712 * 13713 * @hide 13714 */ 13715 public boolean canHaveDisplayList() { 13716 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 13717 } 13718 13719 private void updateDisplayListIfDirty() { 13720 final RenderNode renderNode = mRenderNode; 13721 if (!canHaveDisplayList()) { 13722 // can't populate RenderNode, don't try 13723 return; 13724 } 13725 13726 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 13727 || !renderNode.isValid() 13728 || (mRecreateDisplayList)) { 13729 // Don't need to recreate the display list, just need to tell our 13730 // children to restore/recreate theirs 13731 if (renderNode.isValid() 13732 && !mRecreateDisplayList) { 13733 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13734 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13735 dispatchGetDisplayList(); 13736 13737 return; // no work needed 13738 } 13739 13740 // If we got here, we're recreating it. Mark it as such to ensure that 13741 // we copy in child display lists into ours in drawChild() 13742 mRecreateDisplayList = true; 13743 13744 int width = mRight - mLeft; 13745 int height = mBottom - mTop; 13746 int layerType = getLayerType(); 13747 13748 final HardwareCanvas canvas = renderNode.start(width, height); 13749 13750 try { 13751 final HardwareLayer layer = getHardwareLayer(); 13752 if (layer != null && layer.isValid()) { 13753 canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint); 13754 } else if (layerType == LAYER_TYPE_SOFTWARE) { 13755 buildDrawingCache(true); 13756 Bitmap cache = getDrawingCache(true); 13757 if (cache != null) { 13758 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 13759 } 13760 } else { 13761 computeScroll(); 13762 13763 canvas.translate(-mScrollX, -mScrollY); 13764 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13765 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13766 13767 // Fast path for layouts with no backgrounds 13768 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 13769 dispatchDraw(canvas); 13770 if (mOverlay != null && !mOverlay.isEmpty()) { 13771 mOverlay.getOverlayView().draw(canvas); 13772 } 13773 } else { 13774 draw(canvas); 13775 } 13776 } 13777 } finally { 13778 renderNode.end(canvas); 13779 setDisplayListProperties(renderNode); 13780 } 13781 } else { 13782 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13783 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13784 } 13785 } 13786 13787 /** 13788 * Returns a RenderNode with View draw content recorded, which can be 13789 * used to draw this view again without executing its draw method. 13790 * 13791 * @return A RenderNode ready to replay, or null if caching is not enabled. 13792 * 13793 * @hide 13794 */ 13795 public RenderNode getDisplayList() { 13796 updateDisplayListIfDirty(); 13797 return mRenderNode; 13798 } 13799 13800 private void resetDisplayList() { 13801 if (mRenderNode.isValid()) { 13802 mRenderNode.destroyDisplayListData(); 13803 } 13804 13805 if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) { 13806 mBackgroundRenderNode.destroyDisplayListData(); 13807 } 13808 } 13809 13810 /** 13811 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 13812 * 13813 * @return A non-scaled bitmap representing this view or null if cache is disabled. 13814 * 13815 * @see #getDrawingCache(boolean) 13816 */ 13817 public Bitmap getDrawingCache() { 13818 return getDrawingCache(false); 13819 } 13820 13821 /** 13822 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 13823 * is null when caching is disabled. If caching is enabled and the cache is not ready, 13824 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 13825 * draw from the cache when the cache is enabled. To benefit from the cache, you must 13826 * request the drawing cache by calling this method and draw it on screen if the 13827 * returned bitmap is not null.</p> 13828 * 13829 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 13830 * this method will create a bitmap of the same size as this view. Because this bitmap 13831 * will be drawn scaled by the parent ViewGroup, the result on screen might show 13832 * scaling artifacts. To avoid such artifacts, you should call this method by setting 13833 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 13834 * size than the view. This implies that your application must be able to handle this 13835 * size.</p> 13836 * 13837 * @param autoScale Indicates whether the generated bitmap should be scaled based on 13838 * the current density of the screen when the application is in compatibility 13839 * mode. 13840 * 13841 * @return A bitmap representing this view or null if cache is disabled. 13842 * 13843 * @see #setDrawingCacheEnabled(boolean) 13844 * @see #isDrawingCacheEnabled() 13845 * @see #buildDrawingCache(boolean) 13846 * @see #destroyDrawingCache() 13847 */ 13848 public Bitmap getDrawingCache(boolean autoScale) { 13849 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 13850 return null; 13851 } 13852 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 13853 buildDrawingCache(autoScale); 13854 } 13855 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 13856 } 13857 13858 /** 13859 * <p>Frees the resources used by the drawing cache. If you call 13860 * {@link #buildDrawingCache()} manually without calling 13861 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 13862 * should cleanup the cache with this method afterwards.</p> 13863 * 13864 * @see #setDrawingCacheEnabled(boolean) 13865 * @see #buildDrawingCache() 13866 * @see #getDrawingCache() 13867 */ 13868 public void destroyDrawingCache() { 13869 if (mDrawingCache != null) { 13870 mDrawingCache.recycle(); 13871 mDrawingCache = null; 13872 } 13873 if (mUnscaledDrawingCache != null) { 13874 mUnscaledDrawingCache.recycle(); 13875 mUnscaledDrawingCache = null; 13876 } 13877 } 13878 13879 /** 13880 * Setting a solid background color for the drawing cache's bitmaps will improve 13881 * performance and memory usage. Note, though that this should only be used if this 13882 * view will always be drawn on top of a solid color. 13883 * 13884 * @param color The background color to use for the drawing cache's bitmap 13885 * 13886 * @see #setDrawingCacheEnabled(boolean) 13887 * @see #buildDrawingCache() 13888 * @see #getDrawingCache() 13889 */ 13890 public void setDrawingCacheBackgroundColor(int color) { 13891 if (color != mDrawingCacheBackgroundColor) { 13892 mDrawingCacheBackgroundColor = color; 13893 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 13894 } 13895 } 13896 13897 /** 13898 * @see #setDrawingCacheBackgroundColor(int) 13899 * 13900 * @return The background color to used for the drawing cache's bitmap 13901 */ 13902 public int getDrawingCacheBackgroundColor() { 13903 return mDrawingCacheBackgroundColor; 13904 } 13905 13906 /** 13907 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 13908 * 13909 * @see #buildDrawingCache(boolean) 13910 */ 13911 public void buildDrawingCache() { 13912 buildDrawingCache(false); 13913 } 13914 13915 /** 13916 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 13917 * 13918 * <p>If you call {@link #buildDrawingCache()} manually without calling 13919 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 13920 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 13921 * 13922 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 13923 * this method will create a bitmap of the same size as this view. Because this bitmap 13924 * will be drawn scaled by the parent ViewGroup, the result on screen might show 13925 * scaling artifacts. To avoid such artifacts, you should call this method by setting 13926 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 13927 * size than the view. This implies that your application must be able to handle this 13928 * size.</p> 13929 * 13930 * <p>You should avoid calling this method when hardware acceleration is enabled. If 13931 * you do not need the drawing cache bitmap, calling this method will increase memory 13932 * usage and cause the view to be rendered in software once, thus negatively impacting 13933 * performance.</p> 13934 * 13935 * @see #getDrawingCache() 13936 * @see #destroyDrawingCache() 13937 */ 13938 public void buildDrawingCache(boolean autoScale) { 13939 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ? 13940 mDrawingCache == null : mUnscaledDrawingCache == null)) { 13941 mCachingFailed = false; 13942 13943 int width = mRight - mLeft; 13944 int height = mBottom - mTop; 13945 13946 final AttachInfo attachInfo = mAttachInfo; 13947 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 13948 13949 if (autoScale && scalingRequired) { 13950 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 13951 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 13952 } 13953 13954 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 13955 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 13956 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 13957 13958 final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4); 13959 final long drawingCacheSize = 13960 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize(); 13961 if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) { 13962 if (width > 0 && height > 0) { 13963 Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs " 13964 + projectedBitmapSize + " bytes, only " 13965 + drawingCacheSize + " available"); 13966 } 13967 destroyDrawingCache(); 13968 mCachingFailed = true; 13969 return; 13970 } 13971 13972 boolean clear = true; 13973 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 13974 13975 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 13976 Bitmap.Config quality; 13977 if (!opaque) { 13978 // Never pick ARGB_4444 because it looks awful 13979 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 13980 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 13981 case DRAWING_CACHE_QUALITY_AUTO: 13982 case DRAWING_CACHE_QUALITY_LOW: 13983 case DRAWING_CACHE_QUALITY_HIGH: 13984 default: 13985 quality = Bitmap.Config.ARGB_8888; 13986 break; 13987 } 13988 } else { 13989 // Optimization for translucent windows 13990 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 13991 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 13992 } 13993 13994 // Try to cleanup memory 13995 if (bitmap != null) bitmap.recycle(); 13996 13997 try { 13998 bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 13999 width, height, quality); 14000 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 14001 if (autoScale) { 14002 mDrawingCache = bitmap; 14003 } else { 14004 mUnscaledDrawingCache = bitmap; 14005 } 14006 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 14007 } catch (OutOfMemoryError e) { 14008 // If there is not enough memory to create the bitmap cache, just 14009 // ignore the issue as bitmap caches are not required to draw the 14010 // view hierarchy 14011 if (autoScale) { 14012 mDrawingCache = null; 14013 } else { 14014 mUnscaledDrawingCache = null; 14015 } 14016 mCachingFailed = true; 14017 return; 14018 } 14019 14020 clear = drawingCacheBackgroundColor != 0; 14021 } 14022 14023 Canvas canvas; 14024 if (attachInfo != null) { 14025 canvas = attachInfo.mCanvas; 14026 if (canvas == null) { 14027 canvas = new Canvas(); 14028 } 14029 canvas.setBitmap(bitmap); 14030 // Temporarily clobber the cached Canvas in case one of our children 14031 // is also using a drawing cache. Without this, the children would 14032 // steal the canvas by attaching their own bitmap to it and bad, bad 14033 // thing would happen (invisible views, corrupted drawings, etc.) 14034 attachInfo.mCanvas = null; 14035 } else { 14036 // This case should hopefully never or seldom happen 14037 canvas = new Canvas(bitmap); 14038 } 14039 14040 if (clear) { 14041 bitmap.eraseColor(drawingCacheBackgroundColor); 14042 } 14043 14044 computeScroll(); 14045 final int restoreCount = canvas.save(); 14046 14047 if (autoScale && scalingRequired) { 14048 final float scale = attachInfo.mApplicationScale; 14049 canvas.scale(scale, scale); 14050 } 14051 14052 canvas.translate(-mScrollX, -mScrollY); 14053 14054 mPrivateFlags |= PFLAG_DRAWN; 14055 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 14056 mLayerType != LAYER_TYPE_NONE) { 14057 mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID; 14058 } 14059 14060 // Fast path for layouts with no backgrounds 14061 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14062 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14063 dispatchDraw(canvas); 14064 if (mOverlay != null && !mOverlay.isEmpty()) { 14065 mOverlay.getOverlayView().draw(canvas); 14066 } 14067 } else { 14068 draw(canvas); 14069 } 14070 14071 canvas.restoreToCount(restoreCount); 14072 canvas.setBitmap(null); 14073 14074 if (attachInfo != null) { 14075 // Restore the cached Canvas for our siblings 14076 attachInfo.mCanvas = canvas; 14077 } 14078 } 14079 } 14080 14081 /** 14082 * Create a snapshot of the view into a bitmap. We should probably make 14083 * some form of this public, but should think about the API. 14084 */ 14085 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 14086 int width = mRight - mLeft; 14087 int height = mBottom - mTop; 14088 14089 final AttachInfo attachInfo = mAttachInfo; 14090 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 14091 width = (int) ((width * scale) + 0.5f); 14092 height = (int) ((height * scale) + 0.5f); 14093 14094 Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 14095 width > 0 ? width : 1, height > 0 ? height : 1, quality); 14096 if (bitmap == null) { 14097 throw new OutOfMemoryError(); 14098 } 14099 14100 Resources resources = getResources(); 14101 if (resources != null) { 14102 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 14103 } 14104 14105 Canvas canvas; 14106 if (attachInfo != null) { 14107 canvas = attachInfo.mCanvas; 14108 if (canvas == null) { 14109 canvas = new Canvas(); 14110 } 14111 canvas.setBitmap(bitmap); 14112 // Temporarily clobber the cached Canvas in case one of our children 14113 // is also using a drawing cache. Without this, the children would 14114 // steal the canvas by attaching their own bitmap to it and bad, bad 14115 // things would happen (invisible views, corrupted drawings, etc.) 14116 attachInfo.mCanvas = null; 14117 } else { 14118 // This case should hopefully never or seldom happen 14119 canvas = new Canvas(bitmap); 14120 } 14121 14122 if ((backgroundColor & 0xff000000) != 0) { 14123 bitmap.eraseColor(backgroundColor); 14124 } 14125 14126 computeScroll(); 14127 final int restoreCount = canvas.save(); 14128 canvas.scale(scale, scale); 14129 canvas.translate(-mScrollX, -mScrollY); 14130 14131 // Temporarily remove the dirty mask 14132 int flags = mPrivateFlags; 14133 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14134 14135 // Fast path for layouts with no backgrounds 14136 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14137 dispatchDraw(canvas); 14138 if (mOverlay != null && !mOverlay.isEmpty()) { 14139 mOverlay.getOverlayView().draw(canvas); 14140 } 14141 } else { 14142 draw(canvas); 14143 } 14144 14145 mPrivateFlags = flags; 14146 14147 canvas.restoreToCount(restoreCount); 14148 canvas.setBitmap(null); 14149 14150 if (attachInfo != null) { 14151 // Restore the cached Canvas for our siblings 14152 attachInfo.mCanvas = canvas; 14153 } 14154 14155 return bitmap; 14156 } 14157 14158 /** 14159 * Indicates whether this View is currently in edit mode. A View is usually 14160 * in edit mode when displayed within a developer tool. For instance, if 14161 * this View is being drawn by a visual user interface builder, this method 14162 * should return true. 14163 * 14164 * Subclasses should check the return value of this method to provide 14165 * different behaviors if their normal behavior might interfere with the 14166 * host environment. For instance: the class spawns a thread in its 14167 * constructor, the drawing code relies on device-specific features, etc. 14168 * 14169 * This method is usually checked in the drawing code of custom widgets. 14170 * 14171 * @return True if this View is in edit mode, false otherwise. 14172 */ 14173 public boolean isInEditMode() { 14174 return false; 14175 } 14176 14177 /** 14178 * If the View draws content inside its padding and enables fading edges, 14179 * it needs to support padding offsets. Padding offsets are added to the 14180 * fading edges to extend the length of the fade so that it covers pixels 14181 * drawn inside the padding. 14182 * 14183 * Subclasses of this class should override this method if they need 14184 * to draw content inside the padding. 14185 * 14186 * @return True if padding offset must be applied, false otherwise. 14187 * 14188 * @see #getLeftPaddingOffset() 14189 * @see #getRightPaddingOffset() 14190 * @see #getTopPaddingOffset() 14191 * @see #getBottomPaddingOffset() 14192 * 14193 * @since CURRENT 14194 */ 14195 protected boolean isPaddingOffsetRequired() { 14196 return false; 14197 } 14198 14199 /** 14200 * Amount by which to extend the left fading region. Called only when 14201 * {@link #isPaddingOffsetRequired()} returns true. 14202 * 14203 * @return The left padding offset in pixels. 14204 * 14205 * @see #isPaddingOffsetRequired() 14206 * 14207 * @since CURRENT 14208 */ 14209 protected int getLeftPaddingOffset() { 14210 return 0; 14211 } 14212 14213 /** 14214 * Amount by which to extend the right fading region. Called only when 14215 * {@link #isPaddingOffsetRequired()} returns true. 14216 * 14217 * @return The right padding offset in pixels. 14218 * 14219 * @see #isPaddingOffsetRequired() 14220 * 14221 * @since CURRENT 14222 */ 14223 protected int getRightPaddingOffset() { 14224 return 0; 14225 } 14226 14227 /** 14228 * Amount by which to extend the top fading region. Called only when 14229 * {@link #isPaddingOffsetRequired()} returns true. 14230 * 14231 * @return The top padding offset in pixels. 14232 * 14233 * @see #isPaddingOffsetRequired() 14234 * 14235 * @since CURRENT 14236 */ 14237 protected int getTopPaddingOffset() { 14238 return 0; 14239 } 14240 14241 /** 14242 * Amount by which to extend the bottom fading region. Called only when 14243 * {@link #isPaddingOffsetRequired()} returns true. 14244 * 14245 * @return The bottom padding offset in pixels. 14246 * 14247 * @see #isPaddingOffsetRequired() 14248 * 14249 * @since CURRENT 14250 */ 14251 protected int getBottomPaddingOffset() { 14252 return 0; 14253 } 14254 14255 /** 14256 * @hide 14257 * @param offsetRequired 14258 */ 14259 protected int getFadeTop(boolean offsetRequired) { 14260 int top = mPaddingTop; 14261 if (offsetRequired) top += getTopPaddingOffset(); 14262 return top; 14263 } 14264 14265 /** 14266 * @hide 14267 * @param offsetRequired 14268 */ 14269 protected int getFadeHeight(boolean offsetRequired) { 14270 int padding = mPaddingTop; 14271 if (offsetRequired) padding += getTopPaddingOffset(); 14272 return mBottom - mTop - mPaddingBottom - padding; 14273 } 14274 14275 /** 14276 * <p>Indicates whether this view is attached to a hardware accelerated 14277 * window or not.</p> 14278 * 14279 * <p>Even if this method returns true, it does not mean that every call 14280 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 14281 * accelerated {@link android.graphics.Canvas}. For instance, if this view 14282 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 14283 * window is hardware accelerated, 14284 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 14285 * return false, and this method will return true.</p> 14286 * 14287 * @return True if the view is attached to a window and the window is 14288 * hardware accelerated; false in any other case. 14289 */ 14290 @ViewDebug.ExportedProperty(category = "drawing") 14291 public boolean isHardwareAccelerated() { 14292 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 14293 } 14294 14295 /** 14296 * Sets a rectangular area on this view to which the view will be clipped 14297 * when it is drawn. Setting the value to null will remove the clip bounds 14298 * and the view will draw normally, using its full bounds. 14299 * 14300 * @param clipBounds The rectangular area, in the local coordinates of 14301 * this view, to which future drawing operations will be clipped. 14302 */ 14303 public void setClipBounds(Rect clipBounds) { 14304 if (clipBounds != null) { 14305 if (clipBounds.equals(mClipBounds)) { 14306 return; 14307 } 14308 if (mClipBounds == null) { 14309 invalidate(); 14310 mClipBounds = new Rect(clipBounds); 14311 } else { 14312 invalidate(Math.min(mClipBounds.left, clipBounds.left), 14313 Math.min(mClipBounds.top, clipBounds.top), 14314 Math.max(mClipBounds.right, clipBounds.right), 14315 Math.max(mClipBounds.bottom, clipBounds.bottom)); 14316 mClipBounds.set(clipBounds); 14317 } 14318 } else { 14319 if (mClipBounds != null) { 14320 invalidate(); 14321 mClipBounds = null; 14322 } 14323 } 14324 } 14325 14326 /** 14327 * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}. 14328 * 14329 * @return A copy of the current clip bounds if clip bounds are set, 14330 * otherwise null. 14331 */ 14332 public Rect getClipBounds() { 14333 return (mClipBounds != null) ? new Rect(mClipBounds) : null; 14334 } 14335 14336 /** 14337 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 14338 * case of an active Animation being run on the view. 14339 */ 14340 private boolean drawAnimation(ViewGroup parent, long drawingTime, 14341 Animation a, boolean scalingRequired) { 14342 Transformation invalidationTransform; 14343 final int flags = parent.mGroupFlags; 14344 final boolean initialized = a.isInitialized(); 14345 if (!initialized) { 14346 a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight()); 14347 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 14348 if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler); 14349 onAnimationStart(); 14350 } 14351 14352 final Transformation t = parent.getChildTransformation(); 14353 boolean more = a.getTransformation(drawingTime, t, 1f); 14354 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 14355 if (parent.mInvalidationTransformation == null) { 14356 parent.mInvalidationTransformation = new Transformation(); 14357 } 14358 invalidationTransform = parent.mInvalidationTransformation; 14359 a.getTransformation(drawingTime, invalidationTransform, 1f); 14360 } else { 14361 invalidationTransform = t; 14362 } 14363 14364 if (more) { 14365 if (!a.willChangeBounds()) { 14366 if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) == 14367 ViewGroup.FLAG_OPTIMIZE_INVALIDATE) { 14368 parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED; 14369 } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) { 14370 // The child need to draw an animation, potentially offscreen, so 14371 // make sure we do not cancel invalidate requests 14372 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 14373 parent.invalidate(mLeft, mTop, mRight, mBottom); 14374 } 14375 } else { 14376 if (parent.mInvalidateRegion == null) { 14377 parent.mInvalidateRegion = new RectF(); 14378 } 14379 final RectF region = parent.mInvalidateRegion; 14380 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 14381 invalidationTransform); 14382 14383 // The child need to draw an animation, potentially offscreen, so 14384 // make sure we do not cancel invalidate requests 14385 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 14386 14387 final int left = mLeft + (int) region.left; 14388 final int top = mTop + (int) region.top; 14389 parent.invalidate(left, top, left + (int) (region.width() + .5f), 14390 top + (int) (region.height() + .5f)); 14391 } 14392 } 14393 return more; 14394 } 14395 14396 /** 14397 * This method is called by getDisplayList() when a display list is recorded for a View. 14398 * It pushes any properties to the RenderNode that aren't managed by the RenderNode. 14399 */ 14400 void setDisplayListProperties(RenderNode renderNode) { 14401 if (renderNode != null) { 14402 renderNode.setHasOverlappingRendering(hasOverlappingRendering()); 14403 if (mParent instanceof ViewGroup) { 14404 renderNode.setClipToBounds( 14405 (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0); 14406 } 14407 float alpha = 1; 14408 if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags & 14409 ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 14410 ViewGroup parentVG = (ViewGroup) mParent; 14411 final Transformation t = parentVG.getChildTransformation(); 14412 if (parentVG.getChildStaticTransformation(this, t)) { 14413 final int transformType = t.getTransformationType(); 14414 if (transformType != Transformation.TYPE_IDENTITY) { 14415 if ((transformType & Transformation.TYPE_ALPHA) != 0) { 14416 alpha = t.getAlpha(); 14417 } 14418 if ((transformType & Transformation.TYPE_MATRIX) != 0) { 14419 renderNode.setStaticMatrix(t.getMatrix()); 14420 } 14421 } 14422 } 14423 } 14424 if (mTransformationInfo != null) { 14425 alpha *= getFinalAlpha(); 14426 if (alpha < 1) { 14427 final int multipliedAlpha = (int) (255 * alpha); 14428 if (onSetAlpha(multipliedAlpha)) { 14429 alpha = 1; 14430 } 14431 } 14432 renderNode.setAlpha(alpha); 14433 } else if (alpha < 1) { 14434 renderNode.setAlpha(alpha); 14435 } 14436 } 14437 } 14438 14439 /** 14440 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 14441 * This draw() method is an implementation detail and is not intended to be overridden or 14442 * to be called from anywhere else other than ViewGroup.drawChild(). 14443 */ 14444 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 14445 boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 14446 boolean more = false; 14447 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 14448 final int flags = parent.mGroupFlags; 14449 14450 if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) { 14451 parent.getChildTransformation().clear(); 14452 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14453 } 14454 14455 Transformation transformToApply = null; 14456 boolean concatMatrix = false; 14457 14458 boolean scalingRequired = false; 14459 boolean caching; 14460 int layerType = getLayerType(); 14461 14462 final boolean hardwareAccelerated = canvas.isHardwareAccelerated(); 14463 if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 || 14464 (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) { 14465 caching = true; 14466 // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList 14467 if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired; 14468 } else { 14469 caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated; 14470 } 14471 14472 final Animation a = getAnimation(); 14473 if (a != null) { 14474 more = drawAnimation(parent, drawingTime, a, scalingRequired); 14475 concatMatrix = a.willChangeTransformationMatrix(); 14476 if (concatMatrix) { 14477 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 14478 } 14479 transformToApply = parent.getChildTransformation(); 14480 } else { 14481 if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) { 14482 // No longer animating: clear out old animation matrix 14483 mRenderNode.setAnimationMatrix(null); 14484 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 14485 } 14486 if (!useDisplayListProperties && 14487 (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 14488 final Transformation t = parent.getChildTransformation(); 14489 final boolean hasTransform = parent.getChildStaticTransformation(this, t); 14490 if (hasTransform) { 14491 final int transformType = t.getTransformationType(); 14492 transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null; 14493 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 14494 } 14495 } 14496 } 14497 14498 concatMatrix |= !childHasIdentityMatrix; 14499 14500 // Sets the flag as early as possible to allow draw() implementations 14501 // to call invalidate() successfully when doing animations 14502 mPrivateFlags |= PFLAG_DRAWN; 14503 14504 if (!concatMatrix && 14505 (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS | 14506 ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN && 14507 canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 14508 (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) { 14509 mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED; 14510 return more; 14511 } 14512 mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED; 14513 14514 if (hardwareAccelerated) { 14515 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 14516 // retain the flag's value temporarily in the mRecreateDisplayList flag 14517 mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED; 14518 mPrivateFlags &= ~PFLAG_INVALIDATED; 14519 } 14520 14521 RenderNode renderNode = null; 14522 Bitmap cache = null; 14523 boolean hasDisplayList = false; 14524 if (caching) { 14525 if (!hardwareAccelerated) { 14526 if (layerType != LAYER_TYPE_NONE) { 14527 layerType = LAYER_TYPE_SOFTWARE; 14528 buildDrawingCache(true); 14529 } 14530 cache = getDrawingCache(true); 14531 } else { 14532 switch (layerType) { 14533 case LAYER_TYPE_SOFTWARE: 14534 if (useDisplayListProperties) { 14535 hasDisplayList = canHaveDisplayList(); 14536 } else { 14537 buildDrawingCache(true); 14538 cache = getDrawingCache(true); 14539 } 14540 break; 14541 case LAYER_TYPE_HARDWARE: 14542 if (useDisplayListProperties) { 14543 hasDisplayList = canHaveDisplayList(); 14544 } 14545 break; 14546 case LAYER_TYPE_NONE: 14547 // Delay getting the display list until animation-driven alpha values are 14548 // set up and possibly passed on to the view 14549 hasDisplayList = canHaveDisplayList(); 14550 break; 14551 } 14552 } 14553 } 14554 useDisplayListProperties &= hasDisplayList; 14555 if (useDisplayListProperties) { 14556 renderNode = getDisplayList(); 14557 if (!renderNode.isValid()) { 14558 // Uncommon, but possible. If a view is removed from the hierarchy during the call 14559 // to getDisplayList(), the display list will be marked invalid and we should not 14560 // try to use it again. 14561 renderNode = null; 14562 hasDisplayList = false; 14563 useDisplayListProperties = false; 14564 } 14565 } 14566 14567 int sx = 0; 14568 int sy = 0; 14569 if (!hasDisplayList) { 14570 computeScroll(); 14571 sx = mScrollX; 14572 sy = mScrollY; 14573 } 14574 14575 final boolean hasNoCache = cache == null || hasDisplayList; 14576 final boolean offsetForScroll = cache == null && !hasDisplayList && 14577 layerType != LAYER_TYPE_HARDWARE; 14578 14579 int restoreTo = -1; 14580 if (!useDisplayListProperties || transformToApply != null) { 14581 restoreTo = canvas.save(); 14582 } 14583 if (offsetForScroll) { 14584 canvas.translate(mLeft - sx, mTop - sy); 14585 } else { 14586 if (!useDisplayListProperties) { 14587 canvas.translate(mLeft, mTop); 14588 } 14589 if (scalingRequired) { 14590 if (useDisplayListProperties) { 14591 // TODO: Might not need this if we put everything inside the DL 14592 restoreTo = canvas.save(); 14593 } 14594 // mAttachInfo cannot be null, otherwise scalingRequired == false 14595 final float scale = 1.0f / mAttachInfo.mApplicationScale; 14596 canvas.scale(scale, scale); 14597 } 14598 } 14599 14600 float alpha = useDisplayListProperties ? 1 : (getAlpha() * getTransitionAlpha()); 14601 if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() || 14602 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 14603 if (transformToApply != null || !childHasIdentityMatrix) { 14604 int transX = 0; 14605 int transY = 0; 14606 14607 if (offsetForScroll) { 14608 transX = -sx; 14609 transY = -sy; 14610 } 14611 14612 if (transformToApply != null) { 14613 if (concatMatrix) { 14614 if (useDisplayListProperties) { 14615 renderNode.setAnimationMatrix(transformToApply.getMatrix()); 14616 } else { 14617 // Undo the scroll translation, apply the transformation matrix, 14618 // then redo the scroll translate to get the correct result. 14619 canvas.translate(-transX, -transY); 14620 canvas.concat(transformToApply.getMatrix()); 14621 canvas.translate(transX, transY); 14622 } 14623 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14624 } 14625 14626 float transformAlpha = transformToApply.getAlpha(); 14627 if (transformAlpha < 1) { 14628 alpha *= transformAlpha; 14629 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14630 } 14631 } 14632 14633 if (!childHasIdentityMatrix && !useDisplayListProperties) { 14634 canvas.translate(-transX, -transY); 14635 canvas.concat(getMatrix()); 14636 canvas.translate(transX, transY); 14637 } 14638 } 14639 14640 // Deal with alpha if it is or used to be <1 14641 if (alpha < 1 || 14642 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 14643 if (alpha < 1) { 14644 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA; 14645 } else { 14646 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA; 14647 } 14648 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14649 if (hasNoCache) { 14650 final int multipliedAlpha = (int) (255 * alpha); 14651 if (!onSetAlpha(multipliedAlpha)) { 14652 int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 14653 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 || 14654 layerType != LAYER_TYPE_NONE) { 14655 layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG; 14656 } 14657 if (useDisplayListProperties) { 14658 renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha()); 14659 } else if (layerType == LAYER_TYPE_NONE) { 14660 final int scrollX = hasDisplayList ? 0 : sx; 14661 final int scrollY = hasDisplayList ? 0 : sy; 14662 canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft, 14663 scrollY + mBottom - mTop, multipliedAlpha, layerFlags); 14664 } 14665 } else { 14666 // Alpha is handled by the child directly, clobber the layer's alpha 14667 mPrivateFlags |= PFLAG_ALPHA_SET; 14668 } 14669 } 14670 } 14671 } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 14672 onSetAlpha(255); 14673 mPrivateFlags &= ~PFLAG_ALPHA_SET; 14674 } 14675 14676 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN && 14677 !useDisplayListProperties && cache == null) { 14678 if (offsetForScroll) { 14679 canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop)); 14680 } else { 14681 if (!scalingRequired || cache == null) { 14682 canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop); 14683 } else { 14684 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 14685 } 14686 } 14687 } 14688 14689 if (!useDisplayListProperties && hasDisplayList) { 14690 renderNode = getDisplayList(); 14691 if (!renderNode.isValid()) { 14692 // Uncommon, but possible. If a view is removed from the hierarchy during the call 14693 // to getDisplayList(), the display list will be marked invalid and we should not 14694 // try to use it again. 14695 renderNode = null; 14696 hasDisplayList = false; 14697 } 14698 } 14699 14700 if (hasNoCache) { 14701 boolean layerRendered = false; 14702 if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) { 14703 final HardwareLayer layer = getHardwareLayer(); 14704 if (layer != null && layer.isValid()) { 14705 mLayerPaint.setAlpha((int) (alpha * 255)); 14706 ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint); 14707 layerRendered = true; 14708 } else { 14709 final int scrollX = hasDisplayList ? 0 : sx; 14710 final int scrollY = hasDisplayList ? 0 : sy; 14711 canvas.saveLayer(scrollX, scrollY, 14712 scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint, 14713 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG); 14714 } 14715 } 14716 14717 if (!layerRendered) { 14718 if (!hasDisplayList) { 14719 // Fast path for layouts with no backgrounds 14720 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14721 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14722 dispatchDraw(canvas); 14723 } else { 14724 draw(canvas); 14725 } 14726 } else { 14727 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14728 ((HardwareCanvas) canvas).drawRenderNode(renderNode, null, flags); 14729 } 14730 } 14731 } else if (cache != null) { 14732 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14733 Paint cachePaint; 14734 14735 if (layerType == LAYER_TYPE_NONE) { 14736 cachePaint = parent.mCachePaint; 14737 if (cachePaint == null) { 14738 cachePaint = new Paint(); 14739 cachePaint.setDither(false); 14740 parent.mCachePaint = cachePaint; 14741 } 14742 if (alpha < 1) { 14743 cachePaint.setAlpha((int) (alpha * 255)); 14744 parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 14745 } else if ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) { 14746 cachePaint.setAlpha(255); 14747 parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 14748 } 14749 } else { 14750 cachePaint = mLayerPaint; 14751 cachePaint.setAlpha((int) (alpha * 255)); 14752 } 14753 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 14754 } 14755 14756 if (restoreTo >= 0) { 14757 canvas.restoreToCount(restoreTo); 14758 } 14759 14760 if (a != null && !more) { 14761 if (!hardwareAccelerated && !a.getFillAfter()) { 14762 onSetAlpha(255); 14763 } 14764 parent.finishAnimatingView(this, a); 14765 } 14766 14767 if (more && hardwareAccelerated) { 14768 if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 14769 // alpha animations should cause the child to recreate its display list 14770 invalidate(true); 14771 } 14772 } 14773 14774 mRecreateDisplayList = false; 14775 14776 return more; 14777 } 14778 14779 /** 14780 * Manually render this view (and all of its children) to the given Canvas. 14781 * The view must have already done a full layout before this function is 14782 * called. When implementing a view, implement 14783 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 14784 * If you do need to override this method, call the superclass version. 14785 * 14786 * @param canvas The Canvas to which the View is rendered. 14787 */ 14788 public void draw(Canvas canvas) { 14789 if (mClipBounds != null) { 14790 canvas.clipRect(mClipBounds); 14791 } 14792 final int privateFlags = mPrivateFlags; 14793 final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE && 14794 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 14795 mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN; 14796 14797 /* 14798 * Draw traversal performs several drawing steps which must be executed 14799 * in the appropriate order: 14800 * 14801 * 1. Draw the background 14802 * 2. If necessary, save the canvas' layers to prepare for fading 14803 * 3. Draw view's content 14804 * 4. Draw children 14805 * 5. If necessary, draw the fading edges and restore layers 14806 * 6. Draw decorations (scrollbars for instance) 14807 */ 14808 14809 // Step 1, draw the background, if needed 14810 int saveCount; 14811 14812 if (!dirtyOpaque) { 14813 drawBackground(canvas); 14814 } 14815 14816 // skip step 2 & 5 if possible (common case) 14817 final int viewFlags = mViewFlags; 14818 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 14819 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 14820 if (!verticalEdges && !horizontalEdges) { 14821 // Step 3, draw the content 14822 if (!dirtyOpaque) onDraw(canvas); 14823 14824 // Step 4, draw the children 14825 dispatchDraw(canvas); 14826 14827 // Step 6, draw decorations (scrollbars) 14828 onDrawScrollBars(canvas); 14829 14830 if (mOverlay != null && !mOverlay.isEmpty()) { 14831 mOverlay.getOverlayView().dispatchDraw(canvas); 14832 } 14833 14834 // we're done... 14835 return; 14836 } 14837 14838 /* 14839 * Here we do the full fledged routine... 14840 * (this is an uncommon case where speed matters less, 14841 * this is why we repeat some of the tests that have been 14842 * done above) 14843 */ 14844 14845 boolean drawTop = false; 14846 boolean drawBottom = false; 14847 boolean drawLeft = false; 14848 boolean drawRight = false; 14849 14850 float topFadeStrength = 0.0f; 14851 float bottomFadeStrength = 0.0f; 14852 float leftFadeStrength = 0.0f; 14853 float rightFadeStrength = 0.0f; 14854 14855 // Step 2, save the canvas' layers 14856 int paddingLeft = mPaddingLeft; 14857 14858 final boolean offsetRequired = isPaddingOffsetRequired(); 14859 if (offsetRequired) { 14860 paddingLeft += getLeftPaddingOffset(); 14861 } 14862 14863 int left = mScrollX + paddingLeft; 14864 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 14865 int top = mScrollY + getFadeTop(offsetRequired); 14866 int bottom = top + getFadeHeight(offsetRequired); 14867 14868 if (offsetRequired) { 14869 right += getRightPaddingOffset(); 14870 bottom += getBottomPaddingOffset(); 14871 } 14872 14873 final ScrollabilityCache scrollabilityCache = mScrollCache; 14874 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 14875 int length = (int) fadeHeight; 14876 14877 // clip the fade length if top and bottom fades overlap 14878 // overlapping fades produce odd-looking artifacts 14879 if (verticalEdges && (top + length > bottom - length)) { 14880 length = (bottom - top) / 2; 14881 } 14882 14883 // also clip horizontal fades if necessary 14884 if (horizontalEdges && (left + length > right - length)) { 14885 length = (right - left) / 2; 14886 } 14887 14888 if (verticalEdges) { 14889 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 14890 drawTop = topFadeStrength * fadeHeight > 1.0f; 14891 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 14892 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 14893 } 14894 14895 if (horizontalEdges) { 14896 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 14897 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 14898 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 14899 drawRight = rightFadeStrength * fadeHeight > 1.0f; 14900 } 14901 14902 saveCount = canvas.getSaveCount(); 14903 14904 int solidColor = getSolidColor(); 14905 if (solidColor == 0) { 14906 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 14907 14908 if (drawTop) { 14909 canvas.saveLayer(left, top, right, top + length, null, flags); 14910 } 14911 14912 if (drawBottom) { 14913 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 14914 } 14915 14916 if (drawLeft) { 14917 canvas.saveLayer(left, top, left + length, bottom, null, flags); 14918 } 14919 14920 if (drawRight) { 14921 canvas.saveLayer(right - length, top, right, bottom, null, flags); 14922 } 14923 } else { 14924 scrollabilityCache.setFadeColor(solidColor); 14925 } 14926 14927 // Step 3, draw the content 14928 if (!dirtyOpaque) onDraw(canvas); 14929 14930 // Step 4, draw the children 14931 dispatchDraw(canvas); 14932 14933 // Step 5, draw the fade effect and restore layers 14934 final Paint p = scrollabilityCache.paint; 14935 final Matrix matrix = scrollabilityCache.matrix; 14936 final Shader fade = scrollabilityCache.shader; 14937 14938 if (drawTop) { 14939 matrix.setScale(1, fadeHeight * topFadeStrength); 14940 matrix.postTranslate(left, top); 14941 fade.setLocalMatrix(matrix); 14942 p.setShader(fade); 14943 canvas.drawRect(left, top, right, top + length, p); 14944 } 14945 14946 if (drawBottom) { 14947 matrix.setScale(1, fadeHeight * bottomFadeStrength); 14948 matrix.postRotate(180); 14949 matrix.postTranslate(left, bottom); 14950 fade.setLocalMatrix(matrix); 14951 p.setShader(fade); 14952 canvas.drawRect(left, bottom - length, right, bottom, p); 14953 } 14954 14955 if (drawLeft) { 14956 matrix.setScale(1, fadeHeight * leftFadeStrength); 14957 matrix.postRotate(-90); 14958 matrix.postTranslate(left, top); 14959 fade.setLocalMatrix(matrix); 14960 p.setShader(fade); 14961 canvas.drawRect(left, top, left + length, bottom, p); 14962 } 14963 14964 if (drawRight) { 14965 matrix.setScale(1, fadeHeight * rightFadeStrength); 14966 matrix.postRotate(90); 14967 matrix.postTranslate(right, top); 14968 fade.setLocalMatrix(matrix); 14969 p.setShader(fade); 14970 canvas.drawRect(right - length, top, right, bottom, p); 14971 } 14972 14973 canvas.restoreToCount(saveCount); 14974 14975 // Step 6, draw decorations (scrollbars) 14976 onDrawScrollBars(canvas); 14977 14978 if (mOverlay != null && !mOverlay.isEmpty()) { 14979 mOverlay.getOverlayView().dispatchDraw(canvas); 14980 } 14981 } 14982 14983 /** 14984 * Draws the background onto the specified canvas. 14985 * 14986 * @param canvas Canvas on which to draw the background 14987 */ 14988 private void drawBackground(Canvas canvas) { 14989 final Drawable background = mBackground; 14990 if (background == null) { 14991 return; 14992 } 14993 14994 if (mBackgroundSizeChanged) { 14995 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 14996 mBackgroundSizeChanged = false; 14997 invalidateOutline(); 14998 } 14999 15000 // Attempt to use a display list if requested. 15001 if (canvas.isHardwareAccelerated() && mAttachInfo != null 15002 && mAttachInfo.mHardwareRenderer != null) { 15003 mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode); 15004 15005 final RenderNode displayList = mBackgroundRenderNode; 15006 if (displayList != null && displayList.isValid()) { 15007 setBackgroundDisplayListProperties(displayList); 15008 ((HardwareCanvas) canvas).drawRenderNode(displayList); 15009 return; 15010 } 15011 } 15012 15013 final int scrollX = mScrollX; 15014 final int scrollY = mScrollY; 15015 if ((scrollX | scrollY) == 0) { 15016 background.draw(canvas); 15017 } else { 15018 canvas.translate(scrollX, scrollY); 15019 background.draw(canvas); 15020 canvas.translate(-scrollX, -scrollY); 15021 } 15022 } 15023 15024 /** 15025 * Set up background drawable display list properties. 15026 * 15027 * @param displayList Valid display list for the background drawable 15028 */ 15029 private void setBackgroundDisplayListProperties(RenderNode displayList) { 15030 displayList.setTranslationX(mScrollX); 15031 displayList.setTranslationY(mScrollY); 15032 } 15033 15034 /** 15035 * Creates a new display list or updates the existing display list for the 15036 * specified Drawable. 15037 * 15038 * @param drawable Drawable for which to create a display list 15039 * @param renderNode Existing RenderNode, or {@code null} 15040 * @return A valid display list for the specified drawable 15041 */ 15042 private static RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) { 15043 if (renderNode == null) { 15044 renderNode = RenderNode.create(drawable.getClass().getName()); 15045 } 15046 15047 final Rect bounds = drawable.getBounds(); 15048 final int width = bounds.width(); 15049 final int height = bounds.height(); 15050 final HardwareCanvas canvas = renderNode.start(width, height); 15051 try { 15052 drawable.draw(canvas); 15053 } finally { 15054 renderNode.end(canvas); 15055 } 15056 15057 // Set up drawable properties that are view-independent. 15058 renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom); 15059 renderNode.setProjectBackwards(drawable.isProjected()); 15060 renderNode.setProjectionReceiver(true); 15061 renderNode.setClipToBounds(false); 15062 return renderNode; 15063 } 15064 15065 /** 15066 * Returns the overlay for this view, creating it if it does not yet exist. 15067 * Adding drawables to the overlay will cause them to be displayed whenever 15068 * the view itself is redrawn. Objects in the overlay should be actively 15069 * managed: remove them when they should not be displayed anymore. The 15070 * overlay will always have the same size as its host view. 15071 * 15072 * <p>Note: Overlays do not currently work correctly with {@link 15073 * SurfaceView} or {@link TextureView}; contents in overlays for these 15074 * types of views may not display correctly.</p> 15075 * 15076 * @return The ViewOverlay object for this view. 15077 * @see ViewOverlay 15078 */ 15079 public ViewOverlay getOverlay() { 15080 if (mOverlay == null) { 15081 mOverlay = new ViewOverlay(mContext, this); 15082 } 15083 return mOverlay; 15084 } 15085 15086 /** 15087 * Override this if your view is known to always be drawn on top of a solid color background, 15088 * and needs to draw fading edges. Returning a non-zero color enables the view system to 15089 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 15090 * should be set to 0xFF. 15091 * 15092 * @see #setVerticalFadingEdgeEnabled(boolean) 15093 * @see #setHorizontalFadingEdgeEnabled(boolean) 15094 * 15095 * @return The known solid color background for this view, or 0 if the color may vary 15096 */ 15097 @ViewDebug.ExportedProperty(category = "drawing") 15098 public int getSolidColor() { 15099 return 0; 15100 } 15101 15102 /** 15103 * Build a human readable string representation of the specified view flags. 15104 * 15105 * @param flags the view flags to convert to a string 15106 * @return a String representing the supplied flags 15107 */ 15108 private static String printFlags(int flags) { 15109 String output = ""; 15110 int numFlags = 0; 15111 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 15112 output += "TAKES_FOCUS"; 15113 numFlags++; 15114 } 15115 15116 switch (flags & VISIBILITY_MASK) { 15117 case INVISIBLE: 15118 if (numFlags > 0) { 15119 output += " "; 15120 } 15121 output += "INVISIBLE"; 15122 // USELESS HERE numFlags++; 15123 break; 15124 case GONE: 15125 if (numFlags > 0) { 15126 output += " "; 15127 } 15128 output += "GONE"; 15129 // USELESS HERE numFlags++; 15130 break; 15131 default: 15132 break; 15133 } 15134 return output; 15135 } 15136 15137 /** 15138 * Build a human readable string representation of the specified private 15139 * view flags. 15140 * 15141 * @param privateFlags the private view flags to convert to a string 15142 * @return a String representing the supplied flags 15143 */ 15144 private static String printPrivateFlags(int privateFlags) { 15145 String output = ""; 15146 int numFlags = 0; 15147 15148 if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) { 15149 output += "WANTS_FOCUS"; 15150 numFlags++; 15151 } 15152 15153 if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) { 15154 if (numFlags > 0) { 15155 output += " "; 15156 } 15157 output += "FOCUSED"; 15158 numFlags++; 15159 } 15160 15161 if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) { 15162 if (numFlags > 0) { 15163 output += " "; 15164 } 15165 output += "SELECTED"; 15166 numFlags++; 15167 } 15168 15169 if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) { 15170 if (numFlags > 0) { 15171 output += " "; 15172 } 15173 output += "IS_ROOT_NAMESPACE"; 15174 numFlags++; 15175 } 15176 15177 if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) { 15178 if (numFlags > 0) { 15179 output += " "; 15180 } 15181 output += "HAS_BOUNDS"; 15182 numFlags++; 15183 } 15184 15185 if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) { 15186 if (numFlags > 0) { 15187 output += " "; 15188 } 15189 output += "DRAWN"; 15190 // USELESS HERE numFlags++; 15191 } 15192 return output; 15193 } 15194 15195 /** 15196 * <p>Indicates whether or not this view's layout will be requested during 15197 * the next hierarchy layout pass.</p> 15198 * 15199 * @return true if the layout will be forced during next layout pass 15200 */ 15201 public boolean isLayoutRequested() { 15202 return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 15203 } 15204 15205 /** 15206 * Return true if o is a ViewGroup that is laying out using optical bounds. 15207 * @hide 15208 */ 15209 public static boolean isLayoutModeOptical(Object o) { 15210 return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical(); 15211 } 15212 15213 private boolean setOpticalFrame(int left, int top, int right, int bottom) { 15214 Insets parentInsets = mParent instanceof View ? 15215 ((View) mParent).getOpticalInsets() : Insets.NONE; 15216 Insets childInsets = getOpticalInsets(); 15217 return setFrame( 15218 left + parentInsets.left - childInsets.left, 15219 top + parentInsets.top - childInsets.top, 15220 right + parentInsets.left + childInsets.right, 15221 bottom + parentInsets.top + childInsets.bottom); 15222 } 15223 15224 /** 15225 * Assign a size and position to a view and all of its 15226 * descendants 15227 * 15228 * <p>This is the second phase of the layout mechanism. 15229 * (The first is measuring). In this phase, each parent calls 15230 * layout on all of its children to position them. 15231 * This is typically done using the child measurements 15232 * that were stored in the measure pass().</p> 15233 * 15234 * <p>Derived classes should not override this method. 15235 * Derived classes with children should override 15236 * onLayout. In that method, they should 15237 * call layout on each of their children.</p> 15238 * 15239 * @param l Left position, relative to parent 15240 * @param t Top position, relative to parent 15241 * @param r Right position, relative to parent 15242 * @param b Bottom position, relative to parent 15243 */ 15244 @SuppressWarnings({"unchecked"}) 15245 public void layout(int l, int t, int r, int b) { 15246 if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) { 15247 onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec); 15248 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 15249 } 15250 15251 int oldL = mLeft; 15252 int oldT = mTop; 15253 int oldB = mBottom; 15254 int oldR = mRight; 15255 15256 boolean changed = isLayoutModeOptical(mParent) ? 15257 setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b); 15258 15259 if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) { 15260 onLayout(changed, l, t, r, b); 15261 mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED; 15262 15263 ListenerInfo li = mListenerInfo; 15264 if (li != null && li.mOnLayoutChangeListeners != null) { 15265 ArrayList<OnLayoutChangeListener> listenersCopy = 15266 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 15267 int numListeners = listenersCopy.size(); 15268 for (int i = 0; i < numListeners; ++i) { 15269 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 15270 } 15271 } 15272 } 15273 15274 mPrivateFlags &= ~PFLAG_FORCE_LAYOUT; 15275 mPrivateFlags3 |= PFLAG3_IS_LAID_OUT; 15276 } 15277 15278 /** 15279 * Called from layout when this view should 15280 * assign a size and position to each of its children. 15281 * 15282 * Derived classes with children should override 15283 * this method and call layout on each of 15284 * their children. 15285 * @param changed This is a new size or position for this view 15286 * @param left Left position, relative to parent 15287 * @param top Top position, relative to parent 15288 * @param right Right position, relative to parent 15289 * @param bottom Bottom position, relative to parent 15290 */ 15291 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 15292 } 15293 15294 /** 15295 * Assign a size and position to this view. 15296 * 15297 * This is called from layout. 15298 * 15299 * @param left Left position, relative to parent 15300 * @param top Top position, relative to parent 15301 * @param right Right position, relative to parent 15302 * @param bottom Bottom position, relative to parent 15303 * @return true if the new size and position are different than the 15304 * previous ones 15305 * {@hide} 15306 */ 15307 protected boolean setFrame(int left, int top, int right, int bottom) { 15308 boolean changed = false; 15309 15310 if (DBG) { 15311 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 15312 + right + "," + bottom + ")"); 15313 } 15314 15315 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 15316 changed = true; 15317 15318 // Remember our drawn bit 15319 int drawn = mPrivateFlags & PFLAG_DRAWN; 15320 15321 int oldWidth = mRight - mLeft; 15322 int oldHeight = mBottom - mTop; 15323 int newWidth = right - left; 15324 int newHeight = bottom - top; 15325 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 15326 15327 // Invalidate our old position 15328 invalidate(sizeChanged); 15329 15330 mLeft = left; 15331 mTop = top; 15332 mRight = right; 15333 mBottom = bottom; 15334 mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 15335 15336 mPrivateFlags |= PFLAG_HAS_BOUNDS; 15337 15338 15339 if (sizeChanged) { 15340 sizeChange(newWidth, newHeight, oldWidth, oldHeight); 15341 } 15342 15343 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) { 15344 // If we are visible, force the DRAWN bit to on so that 15345 // this invalidate will go through (at least to our parent). 15346 // This is because someone may have invalidated this view 15347 // before this call to setFrame came in, thereby clearing 15348 // the DRAWN bit. 15349 mPrivateFlags |= PFLAG_DRAWN; 15350 invalidate(sizeChanged); 15351 // parent display list may need to be recreated based on a change in the bounds 15352 // of any child 15353 invalidateParentCaches(); 15354 } 15355 15356 // Reset drawn bit to original value (invalidate turns it off) 15357 mPrivateFlags |= drawn; 15358 15359 mBackgroundSizeChanged = true; 15360 15361 notifySubtreeAccessibilityStateChangedIfNeeded(); 15362 } 15363 return changed; 15364 } 15365 15366 private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) { 15367 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 15368 if (mOverlay != null) { 15369 mOverlay.getOverlayView().setRight(newWidth); 15370 mOverlay.getOverlayView().setBottom(newHeight); 15371 } 15372 invalidateOutline(); 15373 } 15374 15375 /** 15376 * Finalize inflating a view from XML. This is called as the last phase 15377 * of inflation, after all child views have been added. 15378 * 15379 * <p>Even if the subclass overrides onFinishInflate, they should always be 15380 * sure to call the super method, so that we get called. 15381 */ 15382 protected void onFinishInflate() { 15383 } 15384 15385 /** 15386 * Returns the resources associated with this view. 15387 * 15388 * @return Resources object. 15389 */ 15390 public Resources getResources() { 15391 return mResources; 15392 } 15393 15394 /** 15395 * Invalidates the specified Drawable. 15396 * 15397 * @param drawable the drawable to invalidate 15398 */ 15399 @Override 15400 public void invalidateDrawable(@NonNull Drawable drawable) { 15401 if (verifyDrawable(drawable)) { 15402 final Rect dirty = drawable.getDirtyBounds(); 15403 final int scrollX = mScrollX; 15404 final int scrollY = mScrollY; 15405 15406 invalidate(dirty.left + scrollX, dirty.top + scrollY, 15407 dirty.right + scrollX, dirty.bottom + scrollY); 15408 15409 invalidateOutline(); 15410 } 15411 } 15412 15413 /** 15414 * Schedules an action on a drawable to occur at a specified time. 15415 * 15416 * @param who the recipient of the action 15417 * @param what the action to run on the drawable 15418 * @param when the time at which the action must occur. Uses the 15419 * {@link SystemClock#uptimeMillis} timebase. 15420 */ 15421 @Override 15422 public void scheduleDrawable(Drawable who, Runnable what, long when) { 15423 if (verifyDrawable(who) && what != null) { 15424 final long delay = when - SystemClock.uptimeMillis(); 15425 if (mAttachInfo != null) { 15426 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 15427 Choreographer.CALLBACK_ANIMATION, what, who, 15428 Choreographer.subtractFrameDelay(delay)); 15429 } else { 15430 ViewRootImpl.getRunQueue().postDelayed(what, delay); 15431 } 15432 } 15433 } 15434 15435 /** 15436 * Cancels a scheduled action on a drawable. 15437 * 15438 * @param who the recipient of the action 15439 * @param what the action to cancel 15440 */ 15441 @Override 15442 public void unscheduleDrawable(Drawable who, Runnable what) { 15443 if (verifyDrawable(who) && what != null) { 15444 if (mAttachInfo != null) { 15445 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 15446 Choreographer.CALLBACK_ANIMATION, what, who); 15447 } 15448 ViewRootImpl.getRunQueue().removeCallbacks(what); 15449 } 15450 } 15451 15452 /** 15453 * Unschedule any events associated with the given Drawable. This can be 15454 * used when selecting a new Drawable into a view, so that the previous 15455 * one is completely unscheduled. 15456 * 15457 * @param who The Drawable to unschedule. 15458 * 15459 * @see #drawableStateChanged 15460 */ 15461 public void unscheduleDrawable(Drawable who) { 15462 if (mAttachInfo != null && who != null) { 15463 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 15464 Choreographer.CALLBACK_ANIMATION, null, who); 15465 } 15466 } 15467 15468 /** 15469 * Resolve the Drawables depending on the layout direction. This is implicitly supposing 15470 * that the View directionality can and will be resolved before its Drawables. 15471 * 15472 * Will call {@link View#onResolveDrawables} when resolution is done. 15473 * 15474 * @hide 15475 */ 15476 protected void resolveDrawables() { 15477 // Drawables resolution may need to happen before resolving the layout direction (which is 15478 // done only during the measure() call). 15479 // If the layout direction is not resolved yet, we cannot resolve the Drawables except in 15480 // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT. 15481 // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or 15482 // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout 15483 // direction to be resolved as its resolved value will be the same as its raw value. 15484 if (!isLayoutDirectionResolved() && 15485 getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) { 15486 return; 15487 } 15488 15489 final int layoutDirection = isLayoutDirectionResolved() ? 15490 getLayoutDirection() : getRawLayoutDirection(); 15491 15492 if (mBackground != null) { 15493 mBackground.setLayoutDirection(layoutDirection); 15494 } 15495 mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED; 15496 onResolveDrawables(layoutDirection); 15497 } 15498 15499 /** 15500 * Called when layout direction has been resolved. 15501 * 15502 * The default implementation does nothing. 15503 * 15504 * @param layoutDirection The resolved layout direction. 15505 * 15506 * @see #LAYOUT_DIRECTION_LTR 15507 * @see #LAYOUT_DIRECTION_RTL 15508 * 15509 * @hide 15510 */ 15511 public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) { 15512 } 15513 15514 /** 15515 * @hide 15516 */ 15517 protected void resetResolvedDrawables() { 15518 mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED; 15519 } 15520 15521 private boolean isDrawablesResolved() { 15522 return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED; 15523 } 15524 15525 /** 15526 * If your view subclass is displaying its own Drawable objects, it should 15527 * override this function and return true for any Drawable it is 15528 * displaying. This allows animations for those drawables to be 15529 * scheduled. 15530 * 15531 * <p>Be sure to call through to the super class when overriding this 15532 * function. 15533 * 15534 * @param who The Drawable to verify. Return true if it is one you are 15535 * displaying, else return the result of calling through to the 15536 * super class. 15537 * 15538 * @return boolean If true than the Drawable is being displayed in the 15539 * view; else false and it is not allowed to animate. 15540 * 15541 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 15542 * @see #drawableStateChanged() 15543 */ 15544 protected boolean verifyDrawable(Drawable who) { 15545 return who == mBackground; 15546 } 15547 15548 /** 15549 * This function is called whenever the state of the view changes in such 15550 * a way that it impacts the state of drawables being shown. 15551 * <p> 15552 * If the View has a StateListAnimator, it will also be called to run necessary state 15553 * change animations. 15554 * <p> 15555 * Be sure to call through to the superclass when overriding this function. 15556 * 15557 * @see Drawable#setState(int[]) 15558 */ 15559 protected void drawableStateChanged() { 15560 final Drawable d = mBackground; 15561 if (d != null && d.isStateful()) { 15562 d.setState(getDrawableState()); 15563 } 15564 15565 if (mStateListAnimator != null) { 15566 mStateListAnimator.setState(getDrawableState()); 15567 } 15568 } 15569 15570 /** 15571 * This function is called whenever the drawable hotspot changes. 15572 * <p> 15573 * Be sure to call through to the superclass when overriding this function. 15574 * 15575 * @param x hotspot x coordinate 15576 * @param y hotspot y coordinate 15577 */ 15578 public void drawableHotspotChanged(float x, float y) { 15579 if (mBackground != null) { 15580 mBackground.setHotspot(x, y); 15581 } 15582 } 15583 15584 /** 15585 * Call this to force a view to update its drawable state. This will cause 15586 * drawableStateChanged to be called on this view. Views that are interested 15587 * in the new state should call getDrawableState. 15588 * 15589 * @see #drawableStateChanged 15590 * @see #getDrawableState 15591 */ 15592 public void refreshDrawableState() { 15593 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 15594 drawableStateChanged(); 15595 15596 ViewParent parent = mParent; 15597 if (parent != null) { 15598 parent.childDrawableStateChanged(this); 15599 } 15600 } 15601 15602 /** 15603 * Return an array of resource IDs of the drawable states representing the 15604 * current state of the view. 15605 * 15606 * @return The current drawable state 15607 * 15608 * @see Drawable#setState(int[]) 15609 * @see #drawableStateChanged() 15610 * @see #onCreateDrawableState(int) 15611 */ 15612 public final int[] getDrawableState() { 15613 if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) { 15614 return mDrawableState; 15615 } else { 15616 mDrawableState = onCreateDrawableState(0); 15617 mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY; 15618 return mDrawableState; 15619 } 15620 } 15621 15622 /** 15623 * Generate the new {@link android.graphics.drawable.Drawable} state for 15624 * this view. This is called by the view 15625 * system when the cached Drawable state is determined to be invalid. To 15626 * retrieve the current state, you should use {@link #getDrawableState}. 15627 * 15628 * @param extraSpace if non-zero, this is the number of extra entries you 15629 * would like in the returned array in which you can place your own 15630 * states. 15631 * 15632 * @return Returns an array holding the current {@link Drawable} state of 15633 * the view. 15634 * 15635 * @see #mergeDrawableStates(int[], int[]) 15636 */ 15637 protected int[] onCreateDrawableState(int extraSpace) { 15638 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 15639 mParent instanceof View) { 15640 return ((View) mParent).onCreateDrawableState(extraSpace); 15641 } 15642 15643 int[] drawableState; 15644 15645 int privateFlags = mPrivateFlags; 15646 15647 int viewStateIndex = 0; 15648 if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED; 15649 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED; 15650 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED; 15651 if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED; 15652 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED; 15653 if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED; 15654 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 15655 HardwareRenderer.isAvailable()) { 15656 // This is set if HW acceleration is requested, even if the current 15657 // process doesn't allow it. This is just to allow app preview 15658 // windows to better match their app. 15659 viewStateIndex |= VIEW_STATE_ACCELERATED; 15660 } 15661 if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED; 15662 15663 final int privateFlags2 = mPrivateFlags2; 15664 if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT; 15665 if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED; 15666 15667 drawableState = VIEW_STATE_SETS[viewStateIndex]; 15668 15669 //noinspection ConstantIfStatement 15670 if (false) { 15671 Log.i("View", "drawableStateIndex=" + viewStateIndex); 15672 Log.i("View", toString() 15673 + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0) 15674 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 15675 + " fo=" + hasFocus() 15676 + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0) 15677 + " wf=" + hasWindowFocus() 15678 + ": " + Arrays.toString(drawableState)); 15679 } 15680 15681 if (extraSpace == 0) { 15682 return drawableState; 15683 } 15684 15685 final int[] fullState; 15686 if (drawableState != null) { 15687 fullState = new int[drawableState.length + extraSpace]; 15688 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 15689 } else { 15690 fullState = new int[extraSpace]; 15691 } 15692 15693 return fullState; 15694 } 15695 15696 /** 15697 * Merge your own state values in <var>additionalState</var> into the base 15698 * state values <var>baseState</var> that were returned by 15699 * {@link #onCreateDrawableState(int)}. 15700 * 15701 * @param baseState The base state values returned by 15702 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 15703 * own additional state values. 15704 * 15705 * @param additionalState The additional state values you would like 15706 * added to <var>baseState</var>; this array is not modified. 15707 * 15708 * @return As a convenience, the <var>baseState</var> array you originally 15709 * passed into the function is returned. 15710 * 15711 * @see #onCreateDrawableState(int) 15712 */ 15713 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 15714 final int N = baseState.length; 15715 int i = N - 1; 15716 while (i >= 0 && baseState[i] == 0) { 15717 i--; 15718 } 15719 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 15720 return baseState; 15721 } 15722 15723 /** 15724 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 15725 * on all Drawable objects associated with this view. 15726 * <p> 15727 * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator 15728 * attached to this view. 15729 */ 15730 public void jumpDrawablesToCurrentState() { 15731 if (mBackground != null) { 15732 mBackground.jumpToCurrentState(); 15733 } 15734 if (mStateListAnimator != null) { 15735 mStateListAnimator.jumpToCurrentState(); 15736 } 15737 } 15738 15739 /** 15740 * Sets the background color for this view. 15741 * @param color the color of the background 15742 */ 15743 @RemotableViewMethod 15744 public void setBackgroundColor(int color) { 15745 if (mBackground instanceof ColorDrawable) { 15746 ((ColorDrawable) mBackground.mutate()).setColor(color); 15747 computeOpaqueFlags(); 15748 mBackgroundResource = 0; 15749 } else { 15750 setBackground(new ColorDrawable(color)); 15751 } 15752 } 15753 15754 /** 15755 * Set the background to a given resource. The resource should refer to 15756 * a Drawable object or 0 to remove the background. 15757 * @param resid The identifier of the resource. 15758 * 15759 * @attr ref android.R.styleable#View_background 15760 */ 15761 @RemotableViewMethod 15762 public void setBackgroundResource(int resid) { 15763 if (resid != 0 && resid == mBackgroundResource) { 15764 return; 15765 } 15766 15767 Drawable d = null; 15768 if (resid != 0) { 15769 d = mContext.getDrawable(resid); 15770 } 15771 setBackground(d); 15772 15773 mBackgroundResource = resid; 15774 } 15775 15776 /** 15777 * Set the background to a given Drawable, or remove the background. If the 15778 * background has padding, this View's padding is set to the background's 15779 * padding. However, when a background is removed, this View's padding isn't 15780 * touched. If setting the padding is desired, please use 15781 * {@link #setPadding(int, int, int, int)}. 15782 * 15783 * @param background The Drawable to use as the background, or null to remove the 15784 * background 15785 */ 15786 public void setBackground(Drawable background) { 15787 //noinspection deprecation 15788 setBackgroundDrawable(background); 15789 } 15790 15791 /** 15792 * @deprecated use {@link #setBackground(Drawable)} instead 15793 */ 15794 @Deprecated 15795 public void setBackgroundDrawable(Drawable background) { 15796 computeOpaqueFlags(); 15797 15798 if (background == mBackground) { 15799 return; 15800 } 15801 15802 boolean requestLayout = false; 15803 15804 mBackgroundResource = 0; 15805 15806 /* 15807 * Regardless of whether we're setting a new background or not, we want 15808 * to clear the previous drawable. 15809 */ 15810 if (mBackground != null) { 15811 mBackground.setCallback(null); 15812 unscheduleDrawable(mBackground); 15813 } 15814 15815 if (background != null) { 15816 Rect padding = sThreadLocal.get(); 15817 if (padding == null) { 15818 padding = new Rect(); 15819 sThreadLocal.set(padding); 15820 } 15821 resetResolvedDrawables(); 15822 background.setLayoutDirection(getLayoutDirection()); 15823 if (background.getPadding(padding)) { 15824 resetResolvedPadding(); 15825 switch (background.getLayoutDirection()) { 15826 case LAYOUT_DIRECTION_RTL: 15827 mUserPaddingLeftInitial = padding.right; 15828 mUserPaddingRightInitial = padding.left; 15829 internalSetPadding(padding.right, padding.top, padding.left, padding.bottom); 15830 break; 15831 case LAYOUT_DIRECTION_LTR: 15832 default: 15833 mUserPaddingLeftInitial = padding.left; 15834 mUserPaddingRightInitial = padding.right; 15835 internalSetPadding(padding.left, padding.top, padding.right, padding.bottom); 15836 } 15837 mLeftPaddingDefined = false; 15838 mRightPaddingDefined = false; 15839 } 15840 15841 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 15842 // if it has a different minimum size, we should layout again 15843 if (mBackground == null 15844 || mBackground.getMinimumHeight() != background.getMinimumHeight() 15845 || mBackground.getMinimumWidth() != background.getMinimumWidth()) { 15846 requestLayout = true; 15847 } 15848 15849 background.setCallback(this); 15850 if (background.isStateful()) { 15851 background.setState(getDrawableState()); 15852 } 15853 background.setVisible(getVisibility() == VISIBLE, false); 15854 mBackground = background; 15855 15856 applyBackgroundTint(); 15857 15858 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 15859 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 15860 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 15861 requestLayout = true; 15862 } 15863 } else { 15864 /* Remove the background */ 15865 mBackground = null; 15866 15867 if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) { 15868 /* 15869 * This view ONLY drew the background before and we're removing 15870 * the background, so now it won't draw anything 15871 * (hence we SKIP_DRAW) 15872 */ 15873 mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND; 15874 mPrivateFlags |= PFLAG_SKIP_DRAW; 15875 } 15876 15877 /* 15878 * When the background is set, we try to apply its padding to this 15879 * View. When the background is removed, we don't touch this View's 15880 * padding. This is noted in the Javadocs. Hence, we don't need to 15881 * requestLayout(), the invalidate() below is sufficient. 15882 */ 15883 15884 // The old background's minimum size could have affected this 15885 // View's layout, so let's requestLayout 15886 requestLayout = true; 15887 } 15888 15889 computeOpaqueFlags(); 15890 15891 if (requestLayout) { 15892 requestLayout(); 15893 } 15894 15895 mBackgroundSizeChanged = true; 15896 invalidate(true); 15897 } 15898 15899 /** 15900 * Gets the background drawable 15901 * 15902 * @return The drawable used as the background for this view, if any. 15903 * 15904 * @see #setBackground(Drawable) 15905 * 15906 * @attr ref android.R.styleable#View_background 15907 */ 15908 public Drawable getBackground() { 15909 return mBackground; 15910 } 15911 15912 /** 15913 * Applies a tint to the background drawable. 15914 * <p> 15915 * Subsequent calls to {@link #setBackground(Drawable)} will automatically 15916 * mutate the drawable and apply the specified tint and tint mode using 15917 * {@link Drawable#setTint(ColorStateList, PorterDuff.Mode)}. 15918 * 15919 * @param tint the tint to apply, may be {@code null} to clear tint 15920 * @param tintMode the blending mode used to apply the tint, may be 15921 * {@code null} to clear tint 15922 * 15923 * @attr ref android.R.styleable#View_backgroundTint 15924 * @attr ref android.R.styleable#View_backgroundTintMode 15925 * @see Drawable#setTint(ColorStateList, PorterDuff.Mode) 15926 */ 15927 private void setBackgroundTint(@Nullable ColorStateList tint, 15928 @Nullable PorterDuff.Mode tintMode) { 15929 mBackgroundTint = tint; 15930 mBackgroundTintMode = tintMode; 15931 mHasBackgroundTint = true; 15932 15933 applyBackgroundTint(); 15934 } 15935 15936 /** 15937 * Applies a tint to the background drawable. Does not modify the current tint 15938 * mode, which is {@link PorterDuff.Mode#SRC_ATOP} by default. 15939 * <p> 15940 * Subsequent calls to {@link #setBackground(Drawable)} will automatically 15941 * mutate the drawable and apply the specified tint and tint mode using 15942 * {@link Drawable#setTint(ColorStateList, PorterDuff.Mode)}. 15943 * 15944 * @param tint the tint to apply, may be {@code null} to clear tint 15945 * 15946 * @attr ref android.R.styleable#View_backgroundTint 15947 * @see #setBackgroundTint(ColorStateList, PorterDuff.Mode) 15948 */ 15949 public void setBackgroundTint(@Nullable ColorStateList tint) { 15950 setBackgroundTint(tint, mBackgroundTintMode); 15951 } 15952 15953 /** 15954 * @return the tint applied to the background drawable 15955 * @attr ref android.R.styleable#View_backgroundTint 15956 * @see #setBackgroundTint(ColorStateList, PorterDuff.Mode) 15957 */ 15958 @Nullable 15959 public ColorStateList getBackgroundTint() { 15960 return mBackgroundTint; 15961 } 15962 15963 /** 15964 * Specifies the blending mode used to apply the tint specified by 15965 * {@link #setBackgroundTint(ColorStateList)}} to the background drawable. 15966 * The default mode is {@link PorterDuff.Mode#SRC_ATOP}. 15967 * 15968 * @param tintMode the blending mode used to apply the tint, may be 15969 * {@code null} to clear tint 15970 * @attr ref android.R.styleable#View_backgroundTintMode 15971 * @see #setBackgroundTint(ColorStateList) 15972 */ 15973 public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) { 15974 setBackgroundTint(mBackgroundTint, tintMode); 15975 } 15976 15977 /** 15978 * @return the blending mode used to apply the tint to the background drawable 15979 * @attr ref android.R.styleable#View_backgroundTintMode 15980 * @see #setBackgroundTint(ColorStateList, PorterDuff.Mode) 15981 */ 15982 @Nullable 15983 public PorterDuff.Mode getBackgroundTintMode() { 15984 return mBackgroundTintMode; 15985 } 15986 15987 private void applyBackgroundTint() { 15988 if (mBackground != null && mHasBackgroundTint) { 15989 mBackground = mBackground.mutate(); 15990 mBackground.setTint(mBackgroundTint, mBackgroundTintMode); 15991 } 15992 } 15993 15994 /** 15995 * Sets the padding. The view may add on the space required to display 15996 * the scrollbars, depending on the style and visibility of the scrollbars. 15997 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 15998 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 15999 * from the values set in this call. 16000 * 16001 * @attr ref android.R.styleable#View_padding 16002 * @attr ref android.R.styleable#View_paddingBottom 16003 * @attr ref android.R.styleable#View_paddingLeft 16004 * @attr ref android.R.styleable#View_paddingRight 16005 * @attr ref android.R.styleable#View_paddingTop 16006 * @param left the left padding in pixels 16007 * @param top the top padding in pixels 16008 * @param right the right padding in pixels 16009 * @param bottom the bottom padding in pixels 16010 */ 16011 public void setPadding(int left, int top, int right, int bottom) { 16012 resetResolvedPadding(); 16013 16014 mUserPaddingStart = UNDEFINED_PADDING; 16015 mUserPaddingEnd = UNDEFINED_PADDING; 16016 16017 mUserPaddingLeftInitial = left; 16018 mUserPaddingRightInitial = right; 16019 16020 mLeftPaddingDefined = true; 16021 mRightPaddingDefined = true; 16022 16023 internalSetPadding(left, top, right, bottom); 16024 } 16025 16026 /** 16027 * @hide 16028 */ 16029 protected void internalSetPadding(int left, int top, int right, int bottom) { 16030 mUserPaddingLeft = left; 16031 mUserPaddingRight = right; 16032 mUserPaddingBottom = bottom; 16033 16034 final int viewFlags = mViewFlags; 16035 boolean changed = false; 16036 16037 // Common case is there are no scroll bars. 16038 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 16039 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 16040 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 16041 ? 0 : getVerticalScrollbarWidth(); 16042 switch (mVerticalScrollbarPosition) { 16043 case SCROLLBAR_POSITION_DEFAULT: 16044 if (isLayoutRtl()) { 16045 left += offset; 16046 } else { 16047 right += offset; 16048 } 16049 break; 16050 case SCROLLBAR_POSITION_RIGHT: 16051 right += offset; 16052 break; 16053 case SCROLLBAR_POSITION_LEFT: 16054 left += offset; 16055 break; 16056 } 16057 } 16058 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 16059 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 16060 ? 0 : getHorizontalScrollbarHeight(); 16061 } 16062 } 16063 16064 if (mPaddingLeft != left) { 16065 changed = true; 16066 mPaddingLeft = left; 16067 } 16068 if (mPaddingTop != top) { 16069 changed = true; 16070 mPaddingTop = top; 16071 } 16072 if (mPaddingRight != right) { 16073 changed = true; 16074 mPaddingRight = right; 16075 } 16076 if (mPaddingBottom != bottom) { 16077 changed = true; 16078 mPaddingBottom = bottom; 16079 } 16080 16081 if (changed) { 16082 requestLayout(); 16083 } 16084 } 16085 16086 /** 16087 * Sets the relative padding. The view may add on the space required to display 16088 * the scrollbars, depending on the style and visibility of the scrollbars. 16089 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 16090 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 16091 * from the values set in this call. 16092 * 16093 * @attr ref android.R.styleable#View_padding 16094 * @attr ref android.R.styleable#View_paddingBottom 16095 * @attr ref android.R.styleable#View_paddingStart 16096 * @attr ref android.R.styleable#View_paddingEnd 16097 * @attr ref android.R.styleable#View_paddingTop 16098 * @param start the start padding in pixels 16099 * @param top the top padding in pixels 16100 * @param end the end padding in pixels 16101 * @param bottom the bottom padding in pixels 16102 */ 16103 public void setPaddingRelative(int start, int top, int end, int bottom) { 16104 resetResolvedPadding(); 16105 16106 mUserPaddingStart = start; 16107 mUserPaddingEnd = end; 16108 mLeftPaddingDefined = true; 16109 mRightPaddingDefined = true; 16110 16111 switch(getLayoutDirection()) { 16112 case LAYOUT_DIRECTION_RTL: 16113 mUserPaddingLeftInitial = end; 16114 mUserPaddingRightInitial = start; 16115 internalSetPadding(end, top, start, bottom); 16116 break; 16117 case LAYOUT_DIRECTION_LTR: 16118 default: 16119 mUserPaddingLeftInitial = start; 16120 mUserPaddingRightInitial = end; 16121 internalSetPadding(start, top, end, bottom); 16122 } 16123 } 16124 16125 /** 16126 * Returns the top padding of this view. 16127 * 16128 * @return the top padding in pixels 16129 */ 16130 public int getPaddingTop() { 16131 return mPaddingTop; 16132 } 16133 16134 /** 16135 * Returns the bottom padding of this view. If there are inset and enabled 16136 * scrollbars, this value may include the space required to display the 16137 * scrollbars as well. 16138 * 16139 * @return the bottom padding in pixels 16140 */ 16141 public int getPaddingBottom() { 16142 return mPaddingBottom; 16143 } 16144 16145 /** 16146 * Returns the left padding of this view. If there are inset and enabled 16147 * scrollbars, this value may include the space required to display the 16148 * scrollbars as well. 16149 * 16150 * @return the left padding in pixels 16151 */ 16152 public int getPaddingLeft() { 16153 if (!isPaddingResolved()) { 16154 resolvePadding(); 16155 } 16156 return mPaddingLeft; 16157 } 16158 16159 /** 16160 * Returns the start padding of this view depending on its resolved layout direction. 16161 * If there are inset and enabled scrollbars, this value may include the space 16162 * required to display the scrollbars as well. 16163 * 16164 * @return the start padding in pixels 16165 */ 16166 public int getPaddingStart() { 16167 if (!isPaddingResolved()) { 16168 resolvePadding(); 16169 } 16170 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 16171 mPaddingRight : mPaddingLeft; 16172 } 16173 16174 /** 16175 * Returns the right padding of this view. If there are inset and enabled 16176 * scrollbars, this value may include the space required to display the 16177 * scrollbars as well. 16178 * 16179 * @return the right padding in pixels 16180 */ 16181 public int getPaddingRight() { 16182 if (!isPaddingResolved()) { 16183 resolvePadding(); 16184 } 16185 return mPaddingRight; 16186 } 16187 16188 /** 16189 * Returns the end padding of this view depending on its resolved layout direction. 16190 * If there are inset and enabled scrollbars, this value may include the space 16191 * required to display the scrollbars as well. 16192 * 16193 * @return the end padding in pixels 16194 */ 16195 public int getPaddingEnd() { 16196 if (!isPaddingResolved()) { 16197 resolvePadding(); 16198 } 16199 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 16200 mPaddingLeft : mPaddingRight; 16201 } 16202 16203 /** 16204 * Return if the padding as been set thru relative values 16205 * {@link #setPaddingRelative(int, int, int, int)} or thru 16206 * @attr ref android.R.styleable#View_paddingStart or 16207 * @attr ref android.R.styleable#View_paddingEnd 16208 * 16209 * @return true if the padding is relative or false if it is not. 16210 */ 16211 public boolean isPaddingRelative() { 16212 return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING); 16213 } 16214 16215 Insets computeOpticalInsets() { 16216 return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets(); 16217 } 16218 16219 /** 16220 * @hide 16221 */ 16222 public void resetPaddingToInitialValues() { 16223 if (isRtlCompatibilityMode()) { 16224 mPaddingLeft = mUserPaddingLeftInitial; 16225 mPaddingRight = mUserPaddingRightInitial; 16226 return; 16227 } 16228 if (isLayoutRtl()) { 16229 mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial; 16230 mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial; 16231 } else { 16232 mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial; 16233 mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial; 16234 } 16235 } 16236 16237 /** 16238 * @hide 16239 */ 16240 public Insets getOpticalInsets() { 16241 if (mLayoutInsets == null) { 16242 mLayoutInsets = computeOpticalInsets(); 16243 } 16244 return mLayoutInsets; 16245 } 16246 16247 /** 16248 * Set this view's optical insets. 16249 * 16250 * <p>This method should be treated similarly to setMeasuredDimension and not as a general 16251 * property. Views that compute their own optical insets should call it as part of measurement. 16252 * This method does not request layout. If you are setting optical insets outside of 16253 * measure/layout itself you will want to call requestLayout() yourself. 16254 * </p> 16255 * @hide 16256 */ 16257 public void setOpticalInsets(Insets insets) { 16258 mLayoutInsets = insets; 16259 } 16260 16261 /** 16262 * Changes the selection state of this view. A view can be selected or not. 16263 * Note that selection is not the same as focus. Views are typically 16264 * selected in the context of an AdapterView like ListView or GridView; 16265 * the selected view is the view that is highlighted. 16266 * 16267 * @param selected true if the view must be selected, false otherwise 16268 */ 16269 public void setSelected(boolean selected) { 16270 //noinspection DoubleNegation 16271 if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) { 16272 mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0); 16273 if (!selected) resetPressedState(); 16274 invalidate(true); 16275 refreshDrawableState(); 16276 dispatchSetSelected(selected); 16277 notifyViewAccessibilityStateChangedIfNeeded( 16278 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 16279 } 16280 } 16281 16282 /** 16283 * Dispatch setSelected to all of this View's children. 16284 * 16285 * @see #setSelected(boolean) 16286 * 16287 * @param selected The new selected state 16288 */ 16289 protected void dispatchSetSelected(boolean selected) { 16290 } 16291 16292 /** 16293 * Indicates the selection state of this view. 16294 * 16295 * @return true if the view is selected, false otherwise 16296 */ 16297 @ViewDebug.ExportedProperty 16298 public boolean isSelected() { 16299 return (mPrivateFlags & PFLAG_SELECTED) != 0; 16300 } 16301 16302 /** 16303 * Changes the activated state of this view. A view can be activated or not. 16304 * Note that activation is not the same as selection. Selection is 16305 * a transient property, representing the view (hierarchy) the user is 16306 * currently interacting with. Activation is a longer-term state that the 16307 * user can move views in and out of. For example, in a list view with 16308 * single or multiple selection enabled, the views in the current selection 16309 * set are activated. (Um, yeah, we are deeply sorry about the terminology 16310 * here.) The activated state is propagated down to children of the view it 16311 * is set on. 16312 * 16313 * @param activated true if the view must be activated, false otherwise 16314 */ 16315 public void setActivated(boolean activated) { 16316 //noinspection DoubleNegation 16317 if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) { 16318 mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0); 16319 invalidate(true); 16320 refreshDrawableState(); 16321 dispatchSetActivated(activated); 16322 } 16323 } 16324 16325 /** 16326 * Dispatch setActivated to all of this View's children. 16327 * 16328 * @see #setActivated(boolean) 16329 * 16330 * @param activated The new activated state 16331 */ 16332 protected void dispatchSetActivated(boolean activated) { 16333 } 16334 16335 /** 16336 * Indicates the activation state of this view. 16337 * 16338 * @return true if the view is activated, false otherwise 16339 */ 16340 @ViewDebug.ExportedProperty 16341 public boolean isActivated() { 16342 return (mPrivateFlags & PFLAG_ACTIVATED) != 0; 16343 } 16344 16345 /** 16346 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 16347 * observer can be used to get notifications when global events, like 16348 * layout, happen. 16349 * 16350 * The returned ViewTreeObserver observer is not guaranteed to remain 16351 * valid for the lifetime of this View. If the caller of this method keeps 16352 * a long-lived reference to ViewTreeObserver, it should always check for 16353 * the return value of {@link ViewTreeObserver#isAlive()}. 16354 * 16355 * @return The ViewTreeObserver for this view's hierarchy. 16356 */ 16357 public ViewTreeObserver getViewTreeObserver() { 16358 if (mAttachInfo != null) { 16359 return mAttachInfo.mTreeObserver; 16360 } 16361 if (mFloatingTreeObserver == null) { 16362 mFloatingTreeObserver = new ViewTreeObserver(); 16363 } 16364 return mFloatingTreeObserver; 16365 } 16366 16367 /** 16368 * <p>Finds the topmost view in the current view hierarchy.</p> 16369 * 16370 * @return the topmost view containing this view 16371 */ 16372 public View getRootView() { 16373 if (mAttachInfo != null) { 16374 final View v = mAttachInfo.mRootView; 16375 if (v != null) { 16376 return v; 16377 } 16378 } 16379 16380 View parent = this; 16381 16382 while (parent.mParent != null && parent.mParent instanceof View) { 16383 parent = (View) parent.mParent; 16384 } 16385 16386 return parent; 16387 } 16388 16389 /** 16390 * Transforms a motion event from view-local coordinates to on-screen 16391 * coordinates. 16392 * 16393 * @param ev the view-local motion event 16394 * @return false if the transformation could not be applied 16395 * @hide 16396 */ 16397 public boolean toGlobalMotionEvent(MotionEvent ev) { 16398 final AttachInfo info = mAttachInfo; 16399 if (info == null) { 16400 return false; 16401 } 16402 16403 final Matrix m = info.mTmpMatrix; 16404 m.set(Matrix.IDENTITY_MATRIX); 16405 transformMatrixToGlobal(m); 16406 ev.transform(m); 16407 return true; 16408 } 16409 16410 /** 16411 * Transforms a motion event from on-screen coordinates to view-local 16412 * coordinates. 16413 * 16414 * @param ev the on-screen motion event 16415 * @return false if the transformation could not be applied 16416 * @hide 16417 */ 16418 public boolean toLocalMotionEvent(MotionEvent ev) { 16419 final AttachInfo info = mAttachInfo; 16420 if (info == null) { 16421 return false; 16422 } 16423 16424 final Matrix m = info.mTmpMatrix; 16425 m.set(Matrix.IDENTITY_MATRIX); 16426 transformMatrixToLocal(m); 16427 ev.transform(m); 16428 return true; 16429 } 16430 16431 /** 16432 * Modifies the input matrix such that it maps view-local coordinates to 16433 * on-screen coordinates. 16434 * 16435 * @param m input matrix to modify 16436 */ 16437 void transformMatrixToGlobal(Matrix m) { 16438 final ViewParent parent = mParent; 16439 if (parent instanceof View) { 16440 final View vp = (View) parent; 16441 vp.transformMatrixToGlobal(m); 16442 m.postTranslate(-vp.mScrollX, -vp.mScrollY); 16443 } else if (parent instanceof ViewRootImpl) { 16444 final ViewRootImpl vr = (ViewRootImpl) parent; 16445 vr.transformMatrixToGlobal(m); 16446 m.postTranslate(0, -vr.mCurScrollY); 16447 } 16448 16449 m.postTranslate(mLeft, mTop); 16450 16451 if (!hasIdentityMatrix()) { 16452 m.postConcat(getMatrix()); 16453 } 16454 } 16455 16456 /** 16457 * Modifies the input matrix such that it maps on-screen coordinates to 16458 * view-local coordinates. 16459 * 16460 * @param m input matrix to modify 16461 */ 16462 void transformMatrixToLocal(Matrix m) { 16463 final ViewParent parent = mParent; 16464 if (parent instanceof View) { 16465 final View vp = (View) parent; 16466 vp.transformMatrixToLocal(m); 16467 m.preTranslate(vp.mScrollX, vp.mScrollY); 16468 } else if (parent instanceof ViewRootImpl) { 16469 final ViewRootImpl vr = (ViewRootImpl) parent; 16470 vr.transformMatrixToLocal(m); 16471 m.preTranslate(0, vr.mCurScrollY); 16472 } 16473 16474 m.preTranslate(-mLeft, -mTop); 16475 16476 if (!hasIdentityMatrix()) { 16477 m.preConcat(getInverseMatrix()); 16478 } 16479 } 16480 16481 /** 16482 * <p>Computes the coordinates of this view on the screen. The argument 16483 * must be an array of two integers. After the method returns, the array 16484 * contains the x and y location in that order.</p> 16485 * 16486 * @param location an array of two integers in which to hold the coordinates 16487 */ 16488 public void getLocationOnScreen(int[] location) { 16489 getLocationInWindow(location); 16490 16491 final AttachInfo info = mAttachInfo; 16492 if (info != null) { 16493 location[0] += info.mWindowLeft; 16494 location[1] += info.mWindowTop; 16495 } 16496 } 16497 16498 /** 16499 * <p>Computes the coordinates of this view in its window. The argument 16500 * must be an array of two integers. After the method returns, the array 16501 * contains the x and y location in that order.</p> 16502 * 16503 * @param location an array of two integers in which to hold the coordinates 16504 */ 16505 public void getLocationInWindow(int[] location) { 16506 if (location == null || location.length < 2) { 16507 throw new IllegalArgumentException("location must be an array of two integers"); 16508 } 16509 16510 if (mAttachInfo == null) { 16511 // When the view is not attached to a window, this method does not make sense 16512 location[0] = location[1] = 0; 16513 return; 16514 } 16515 16516 float[] position = mAttachInfo.mTmpTransformLocation; 16517 position[0] = position[1] = 0.0f; 16518 16519 if (!hasIdentityMatrix()) { 16520 getMatrix().mapPoints(position); 16521 } 16522 16523 position[0] += mLeft; 16524 position[1] += mTop; 16525 16526 ViewParent viewParent = mParent; 16527 while (viewParent instanceof View) { 16528 final View view = (View) viewParent; 16529 16530 position[0] -= view.mScrollX; 16531 position[1] -= view.mScrollY; 16532 16533 if (!view.hasIdentityMatrix()) { 16534 view.getMatrix().mapPoints(position); 16535 } 16536 16537 position[0] += view.mLeft; 16538 position[1] += view.mTop; 16539 16540 viewParent = view.mParent; 16541 } 16542 16543 if (viewParent instanceof ViewRootImpl) { 16544 // *cough* 16545 final ViewRootImpl vr = (ViewRootImpl) viewParent; 16546 position[1] -= vr.mCurScrollY; 16547 } 16548 16549 location[0] = (int) (position[0] + 0.5f); 16550 location[1] = (int) (position[1] + 0.5f); 16551 } 16552 16553 /** 16554 * {@hide} 16555 * @param id the id of the view to be found 16556 * @return the view of the specified id, null if cannot be found 16557 */ 16558 protected View findViewTraversal(int id) { 16559 if (id == mID) { 16560 return this; 16561 } 16562 return null; 16563 } 16564 16565 /** 16566 * {@hide} 16567 * @param tag the tag of the view to be found 16568 * @return the view of specified tag, null if cannot be found 16569 */ 16570 protected View findViewWithTagTraversal(Object tag) { 16571 if (tag != null && tag.equals(mTag)) { 16572 return this; 16573 } 16574 return null; 16575 } 16576 16577 /** 16578 * {@hide} 16579 * @param predicate The predicate to evaluate. 16580 * @param childToSkip If not null, ignores this child during the recursive traversal. 16581 * @return The first view that matches the predicate or null. 16582 */ 16583 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 16584 if (predicate.apply(this)) { 16585 return this; 16586 } 16587 return null; 16588 } 16589 16590 /** 16591 * Look for a child view with the given id. If this view has the given 16592 * id, return this view. 16593 * 16594 * @param id The id to search for. 16595 * @return The view that has the given id in the hierarchy or null 16596 */ 16597 public final View findViewById(int id) { 16598 if (id < 0) { 16599 return null; 16600 } 16601 return findViewTraversal(id); 16602 } 16603 16604 /** 16605 * Finds a view by its unuque and stable accessibility id. 16606 * 16607 * @param accessibilityId The searched accessibility id. 16608 * @return The found view. 16609 */ 16610 final View findViewByAccessibilityId(int accessibilityId) { 16611 if (accessibilityId < 0) { 16612 return null; 16613 } 16614 return findViewByAccessibilityIdTraversal(accessibilityId); 16615 } 16616 16617 /** 16618 * Performs the traversal to find a view by its unuque and stable accessibility id. 16619 * 16620 * <strong>Note:</strong>This method does not stop at the root namespace 16621 * boundary since the user can touch the screen at an arbitrary location 16622 * potentially crossing the root namespace bounday which will send an 16623 * accessibility event to accessibility services and they should be able 16624 * to obtain the event source. Also accessibility ids are guaranteed to be 16625 * unique in the window. 16626 * 16627 * @param accessibilityId The accessibility id. 16628 * @return The found view. 16629 * 16630 * @hide 16631 */ 16632 public View findViewByAccessibilityIdTraversal(int accessibilityId) { 16633 if (getAccessibilityViewId() == accessibilityId) { 16634 return this; 16635 } 16636 return null; 16637 } 16638 16639 /** 16640 * Look for a child view with the given tag. If this view has the given 16641 * tag, return this view. 16642 * 16643 * @param tag The tag to search for, using "tag.equals(getTag())". 16644 * @return The View that has the given tag in the hierarchy or null 16645 */ 16646 public final View findViewWithTag(Object tag) { 16647 if (tag == null) { 16648 return null; 16649 } 16650 return findViewWithTagTraversal(tag); 16651 } 16652 16653 /** 16654 * {@hide} 16655 * Look for a child view that matches the specified predicate. 16656 * If this view matches the predicate, return this view. 16657 * 16658 * @param predicate The predicate to evaluate. 16659 * @return The first view that matches the predicate or null. 16660 */ 16661 public final View findViewByPredicate(Predicate<View> predicate) { 16662 return findViewByPredicateTraversal(predicate, null); 16663 } 16664 16665 /** 16666 * {@hide} 16667 * Look for a child view that matches the specified predicate, 16668 * starting with the specified view and its descendents and then 16669 * recusively searching the ancestors and siblings of that view 16670 * until this view is reached. 16671 * 16672 * This method is useful in cases where the predicate does not match 16673 * a single unique view (perhaps multiple views use the same id) 16674 * and we are trying to find the view that is "closest" in scope to the 16675 * starting view. 16676 * 16677 * @param start The view to start from. 16678 * @param predicate The predicate to evaluate. 16679 * @return The first view that matches the predicate or null. 16680 */ 16681 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 16682 View childToSkip = null; 16683 for (;;) { 16684 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 16685 if (view != null || start == this) { 16686 return view; 16687 } 16688 16689 ViewParent parent = start.getParent(); 16690 if (parent == null || !(parent instanceof View)) { 16691 return null; 16692 } 16693 16694 childToSkip = start; 16695 start = (View) parent; 16696 } 16697 } 16698 16699 /** 16700 * Sets the identifier for this view. The identifier does not have to be 16701 * unique in this view's hierarchy. The identifier should be a positive 16702 * number. 16703 * 16704 * @see #NO_ID 16705 * @see #getId() 16706 * @see #findViewById(int) 16707 * 16708 * @param id a number used to identify the view 16709 * 16710 * @attr ref android.R.styleable#View_id 16711 */ 16712 public void setId(int id) { 16713 mID = id; 16714 if (mID == View.NO_ID && mLabelForId != View.NO_ID) { 16715 mID = generateViewId(); 16716 } 16717 } 16718 16719 /** 16720 * {@hide} 16721 * 16722 * @param isRoot true if the view belongs to the root namespace, false 16723 * otherwise 16724 */ 16725 public void setIsRootNamespace(boolean isRoot) { 16726 if (isRoot) { 16727 mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE; 16728 } else { 16729 mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE; 16730 } 16731 } 16732 16733 /** 16734 * {@hide} 16735 * 16736 * @return true if the view belongs to the root namespace, false otherwise 16737 */ 16738 public boolean isRootNamespace() { 16739 return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0; 16740 } 16741 16742 /** 16743 * Returns this view's identifier. 16744 * 16745 * @return a positive integer used to identify the view or {@link #NO_ID} 16746 * if the view has no ID 16747 * 16748 * @see #setId(int) 16749 * @see #findViewById(int) 16750 * @attr ref android.R.styleable#View_id 16751 */ 16752 @ViewDebug.CapturedViewProperty 16753 public int getId() { 16754 return mID; 16755 } 16756 16757 /** 16758 * Returns this view's tag. 16759 * 16760 * @return the Object stored in this view as a tag, or {@code null} if not 16761 * set 16762 * 16763 * @see #setTag(Object) 16764 * @see #getTag(int) 16765 */ 16766 @ViewDebug.ExportedProperty 16767 public Object getTag() { 16768 return mTag; 16769 } 16770 16771 /** 16772 * Sets the tag associated with this view. A tag can be used to mark 16773 * a view in its hierarchy and does not have to be unique within the 16774 * hierarchy. Tags can also be used to store data within a view without 16775 * resorting to another data structure. 16776 * 16777 * @param tag an Object to tag the view with 16778 * 16779 * @see #getTag() 16780 * @see #setTag(int, Object) 16781 */ 16782 public void setTag(final Object tag) { 16783 mTag = tag; 16784 } 16785 16786 /** 16787 * Returns the tag associated with this view and the specified key. 16788 * 16789 * @param key The key identifying the tag 16790 * 16791 * @return the Object stored in this view as a tag, or {@code null} if not 16792 * set 16793 * 16794 * @see #setTag(int, Object) 16795 * @see #getTag() 16796 */ 16797 public Object getTag(int key) { 16798 if (mKeyedTags != null) return mKeyedTags.get(key); 16799 return null; 16800 } 16801 16802 /** 16803 * Sets a tag associated with this view and a key. A tag can be used 16804 * to mark a view in its hierarchy and does not have to be unique within 16805 * the hierarchy. Tags can also be used to store data within a view 16806 * without resorting to another data structure. 16807 * 16808 * The specified key should be an id declared in the resources of the 16809 * application to ensure it is unique (see the <a 16810 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 16811 * Keys identified as belonging to 16812 * the Android framework or not associated with any package will cause 16813 * an {@link IllegalArgumentException} to be thrown. 16814 * 16815 * @param key The key identifying the tag 16816 * @param tag An Object to tag the view with 16817 * 16818 * @throws IllegalArgumentException If they specified key is not valid 16819 * 16820 * @see #setTag(Object) 16821 * @see #getTag(int) 16822 */ 16823 public void setTag(int key, final Object tag) { 16824 // If the package id is 0x00 or 0x01, it's either an undefined package 16825 // or a framework id 16826 if ((key >>> 24) < 2) { 16827 throw new IllegalArgumentException("The key must be an application-specific " 16828 + "resource id."); 16829 } 16830 16831 setKeyedTag(key, tag); 16832 } 16833 16834 /** 16835 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 16836 * framework id. 16837 * 16838 * @hide 16839 */ 16840 public void setTagInternal(int key, Object tag) { 16841 if ((key >>> 24) != 0x1) { 16842 throw new IllegalArgumentException("The key must be a framework-specific " 16843 + "resource id."); 16844 } 16845 16846 setKeyedTag(key, tag); 16847 } 16848 16849 private void setKeyedTag(int key, Object tag) { 16850 if (mKeyedTags == null) { 16851 mKeyedTags = new SparseArray<Object>(2); 16852 } 16853 16854 mKeyedTags.put(key, tag); 16855 } 16856 16857 /** 16858 * Prints information about this view in the log output, with the tag 16859 * {@link #VIEW_LOG_TAG}. 16860 * 16861 * @hide 16862 */ 16863 public void debug() { 16864 debug(0); 16865 } 16866 16867 /** 16868 * Prints information about this view in the log output, with the tag 16869 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 16870 * indentation defined by the <code>depth</code>. 16871 * 16872 * @param depth the indentation level 16873 * 16874 * @hide 16875 */ 16876 protected void debug(int depth) { 16877 String output = debugIndent(depth - 1); 16878 16879 output += "+ " + this; 16880 int id = getId(); 16881 if (id != -1) { 16882 output += " (id=" + id + ")"; 16883 } 16884 Object tag = getTag(); 16885 if (tag != null) { 16886 output += " (tag=" + tag + ")"; 16887 } 16888 Log.d(VIEW_LOG_TAG, output); 16889 16890 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 16891 output = debugIndent(depth) + " FOCUSED"; 16892 Log.d(VIEW_LOG_TAG, output); 16893 } 16894 16895 output = debugIndent(depth); 16896 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 16897 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 16898 + "} "; 16899 Log.d(VIEW_LOG_TAG, output); 16900 16901 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 16902 || mPaddingBottom != 0) { 16903 output = debugIndent(depth); 16904 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 16905 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 16906 Log.d(VIEW_LOG_TAG, output); 16907 } 16908 16909 output = debugIndent(depth); 16910 output += "mMeasureWidth=" + mMeasuredWidth + 16911 " mMeasureHeight=" + mMeasuredHeight; 16912 Log.d(VIEW_LOG_TAG, output); 16913 16914 output = debugIndent(depth); 16915 if (mLayoutParams == null) { 16916 output += "BAD! no layout params"; 16917 } else { 16918 output = mLayoutParams.debug(output); 16919 } 16920 Log.d(VIEW_LOG_TAG, output); 16921 16922 output = debugIndent(depth); 16923 output += "flags={"; 16924 output += View.printFlags(mViewFlags); 16925 output += "}"; 16926 Log.d(VIEW_LOG_TAG, output); 16927 16928 output = debugIndent(depth); 16929 output += "privateFlags={"; 16930 output += View.printPrivateFlags(mPrivateFlags); 16931 output += "}"; 16932 Log.d(VIEW_LOG_TAG, output); 16933 } 16934 16935 /** 16936 * Creates a string of whitespaces used for indentation. 16937 * 16938 * @param depth the indentation level 16939 * @return a String containing (depth * 2 + 3) * 2 white spaces 16940 * 16941 * @hide 16942 */ 16943 protected static String debugIndent(int depth) { 16944 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 16945 for (int i = 0; i < (depth * 2) + 3; i++) { 16946 spaces.append(' ').append(' '); 16947 } 16948 return spaces.toString(); 16949 } 16950 16951 /** 16952 * <p>Return the offset of the widget's text baseline from the widget's top 16953 * boundary. If this widget does not support baseline alignment, this 16954 * method returns -1. </p> 16955 * 16956 * @return the offset of the baseline within the widget's bounds or -1 16957 * if baseline alignment is not supported 16958 */ 16959 @ViewDebug.ExportedProperty(category = "layout") 16960 public int getBaseline() { 16961 return -1; 16962 } 16963 16964 /** 16965 * Returns whether the view hierarchy is currently undergoing a layout pass. This 16966 * information is useful to avoid situations such as calling {@link #requestLayout()} during 16967 * a layout pass. 16968 * 16969 * @return whether the view hierarchy is currently undergoing a layout pass 16970 */ 16971 public boolean isInLayout() { 16972 ViewRootImpl viewRoot = getViewRootImpl(); 16973 return (viewRoot != null && viewRoot.isInLayout()); 16974 } 16975 16976 /** 16977 * Call this when something has changed which has invalidated the 16978 * layout of this view. This will schedule a layout pass of the view 16979 * tree. This should not be called while the view hierarchy is currently in a layout 16980 * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the 16981 * end of the current layout pass (and then layout will run again) or after the current 16982 * frame is drawn and the next layout occurs. 16983 * 16984 * <p>Subclasses which override this method should call the superclass method to 16985 * handle possible request-during-layout errors correctly.</p> 16986 */ 16987 public void requestLayout() { 16988 if (mMeasureCache != null) mMeasureCache.clear(); 16989 16990 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) { 16991 // Only trigger request-during-layout logic if this is the view requesting it, 16992 // not the views in its parent hierarchy 16993 ViewRootImpl viewRoot = getViewRootImpl(); 16994 if (viewRoot != null && viewRoot.isInLayout()) { 16995 if (!viewRoot.requestLayoutDuringLayout(this)) { 16996 return; 16997 } 16998 } 16999 mAttachInfo.mViewRequestingLayout = this; 17000 } 17001 17002 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 17003 mPrivateFlags |= PFLAG_INVALIDATED; 17004 17005 if (mParent != null && !mParent.isLayoutRequested()) { 17006 mParent.requestLayout(); 17007 } 17008 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) { 17009 mAttachInfo.mViewRequestingLayout = null; 17010 } 17011 } 17012 17013 /** 17014 * Forces this view to be laid out during the next layout pass. 17015 * This method does not call requestLayout() or forceLayout() 17016 * on the parent. 17017 */ 17018 public void forceLayout() { 17019 if (mMeasureCache != null) mMeasureCache.clear(); 17020 17021 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 17022 mPrivateFlags |= PFLAG_INVALIDATED; 17023 } 17024 17025 /** 17026 * <p> 17027 * This is called to find out how big a view should be. The parent 17028 * supplies constraint information in the width and height parameters. 17029 * </p> 17030 * 17031 * <p> 17032 * The actual measurement work of a view is performed in 17033 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 17034 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 17035 * </p> 17036 * 17037 * 17038 * @param widthMeasureSpec Horizontal space requirements as imposed by the 17039 * parent 17040 * @param heightMeasureSpec Vertical space requirements as imposed by the 17041 * parent 17042 * 17043 * @see #onMeasure(int, int) 17044 */ 17045 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 17046 boolean optical = isLayoutModeOptical(this); 17047 if (optical != isLayoutModeOptical(mParent)) { 17048 Insets insets = getOpticalInsets(); 17049 int oWidth = insets.left + insets.right; 17050 int oHeight = insets.top + insets.bottom; 17051 widthMeasureSpec = MeasureSpec.adjust(widthMeasureSpec, optical ? -oWidth : oWidth); 17052 heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight); 17053 } 17054 17055 // Suppress sign extension for the low bytes 17056 long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL; 17057 if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2); 17058 17059 if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT || 17060 widthMeasureSpec != mOldWidthMeasureSpec || 17061 heightMeasureSpec != mOldHeightMeasureSpec) { 17062 17063 // first clears the measured dimension flag 17064 mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET; 17065 17066 resolveRtlPropertiesIfNeeded(); 17067 17068 int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 : 17069 mMeasureCache.indexOfKey(key); 17070 if (cacheIndex < 0 || sIgnoreMeasureCache) { 17071 // measure ourselves, this should set the measured dimension flag back 17072 onMeasure(widthMeasureSpec, heightMeasureSpec); 17073 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 17074 } else { 17075 long value = mMeasureCache.valueAt(cacheIndex); 17076 // Casting a long to int drops the high 32 bits, no mask needed 17077 setMeasuredDimensionRaw((int) (value >> 32), (int) value); 17078 mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 17079 } 17080 17081 // flag not set, setMeasuredDimension() was not invoked, we raise 17082 // an exception to warn the developer 17083 if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) { 17084 throw new IllegalStateException("onMeasure() did not set the" 17085 + " measured dimension by calling" 17086 + " setMeasuredDimension()"); 17087 } 17088 17089 mPrivateFlags |= PFLAG_LAYOUT_REQUIRED; 17090 } 17091 17092 mOldWidthMeasureSpec = widthMeasureSpec; 17093 mOldHeightMeasureSpec = heightMeasureSpec; 17094 17095 mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 | 17096 (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension 17097 } 17098 17099 /** 17100 * <p> 17101 * Measure the view and its content to determine the measured width and the 17102 * measured height. This method is invoked by {@link #measure(int, int)} and 17103 * should be overriden by subclasses to provide accurate and efficient 17104 * measurement of their contents. 17105 * </p> 17106 * 17107 * <p> 17108 * <strong>CONTRACT:</strong> When overriding this method, you 17109 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 17110 * measured width and height of this view. Failure to do so will trigger an 17111 * <code>IllegalStateException</code>, thrown by 17112 * {@link #measure(int, int)}. Calling the superclass' 17113 * {@link #onMeasure(int, int)} is a valid use. 17114 * </p> 17115 * 17116 * <p> 17117 * The base class implementation of measure defaults to the background size, 17118 * unless a larger size is allowed by the MeasureSpec. Subclasses should 17119 * override {@link #onMeasure(int, int)} to provide better measurements of 17120 * their content. 17121 * </p> 17122 * 17123 * <p> 17124 * If this method is overridden, it is the subclass's responsibility to make 17125 * sure the measured height and width are at least the view's minimum height 17126 * and width ({@link #getSuggestedMinimumHeight()} and 17127 * {@link #getSuggestedMinimumWidth()}). 17128 * </p> 17129 * 17130 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 17131 * The requirements are encoded with 17132 * {@link android.view.View.MeasureSpec}. 17133 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 17134 * The requirements are encoded with 17135 * {@link android.view.View.MeasureSpec}. 17136 * 17137 * @see #getMeasuredWidth() 17138 * @see #getMeasuredHeight() 17139 * @see #setMeasuredDimension(int, int) 17140 * @see #getSuggestedMinimumHeight() 17141 * @see #getSuggestedMinimumWidth() 17142 * @see android.view.View.MeasureSpec#getMode(int) 17143 * @see android.view.View.MeasureSpec#getSize(int) 17144 */ 17145 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 17146 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 17147 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 17148 } 17149 17150 /** 17151 * <p>This method must be called by {@link #onMeasure(int, int)} to store the 17152 * measured width and measured height. Failing to do so will trigger an 17153 * exception at measurement time.</p> 17154 * 17155 * @param measuredWidth The measured width of this view. May be a complex 17156 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17157 * {@link #MEASURED_STATE_TOO_SMALL}. 17158 * @param measuredHeight The measured height of this view. May be a complex 17159 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17160 * {@link #MEASURED_STATE_TOO_SMALL}. 17161 */ 17162 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 17163 boolean optical = isLayoutModeOptical(this); 17164 if (optical != isLayoutModeOptical(mParent)) { 17165 Insets insets = getOpticalInsets(); 17166 int opticalWidth = insets.left + insets.right; 17167 int opticalHeight = insets.top + insets.bottom; 17168 17169 measuredWidth += optical ? opticalWidth : -opticalWidth; 17170 measuredHeight += optical ? opticalHeight : -opticalHeight; 17171 } 17172 setMeasuredDimensionRaw(measuredWidth, measuredHeight); 17173 } 17174 17175 /** 17176 * Sets the measured dimension without extra processing for things like optical bounds. 17177 * Useful for reapplying consistent values that have already been cooked with adjustments 17178 * for optical bounds, etc. such as those from the measurement cache. 17179 * 17180 * @param measuredWidth The measured width of this view. May be a complex 17181 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17182 * {@link #MEASURED_STATE_TOO_SMALL}. 17183 * @param measuredHeight The measured height of this view. May be a complex 17184 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17185 * {@link #MEASURED_STATE_TOO_SMALL}. 17186 */ 17187 private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) { 17188 mMeasuredWidth = measuredWidth; 17189 mMeasuredHeight = measuredHeight; 17190 17191 mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET; 17192 } 17193 17194 /** 17195 * Merge two states as returned by {@link #getMeasuredState()}. 17196 * @param curState The current state as returned from a view or the result 17197 * of combining multiple views. 17198 * @param newState The new view state to combine. 17199 * @return Returns a new integer reflecting the combination of the two 17200 * states. 17201 */ 17202 public static int combineMeasuredStates(int curState, int newState) { 17203 return curState | newState; 17204 } 17205 17206 /** 17207 * Version of {@link #resolveSizeAndState(int, int, int)} 17208 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 17209 */ 17210 public static int resolveSize(int size, int measureSpec) { 17211 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 17212 } 17213 17214 /** 17215 * Utility to reconcile a desired size and state, with constraints imposed 17216 * by a MeasureSpec. Will take the desired size, unless a different size 17217 * is imposed by the constraints. The returned value is a compound integer, 17218 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 17219 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting 17220 * size is smaller than the size the view wants to be. 17221 * 17222 * @param size How big the view wants to be 17223 * @param measureSpec Constraints imposed by the parent 17224 * @return Size information bit mask as defined by 17225 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 17226 */ 17227 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 17228 int result = size; 17229 int specMode = MeasureSpec.getMode(measureSpec); 17230 int specSize = MeasureSpec.getSize(measureSpec); 17231 switch (specMode) { 17232 case MeasureSpec.UNSPECIFIED: 17233 result = size; 17234 break; 17235 case MeasureSpec.AT_MOST: 17236 if (specSize < size) { 17237 result = specSize | MEASURED_STATE_TOO_SMALL; 17238 } else { 17239 result = size; 17240 } 17241 break; 17242 case MeasureSpec.EXACTLY: 17243 result = specSize; 17244 break; 17245 } 17246 return result | (childMeasuredState&MEASURED_STATE_MASK); 17247 } 17248 17249 /** 17250 * Utility to return a default size. Uses the supplied size if the 17251 * MeasureSpec imposed no constraints. Will get larger if allowed 17252 * by the MeasureSpec. 17253 * 17254 * @param size Default size for this view 17255 * @param measureSpec Constraints imposed by the parent 17256 * @return The size this view should be. 17257 */ 17258 public static int getDefaultSize(int size, int measureSpec) { 17259 int result = size; 17260 int specMode = MeasureSpec.getMode(measureSpec); 17261 int specSize = MeasureSpec.getSize(measureSpec); 17262 17263 switch (specMode) { 17264 case MeasureSpec.UNSPECIFIED: 17265 result = size; 17266 break; 17267 case MeasureSpec.AT_MOST: 17268 case MeasureSpec.EXACTLY: 17269 result = specSize; 17270 break; 17271 } 17272 return result; 17273 } 17274 17275 /** 17276 * Returns the suggested minimum height that the view should use. This 17277 * returns the maximum of the view's minimum height 17278 * and the background's minimum height 17279 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 17280 * <p> 17281 * When being used in {@link #onMeasure(int, int)}, the caller should still 17282 * ensure the returned height is within the requirements of the parent. 17283 * 17284 * @return The suggested minimum height of the view. 17285 */ 17286 protected int getSuggestedMinimumHeight() { 17287 return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight()); 17288 17289 } 17290 17291 /** 17292 * Returns the suggested minimum width that the view should use. This 17293 * returns the maximum of the view's minimum width) 17294 * and the background's minimum width 17295 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 17296 * <p> 17297 * When being used in {@link #onMeasure(int, int)}, the caller should still 17298 * ensure the returned width is within the requirements of the parent. 17299 * 17300 * @return The suggested minimum width of the view. 17301 */ 17302 protected int getSuggestedMinimumWidth() { 17303 return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); 17304 } 17305 17306 /** 17307 * Returns the minimum height of the view. 17308 * 17309 * @return the minimum height the view will try to be. 17310 * 17311 * @see #setMinimumHeight(int) 17312 * 17313 * @attr ref android.R.styleable#View_minHeight 17314 */ 17315 public int getMinimumHeight() { 17316 return mMinHeight; 17317 } 17318 17319 /** 17320 * Sets the minimum height of the view. It is not guaranteed the view will 17321 * be able to achieve this minimum height (for example, if its parent layout 17322 * constrains it with less available height). 17323 * 17324 * @param minHeight The minimum height the view will try to be. 17325 * 17326 * @see #getMinimumHeight() 17327 * 17328 * @attr ref android.R.styleable#View_minHeight 17329 */ 17330 public void setMinimumHeight(int minHeight) { 17331 mMinHeight = minHeight; 17332 requestLayout(); 17333 } 17334 17335 /** 17336 * Returns the minimum width of the view. 17337 * 17338 * @return the minimum width the view will try to be. 17339 * 17340 * @see #setMinimumWidth(int) 17341 * 17342 * @attr ref android.R.styleable#View_minWidth 17343 */ 17344 public int getMinimumWidth() { 17345 return mMinWidth; 17346 } 17347 17348 /** 17349 * Sets the minimum width of the view. It is not guaranteed the view will 17350 * be able to achieve this minimum width (for example, if its parent layout 17351 * constrains it with less available width). 17352 * 17353 * @param minWidth The minimum width the view will try to be. 17354 * 17355 * @see #getMinimumWidth() 17356 * 17357 * @attr ref android.R.styleable#View_minWidth 17358 */ 17359 public void setMinimumWidth(int minWidth) { 17360 mMinWidth = minWidth; 17361 requestLayout(); 17362 17363 } 17364 17365 /** 17366 * Get the animation currently associated with this view. 17367 * 17368 * @return The animation that is currently playing or 17369 * scheduled to play for this view. 17370 */ 17371 public Animation getAnimation() { 17372 return mCurrentAnimation; 17373 } 17374 17375 /** 17376 * Start the specified animation now. 17377 * 17378 * @param animation the animation to start now 17379 */ 17380 public void startAnimation(Animation animation) { 17381 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 17382 setAnimation(animation); 17383 invalidateParentCaches(); 17384 invalidate(true); 17385 } 17386 17387 /** 17388 * Cancels any animations for this view. 17389 */ 17390 public void clearAnimation() { 17391 if (mCurrentAnimation != null) { 17392 mCurrentAnimation.detach(); 17393 } 17394 mCurrentAnimation = null; 17395 invalidateParentIfNeeded(); 17396 } 17397 17398 /** 17399 * Sets the next animation to play for this view. 17400 * If you want the animation to play immediately, use 17401 * {@link #startAnimation(android.view.animation.Animation)} instead. 17402 * This method provides allows fine-grained 17403 * control over the start time and invalidation, but you 17404 * must make sure that 1) the animation has a start time set, and 17405 * 2) the view's parent (which controls animations on its children) 17406 * will be invalidated when the animation is supposed to 17407 * start. 17408 * 17409 * @param animation The next animation, or null. 17410 */ 17411 public void setAnimation(Animation animation) { 17412 mCurrentAnimation = animation; 17413 17414 if (animation != null) { 17415 // If the screen is off assume the animation start time is now instead of 17416 // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time 17417 // would cause the animation to start when the screen turns back on 17418 if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF 17419 && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) { 17420 animation.setStartTime(AnimationUtils.currentAnimationTimeMillis()); 17421 } 17422 animation.reset(); 17423 } 17424 } 17425 17426 /** 17427 * Invoked by a parent ViewGroup to notify the start of the animation 17428 * currently associated with this view. If you override this method, 17429 * always call super.onAnimationStart(); 17430 * 17431 * @see #setAnimation(android.view.animation.Animation) 17432 * @see #getAnimation() 17433 */ 17434 protected void onAnimationStart() { 17435 mPrivateFlags |= PFLAG_ANIMATION_STARTED; 17436 } 17437 17438 /** 17439 * Invoked by a parent ViewGroup to notify the end of the animation 17440 * currently associated with this view. If you override this method, 17441 * always call super.onAnimationEnd(); 17442 * 17443 * @see #setAnimation(android.view.animation.Animation) 17444 * @see #getAnimation() 17445 */ 17446 protected void onAnimationEnd() { 17447 mPrivateFlags &= ~PFLAG_ANIMATION_STARTED; 17448 } 17449 17450 /** 17451 * Invoked if there is a Transform that involves alpha. Subclass that can 17452 * draw themselves with the specified alpha should return true, and then 17453 * respect that alpha when their onDraw() is called. If this returns false 17454 * then the view may be redirected to draw into an offscreen buffer to 17455 * fulfill the request, which will look fine, but may be slower than if the 17456 * subclass handles it internally. The default implementation returns false. 17457 * 17458 * @param alpha The alpha (0..255) to apply to the view's drawing 17459 * @return true if the view can draw with the specified alpha. 17460 */ 17461 protected boolean onSetAlpha(int alpha) { 17462 return false; 17463 } 17464 17465 /** 17466 * This is used by the RootView to perform an optimization when 17467 * the view hierarchy contains one or several SurfaceView. 17468 * SurfaceView is always considered transparent, but its children are not, 17469 * therefore all View objects remove themselves from the global transparent 17470 * region (passed as a parameter to this function). 17471 * 17472 * @param region The transparent region for this ViewAncestor (window). 17473 * 17474 * @return Returns true if the effective visibility of the view at this 17475 * point is opaque, regardless of the transparent region; returns false 17476 * if it is possible for underlying windows to be seen behind the view. 17477 * 17478 * {@hide} 17479 */ 17480 public boolean gatherTransparentRegion(Region region) { 17481 final AttachInfo attachInfo = mAttachInfo; 17482 if (region != null && attachInfo != null) { 17483 final int pflags = mPrivateFlags; 17484 if ((pflags & PFLAG_SKIP_DRAW) == 0) { 17485 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 17486 // remove it from the transparent region. 17487 final int[] location = attachInfo.mTransparentLocation; 17488 getLocationInWindow(location); 17489 region.op(location[0], location[1], location[0] + mRight - mLeft, 17490 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 17491 } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null && 17492 mBackground.getOpacity() != PixelFormat.TRANSPARENT) { 17493 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 17494 // exists, so we remove the background drawable's non-transparent 17495 // parts from this transparent region. 17496 applyDrawableToTransparentRegion(mBackground, region); 17497 } 17498 } 17499 return true; 17500 } 17501 17502 /** 17503 * Play a sound effect for this view. 17504 * 17505 * <p>The framework will play sound effects for some built in actions, such as 17506 * clicking, but you may wish to play these effects in your widget, 17507 * for instance, for internal navigation. 17508 * 17509 * <p>The sound effect will only be played if sound effects are enabled by the user, and 17510 * {@link #isSoundEffectsEnabled()} is true. 17511 * 17512 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 17513 */ 17514 public void playSoundEffect(int soundConstant) { 17515 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 17516 return; 17517 } 17518 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 17519 } 17520 17521 /** 17522 * BZZZTT!!1! 17523 * 17524 * <p>Provide haptic feedback to the user for this view. 17525 * 17526 * <p>The framework will provide haptic feedback for some built in actions, 17527 * such as long presses, but you may wish to provide feedback for your 17528 * own widget. 17529 * 17530 * <p>The feedback will only be performed if 17531 * {@link #isHapticFeedbackEnabled()} is true. 17532 * 17533 * @param feedbackConstant One of the constants defined in 17534 * {@link HapticFeedbackConstants} 17535 */ 17536 public boolean performHapticFeedback(int feedbackConstant) { 17537 return performHapticFeedback(feedbackConstant, 0); 17538 } 17539 17540 /** 17541 * BZZZTT!!1! 17542 * 17543 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 17544 * 17545 * @param feedbackConstant One of the constants defined in 17546 * {@link HapticFeedbackConstants} 17547 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 17548 */ 17549 public boolean performHapticFeedback(int feedbackConstant, int flags) { 17550 if (mAttachInfo == null) { 17551 return false; 17552 } 17553 //noinspection SimplifiableIfStatement 17554 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 17555 && !isHapticFeedbackEnabled()) { 17556 return false; 17557 } 17558 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 17559 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 17560 } 17561 17562 /** 17563 * Request that the visibility of the status bar or other screen/window 17564 * decorations be changed. 17565 * 17566 * <p>This method is used to put the over device UI into temporary modes 17567 * where the user's attention is focused more on the application content, 17568 * by dimming or hiding surrounding system affordances. This is typically 17569 * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY 17570 * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content 17571 * to be placed behind the action bar (and with these flags other system 17572 * affordances) so that smooth transitions between hiding and showing them 17573 * can be done. 17574 * 17575 * <p>Two representative examples of the use of system UI visibility is 17576 * implementing a content browsing application (like a magazine reader) 17577 * and a video playing application. 17578 * 17579 * <p>The first code shows a typical implementation of a View in a content 17580 * browsing application. In this implementation, the application goes 17581 * into a content-oriented mode by hiding the status bar and action bar, 17582 * and putting the navigation elements into lights out mode. The user can 17583 * then interact with content while in this mode. Such an application should 17584 * provide an easy way for the user to toggle out of the mode (such as to 17585 * check information in the status bar or access notifications). In the 17586 * implementation here, this is done simply by tapping on the content. 17587 * 17588 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java 17589 * content} 17590 * 17591 * <p>This second code sample shows a typical implementation of a View 17592 * in a video playing application. In this situation, while the video is 17593 * playing the application would like to go into a complete full-screen mode, 17594 * to use as much of the display as possible for the video. When in this state 17595 * the user can not interact with the application; the system intercepts 17596 * touching on the screen to pop the UI out of full screen mode. See 17597 * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code. 17598 * 17599 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java 17600 * content} 17601 * 17602 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 17603 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 17604 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 17605 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 17606 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 17607 */ 17608 public void setSystemUiVisibility(int visibility) { 17609 if (visibility != mSystemUiVisibility) { 17610 mSystemUiVisibility = visibility; 17611 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 17612 mParent.recomputeViewAttributes(this); 17613 } 17614 } 17615 } 17616 17617 /** 17618 * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested. 17619 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 17620 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 17621 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 17622 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 17623 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 17624 */ 17625 public int getSystemUiVisibility() { 17626 return mSystemUiVisibility; 17627 } 17628 17629 /** 17630 * Returns the current system UI visibility that is currently set for 17631 * the entire window. This is the combination of the 17632 * {@link #setSystemUiVisibility(int)} values supplied by all of the 17633 * views in the window. 17634 */ 17635 public int getWindowSystemUiVisibility() { 17636 return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0; 17637 } 17638 17639 /** 17640 * Override to find out when the window's requested system UI visibility 17641 * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}. 17642 * This is different from the callbacks received through 17643 * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)} 17644 * in that this is only telling you about the local request of the window, 17645 * not the actual values applied by the system. 17646 */ 17647 public void onWindowSystemUiVisibilityChanged(int visible) { 17648 } 17649 17650 /** 17651 * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down 17652 * the view hierarchy. 17653 */ 17654 public void dispatchWindowSystemUiVisiblityChanged(int visible) { 17655 onWindowSystemUiVisibilityChanged(visible); 17656 } 17657 17658 /** 17659 * Set a listener to receive callbacks when the visibility of the system bar changes. 17660 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 17661 */ 17662 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 17663 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 17664 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 17665 mParent.recomputeViewAttributes(this); 17666 } 17667 } 17668 17669 /** 17670 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 17671 * the view hierarchy. 17672 */ 17673 public void dispatchSystemUiVisibilityChanged(int visibility) { 17674 ListenerInfo li = mListenerInfo; 17675 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 17676 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 17677 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 17678 } 17679 } 17680 17681 boolean updateLocalSystemUiVisibility(int localValue, int localChanges) { 17682 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 17683 if (val != mSystemUiVisibility) { 17684 setSystemUiVisibility(val); 17685 return true; 17686 } 17687 return false; 17688 } 17689 17690 /** @hide */ 17691 public void setDisabledSystemUiVisibility(int flags) { 17692 if (mAttachInfo != null) { 17693 if (mAttachInfo.mDisabledSystemUiVisibility != flags) { 17694 mAttachInfo.mDisabledSystemUiVisibility = flags; 17695 if (mParent != null) { 17696 mParent.recomputeViewAttributes(this); 17697 } 17698 } 17699 } 17700 } 17701 17702 /** 17703 * Creates an image that the system displays during the drag and drop 17704 * operation. This is called a "drag shadow". The default implementation 17705 * for a DragShadowBuilder based on a View returns an image that has exactly the same 17706 * appearance as the given View. The default also positions the center of the drag shadow 17707 * directly under the touch point. If no View is provided (the constructor with no parameters 17708 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 17709 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the 17710 * default is an invisible drag shadow. 17711 * <p> 17712 * You are not required to use the View you provide to the constructor as the basis of the 17713 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 17714 * anything you want as the drag shadow. 17715 * </p> 17716 * <p> 17717 * You pass a DragShadowBuilder object to the system when you start the drag. The system 17718 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 17719 * size and position of the drag shadow. It uses this data to construct a 17720 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 17721 * so that your application can draw the shadow image in the Canvas. 17722 * </p> 17723 * 17724 * <div class="special reference"> 17725 * <h3>Developer Guides</h3> 17726 * <p>For a guide to implementing drag and drop features, read the 17727 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 17728 * </div> 17729 */ 17730 public static class DragShadowBuilder { 17731 private final WeakReference<View> mView; 17732 17733 /** 17734 * Constructs a shadow image builder based on a View. By default, the resulting drag 17735 * shadow will have the same appearance and dimensions as the View, with the touch point 17736 * over the center of the View. 17737 * @param view A View. Any View in scope can be used. 17738 */ 17739 public DragShadowBuilder(View view) { 17740 mView = new WeakReference<View>(view); 17741 } 17742 17743 /** 17744 * Construct a shadow builder object with no associated View. This 17745 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 17746 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 17747 * to supply the drag shadow's dimensions and appearance without 17748 * reference to any View object. If they are not overridden, then the result is an 17749 * invisible drag shadow. 17750 */ 17751 public DragShadowBuilder() { 17752 mView = new WeakReference<View>(null); 17753 } 17754 17755 /** 17756 * Returns the View object that had been passed to the 17757 * {@link #View.DragShadowBuilder(View)} 17758 * constructor. If that View parameter was {@code null} or if the 17759 * {@link #View.DragShadowBuilder()} 17760 * constructor was used to instantiate the builder object, this method will return 17761 * null. 17762 * 17763 * @return The View object associate with this builder object. 17764 */ 17765 @SuppressWarnings({"JavadocReference"}) 17766 final public View getView() { 17767 return mView.get(); 17768 } 17769 17770 /** 17771 * Provides the metrics for the shadow image. These include the dimensions of 17772 * the shadow image, and the point within that shadow that should 17773 * be centered under the touch location while dragging. 17774 * <p> 17775 * The default implementation sets the dimensions of the shadow to be the 17776 * same as the dimensions of the View itself and centers the shadow under 17777 * the touch point. 17778 * </p> 17779 * 17780 * @param shadowSize A {@link android.graphics.Point} containing the width and height 17781 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 17782 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 17783 * image. 17784 * 17785 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 17786 * shadow image that should be underneath the touch point during the drag and drop 17787 * operation. Your application must set {@link android.graphics.Point#x} to the 17788 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 17789 */ 17790 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 17791 final View view = mView.get(); 17792 if (view != null) { 17793 shadowSize.set(view.getWidth(), view.getHeight()); 17794 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 17795 } else { 17796 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 17797 } 17798 } 17799 17800 /** 17801 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 17802 * based on the dimensions it received from the 17803 * {@link #onProvideShadowMetrics(Point, Point)} callback. 17804 * 17805 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 17806 */ 17807 public void onDrawShadow(Canvas canvas) { 17808 final View view = mView.get(); 17809 if (view != null) { 17810 view.draw(canvas); 17811 } else { 17812 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 17813 } 17814 } 17815 } 17816 17817 /** 17818 * Starts a drag and drop operation. When your application calls this method, it passes a 17819 * {@link android.view.View.DragShadowBuilder} object to the system. The 17820 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 17821 * to get metrics for the drag shadow, and then calls the object's 17822 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 17823 * <p> 17824 * Once the system has the drag shadow, it begins the drag and drop operation by sending 17825 * drag events to all the View objects in your application that are currently visible. It does 17826 * this either by calling the View object's drag listener (an implementation of 17827 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 17828 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 17829 * Both are passed a {@link android.view.DragEvent} object that has a 17830 * {@link android.view.DragEvent#getAction()} value of 17831 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 17832 * </p> 17833 * <p> 17834 * Your application can invoke startDrag() on any attached View object. The View object does not 17835 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to 17836 * be related to the View the user selected for dragging. 17837 * </p> 17838 * @param data A {@link android.content.ClipData} object pointing to the data to be 17839 * transferred by the drag and drop operation. 17840 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 17841 * drag shadow. 17842 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 17843 * drop operation. This Object is put into every DragEvent object sent by the system during the 17844 * current drag. 17845 * <p> 17846 * myLocalState is a lightweight mechanism for the sending information from the dragged View 17847 * to the target Views. For example, it can contain flags that differentiate between a 17848 * a copy operation and a move operation. 17849 * </p> 17850 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 17851 * so the parameter should be set to 0. 17852 * @return {@code true} if the method completes successfully, or 17853 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 17854 * do a drag, and so no drag operation is in progress. 17855 */ 17856 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 17857 Object myLocalState, int flags) { 17858 if (ViewDebug.DEBUG_DRAG) { 17859 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 17860 } 17861 boolean okay = false; 17862 17863 Point shadowSize = new Point(); 17864 Point shadowTouchPoint = new Point(); 17865 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 17866 17867 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 17868 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 17869 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 17870 } 17871 17872 if (ViewDebug.DEBUG_DRAG) { 17873 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 17874 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 17875 } 17876 Surface surface = new Surface(); 17877 try { 17878 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 17879 flags, shadowSize.x, shadowSize.y, surface); 17880 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 17881 + " surface=" + surface); 17882 if (token != null) { 17883 Canvas canvas = surface.lockCanvas(null); 17884 try { 17885 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 17886 shadowBuilder.onDrawShadow(canvas); 17887 } finally { 17888 surface.unlockCanvasAndPost(canvas); 17889 } 17890 17891 final ViewRootImpl root = getViewRootImpl(); 17892 17893 // Cache the local state object for delivery with DragEvents 17894 root.setLocalDragState(myLocalState); 17895 17896 // repurpose 'shadowSize' for the last touch point 17897 root.getLastTouchPoint(shadowSize); 17898 17899 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 17900 shadowSize.x, shadowSize.y, 17901 shadowTouchPoint.x, shadowTouchPoint.y, data); 17902 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 17903 17904 // Off and running! Release our local surface instance; the drag 17905 // shadow surface is now managed by the system process. 17906 surface.release(); 17907 } 17908 } catch (Exception e) { 17909 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 17910 surface.destroy(); 17911 } 17912 17913 return okay; 17914 } 17915 17916 /** 17917 * Handles drag events sent by the system following a call to 17918 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}. 17919 *<p> 17920 * When the system calls this method, it passes a 17921 * {@link android.view.DragEvent} object. A call to 17922 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 17923 * in DragEvent. The method uses these to determine what is happening in the drag and drop 17924 * operation. 17925 * @param event The {@link android.view.DragEvent} sent by the system. 17926 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 17927 * in DragEvent, indicating the type of drag event represented by this object. 17928 * @return {@code true} if the method was successful, otherwise {@code false}. 17929 * <p> 17930 * The method should return {@code true} in response to an action type of 17931 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 17932 * operation. 17933 * </p> 17934 * <p> 17935 * The method should also return {@code true} in response to an action type of 17936 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 17937 * {@code false} if it didn't. 17938 * </p> 17939 */ 17940 public boolean onDragEvent(DragEvent event) { 17941 return false; 17942 } 17943 17944 /** 17945 * Detects if this View is enabled and has a drag event listener. 17946 * If both are true, then it calls the drag event listener with the 17947 * {@link android.view.DragEvent} it received. If the drag event listener returns 17948 * {@code true}, then dispatchDragEvent() returns {@code true}. 17949 * <p> 17950 * For all other cases, the method calls the 17951 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 17952 * method and returns its result. 17953 * </p> 17954 * <p> 17955 * This ensures that a drag event is always consumed, even if the View does not have a drag 17956 * event listener. However, if the View has a listener and the listener returns true, then 17957 * onDragEvent() is not called. 17958 * </p> 17959 */ 17960 public boolean dispatchDragEvent(DragEvent event) { 17961 ListenerInfo li = mListenerInfo; 17962 //noinspection SimplifiableIfStatement 17963 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 17964 && li.mOnDragListener.onDrag(this, event)) { 17965 return true; 17966 } 17967 return onDragEvent(event); 17968 } 17969 17970 boolean canAcceptDrag() { 17971 return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0; 17972 } 17973 17974 /** 17975 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 17976 * it is ever exposed at all. 17977 * @hide 17978 */ 17979 public void onCloseSystemDialogs(String reason) { 17980 } 17981 17982 /** 17983 * Given a Drawable whose bounds have been set to draw into this view, 17984 * update a Region being computed for 17985 * {@link #gatherTransparentRegion(android.graphics.Region)} so 17986 * that any non-transparent parts of the Drawable are removed from the 17987 * given transparent region. 17988 * 17989 * @param dr The Drawable whose transparency is to be applied to the region. 17990 * @param region A Region holding the current transparency information, 17991 * where any parts of the region that are set are considered to be 17992 * transparent. On return, this region will be modified to have the 17993 * transparency information reduced by the corresponding parts of the 17994 * Drawable that are not transparent. 17995 * {@hide} 17996 */ 17997 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 17998 if (DBG) { 17999 Log.i("View", "Getting transparent region for: " + this); 18000 } 18001 final Region r = dr.getTransparentRegion(); 18002 final Rect db = dr.getBounds(); 18003 final AttachInfo attachInfo = mAttachInfo; 18004 if (r != null && attachInfo != null) { 18005 final int w = getRight()-getLeft(); 18006 final int h = getBottom()-getTop(); 18007 if (db.left > 0) { 18008 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 18009 r.op(0, 0, db.left, h, Region.Op.UNION); 18010 } 18011 if (db.right < w) { 18012 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 18013 r.op(db.right, 0, w, h, Region.Op.UNION); 18014 } 18015 if (db.top > 0) { 18016 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 18017 r.op(0, 0, w, db.top, Region.Op.UNION); 18018 } 18019 if (db.bottom < h) { 18020 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 18021 r.op(0, db.bottom, w, h, Region.Op.UNION); 18022 } 18023 final int[] location = attachInfo.mTransparentLocation; 18024 getLocationInWindow(location); 18025 r.translate(location[0], location[1]); 18026 region.op(r, Region.Op.INTERSECT); 18027 } else { 18028 region.op(db, Region.Op.DIFFERENCE); 18029 } 18030 } 18031 18032 private void checkForLongClick(int delayOffset) { 18033 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 18034 mHasPerformedLongPress = false; 18035 18036 if (mPendingCheckForLongPress == null) { 18037 mPendingCheckForLongPress = new CheckForLongPress(); 18038 } 18039 mPendingCheckForLongPress.rememberWindowAttachCount(); 18040 postDelayed(mPendingCheckForLongPress, 18041 ViewConfiguration.getLongPressTimeout() - delayOffset); 18042 } 18043 } 18044 18045 /** 18046 * Inflate a view from an XML resource. This convenience method wraps the {@link 18047 * LayoutInflater} class, which provides a full range of options for view inflation. 18048 * 18049 * @param context The Context object for your activity or application. 18050 * @param resource The resource ID to inflate 18051 * @param root A view group that will be the parent. Used to properly inflate the 18052 * layout_* parameters. 18053 * @see LayoutInflater 18054 */ 18055 public static View inflate(Context context, int resource, ViewGroup root) { 18056 LayoutInflater factory = LayoutInflater.from(context); 18057 return factory.inflate(resource, root); 18058 } 18059 18060 /** 18061 * Scroll the view with standard behavior for scrolling beyond the normal 18062 * content boundaries. Views that call this method should override 18063 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 18064 * results of an over-scroll operation. 18065 * 18066 * Views can use this method to handle any touch or fling-based scrolling. 18067 * 18068 * @param deltaX Change in X in pixels 18069 * @param deltaY Change in Y in pixels 18070 * @param scrollX Current X scroll value in pixels before applying deltaX 18071 * @param scrollY Current Y scroll value in pixels before applying deltaY 18072 * @param scrollRangeX Maximum content scroll range along the X axis 18073 * @param scrollRangeY Maximum content scroll range along the Y axis 18074 * @param maxOverScrollX Number of pixels to overscroll by in either direction 18075 * along the X axis. 18076 * @param maxOverScrollY Number of pixels to overscroll by in either direction 18077 * along the Y axis. 18078 * @param isTouchEvent true if this scroll operation is the result of a touch event. 18079 * @return true if scrolling was clamped to an over-scroll boundary along either 18080 * axis, false otherwise. 18081 */ 18082 @SuppressWarnings({"UnusedParameters"}) 18083 protected boolean overScrollBy(int deltaX, int deltaY, 18084 int scrollX, int scrollY, 18085 int scrollRangeX, int scrollRangeY, 18086 int maxOverScrollX, int maxOverScrollY, 18087 boolean isTouchEvent) { 18088 final int overScrollMode = mOverScrollMode; 18089 final boolean canScrollHorizontal = 18090 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 18091 final boolean canScrollVertical = 18092 computeVerticalScrollRange() > computeVerticalScrollExtent(); 18093 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 18094 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 18095 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 18096 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 18097 18098 int newScrollX = scrollX + deltaX; 18099 if (!overScrollHorizontal) { 18100 maxOverScrollX = 0; 18101 } 18102 18103 int newScrollY = scrollY + deltaY; 18104 if (!overScrollVertical) { 18105 maxOverScrollY = 0; 18106 } 18107 18108 // Clamp values if at the limits and record 18109 final int left = -maxOverScrollX; 18110 final int right = maxOverScrollX + scrollRangeX; 18111 final int top = -maxOverScrollY; 18112 final int bottom = maxOverScrollY + scrollRangeY; 18113 18114 boolean clampedX = false; 18115 if (newScrollX > right) { 18116 newScrollX = right; 18117 clampedX = true; 18118 } else if (newScrollX < left) { 18119 newScrollX = left; 18120 clampedX = true; 18121 } 18122 18123 boolean clampedY = false; 18124 if (newScrollY > bottom) { 18125 newScrollY = bottom; 18126 clampedY = true; 18127 } else if (newScrollY < top) { 18128 newScrollY = top; 18129 clampedY = true; 18130 } 18131 18132 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 18133 18134 return clampedX || clampedY; 18135 } 18136 18137 /** 18138 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 18139 * respond to the results of an over-scroll operation. 18140 * 18141 * @param scrollX New X scroll value in pixels 18142 * @param scrollY New Y scroll value in pixels 18143 * @param clampedX True if scrollX was clamped to an over-scroll boundary 18144 * @param clampedY True if scrollY was clamped to an over-scroll boundary 18145 */ 18146 protected void onOverScrolled(int scrollX, int scrollY, 18147 boolean clampedX, boolean clampedY) { 18148 // Intentionally empty. 18149 } 18150 18151 /** 18152 * Returns the over-scroll mode for this view. The result will be 18153 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 18154 * (allow over-scrolling only if the view content is larger than the container), 18155 * or {@link #OVER_SCROLL_NEVER}. 18156 * 18157 * @return This view's over-scroll mode. 18158 */ 18159 public int getOverScrollMode() { 18160 return mOverScrollMode; 18161 } 18162 18163 /** 18164 * Set the over-scroll mode for this view. Valid over-scroll modes are 18165 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 18166 * (allow over-scrolling only if the view content is larger than the container), 18167 * or {@link #OVER_SCROLL_NEVER}. 18168 * 18169 * Setting the over-scroll mode of a view will have an effect only if the 18170 * view is capable of scrolling. 18171 * 18172 * @param overScrollMode The new over-scroll mode for this view. 18173 */ 18174 public void setOverScrollMode(int overScrollMode) { 18175 if (overScrollMode != OVER_SCROLL_ALWAYS && 18176 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 18177 overScrollMode != OVER_SCROLL_NEVER) { 18178 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 18179 } 18180 mOverScrollMode = overScrollMode; 18181 } 18182 18183 /** 18184 * Enable or disable nested scrolling for this view. 18185 * 18186 * <p>If this property is set to true the view will be permitted to initiate nested 18187 * scrolling operations with a compatible parent view in the current hierarchy. If this 18188 * view does not implement nested scrolling this will have no effect. Disabling nested scrolling 18189 * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping} 18190 * the nested scroll.</p> 18191 * 18192 * @param enabled true to enable nested scrolling, false to disable 18193 * 18194 * @see #isNestedScrollingEnabled() 18195 */ 18196 public void setNestedScrollingEnabled(boolean enabled) { 18197 if (enabled) { 18198 mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED; 18199 } else { 18200 stopNestedScroll(); 18201 mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED; 18202 } 18203 } 18204 18205 /** 18206 * Returns true if nested scrolling is enabled for this view. 18207 * 18208 * <p>If nested scrolling is enabled and this View class implementation supports it, 18209 * this view will act as a nested scrolling child view when applicable, forwarding data 18210 * about the scroll operation in progress to a compatible and cooperating nested scrolling 18211 * parent.</p> 18212 * 18213 * @return true if nested scrolling is enabled 18214 * 18215 * @see #setNestedScrollingEnabled(boolean) 18216 */ 18217 public boolean isNestedScrollingEnabled() { 18218 return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) == 18219 PFLAG3_NESTED_SCROLLING_ENABLED; 18220 } 18221 18222 /** 18223 * Begin a nestable scroll operation along the given axes. 18224 * 18225 * <p>A view starting a nested scroll promises to abide by the following contract:</p> 18226 * 18227 * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case 18228 * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}. 18229 * In the case of touch scrolling the nested scroll will be terminated automatically in 18230 * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}. 18231 * In the event of programmatic scrolling the caller must explicitly call 18232 * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p> 18233 * 18234 * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found. 18235 * If it returns false the caller may ignore the rest of this contract until the next scroll. 18236 * Calling startNestedScroll while a nested scroll is already in progress will return true.</p> 18237 * 18238 * <p>At each incremental step of the scroll the caller should invoke 18239 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} 18240 * once it has calculated the requested scrolling delta. If it returns true the nested scrolling 18241 * parent at least partially consumed the scroll and the caller should adjust the amount it 18242 * scrolls by.</p> 18243 * 18244 * <p>After applying the remainder of the scroll delta the caller should invoke 18245 * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing 18246 * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat 18247 * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}. 18248 * </p> 18249 * 18250 * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or 18251 * {@link #SCROLL_AXIS_VERTICAL}. 18252 * @return true if a cooperative parent was found and nested scrolling has been enabled for 18253 * the current gesture. 18254 * 18255 * @see #stopNestedScroll() 18256 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 18257 * @see #dispatchNestedScroll(int, int, int, int, int[]) 18258 */ 18259 public boolean startNestedScroll(int axes) { 18260 if (hasNestedScrollingParent()) { 18261 // Already in progress 18262 return true; 18263 } 18264 if (isNestedScrollingEnabled()) { 18265 ViewParent p = getParent(); 18266 View child = this; 18267 while (p != null) { 18268 try { 18269 if (p.onStartNestedScroll(child, this, axes)) { 18270 mNestedScrollingParent = p; 18271 p.onNestedScrollAccepted(child, this, axes); 18272 return true; 18273 } 18274 } catch (AbstractMethodError e) { 18275 Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " + 18276 "method onStartNestedScroll", e); 18277 // Allow the search upward to continue 18278 } 18279 if (p instanceof View) { 18280 child = (View) p; 18281 } 18282 p = p.getParent(); 18283 } 18284 } 18285 return false; 18286 } 18287 18288 /** 18289 * Stop a nested scroll in progress. 18290 * 18291 * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p> 18292 * 18293 * @see #startNestedScroll(int) 18294 */ 18295 public void stopNestedScroll() { 18296 if (mNestedScrollingParent != null) { 18297 mNestedScrollingParent.onStopNestedScroll(this); 18298 mNestedScrollingParent = null; 18299 } 18300 } 18301 18302 /** 18303 * Returns true if this view has a nested scrolling parent. 18304 * 18305 * <p>The presence of a nested scrolling parent indicates that this view has initiated 18306 * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p> 18307 * 18308 * @return whether this view has a nested scrolling parent 18309 */ 18310 public boolean hasNestedScrollingParent() { 18311 return mNestedScrollingParent != null; 18312 } 18313 18314 /** 18315 * Dispatch one step of a nested scroll in progress. 18316 * 18317 * <p>Implementations of views that support nested scrolling should call this to report 18318 * info about a scroll in progress to the current nested scrolling parent. If a nested scroll 18319 * is not currently in progress or nested scrolling is not 18320 * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p> 18321 * 18322 * <p>Compatible View implementations should also call 18323 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before 18324 * consuming a component of the scroll event themselves.</p> 18325 * 18326 * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step 18327 * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step 18328 * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view 18329 * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view 18330 * @param offsetInWindow Optional. If not null, on return this will contain the offset 18331 * in local view coordinates of this view from before this operation 18332 * to after it completes. View implementations may use this to adjust 18333 * expected input coordinate tracking. 18334 * @return true if the event was dispatched, false if it could not be dispatched. 18335 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 18336 */ 18337 public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, 18338 int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow) { 18339 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18340 if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) { 18341 int startX = 0; 18342 int startY = 0; 18343 if (offsetInWindow != null) { 18344 getLocationInWindow(offsetInWindow); 18345 startX = offsetInWindow[0]; 18346 startY = offsetInWindow[1]; 18347 } 18348 18349 mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed, 18350 dxUnconsumed, dyUnconsumed); 18351 18352 if (offsetInWindow != null) { 18353 getLocationInWindow(offsetInWindow); 18354 offsetInWindow[0] -= startX; 18355 offsetInWindow[1] -= startY; 18356 } 18357 return true; 18358 } else if (offsetInWindow != null) { 18359 // No motion, no dispatch. Keep offsetInWindow up to date. 18360 offsetInWindow[0] = 0; 18361 offsetInWindow[1] = 0; 18362 } 18363 } 18364 return false; 18365 } 18366 18367 /** 18368 * Dispatch one step of a nested scroll in progress before this view consumes any portion of it. 18369 * 18370 * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch. 18371 * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested 18372 * scrolling operation to consume some or all of the scroll operation before the child view 18373 * consumes it.</p> 18374 * 18375 * @param dx Horizontal scroll distance in pixels 18376 * @param dy Vertical scroll distance in pixels 18377 * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx 18378 * and consumed[1] the consumed dy. 18379 * @param offsetInWindow Optional. If not null, on return this will contain the offset 18380 * in local view coordinates of this view from before this operation 18381 * to after it completes. View implementations may use this to adjust 18382 * expected input coordinate tracking. 18383 * @return true if the parent consumed some or all of the scroll delta 18384 * @see #dispatchNestedScroll(int, int, int, int, int[]) 18385 */ 18386 public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) { 18387 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18388 if (dx != 0 || dy != 0) { 18389 int startX = 0; 18390 int startY = 0; 18391 if (offsetInWindow != null) { 18392 getLocationInWindow(offsetInWindow); 18393 startX = offsetInWindow[0]; 18394 startY = offsetInWindow[1]; 18395 } 18396 18397 if (consumed == null) { 18398 if (mTempNestedScrollConsumed == null) { 18399 mTempNestedScrollConsumed = new int[2]; 18400 } 18401 consumed = mTempNestedScrollConsumed; 18402 } 18403 consumed[0] = 0; 18404 consumed[1] = 0; 18405 mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed); 18406 18407 if (offsetInWindow != null) { 18408 getLocationInWindow(offsetInWindow); 18409 offsetInWindow[0] -= startX; 18410 offsetInWindow[1] -= startY; 18411 } 18412 return consumed[0] != 0 || consumed[1] != 0; 18413 } else if (offsetInWindow != null) { 18414 offsetInWindow[0] = 0; 18415 offsetInWindow[1] = 0; 18416 } 18417 } 18418 return false; 18419 } 18420 18421 /** 18422 * Dispatch a fling to a nested scrolling parent. 18423 * 18424 * <p>This method should be used to indicate that a nested scrolling child has detected 18425 * suitable conditions for a fling. Generally this means that a touch scroll has ended with a 18426 * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds 18427 * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity} 18428 * along a scrollable axis.</p> 18429 * 18430 * <p>If a nested scrolling child view would normally fling but it is at the edge of 18431 * its own content, it can use this method to delegate the fling to its nested scrolling 18432 * parent instead. The parent may optionally consume the fling or observe a child fling.</p> 18433 * 18434 * @param velocityX Horizontal fling velocity in pixels per second 18435 * @param velocityY Vertical fling velocity in pixels per second 18436 * @param consumed true if the child consumed the fling, false otherwise 18437 * @return true if the nested scrolling parent consumed or otherwise reacted to the fling 18438 */ 18439 public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) { 18440 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18441 return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed); 18442 } 18443 return false; 18444 } 18445 18446 /** 18447 * Gets a scale factor that determines the distance the view should scroll 18448 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 18449 * @return The vertical scroll scale factor. 18450 * @hide 18451 */ 18452 protected float getVerticalScrollFactor() { 18453 if (mVerticalScrollFactor == 0) { 18454 TypedValue outValue = new TypedValue(); 18455 if (!mContext.getTheme().resolveAttribute( 18456 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 18457 throw new IllegalStateException( 18458 "Expected theme to define listPreferredItemHeight."); 18459 } 18460 mVerticalScrollFactor = outValue.getDimension( 18461 mContext.getResources().getDisplayMetrics()); 18462 } 18463 return mVerticalScrollFactor; 18464 } 18465 18466 /** 18467 * Gets a scale factor that determines the distance the view should scroll 18468 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 18469 * @return The horizontal scroll scale factor. 18470 * @hide 18471 */ 18472 protected float getHorizontalScrollFactor() { 18473 // TODO: Should use something else. 18474 return getVerticalScrollFactor(); 18475 } 18476 18477 /** 18478 * Return the value specifying the text direction or policy that was set with 18479 * {@link #setTextDirection(int)}. 18480 * 18481 * @return the defined text direction. It can be one of: 18482 * 18483 * {@link #TEXT_DIRECTION_INHERIT}, 18484 * {@link #TEXT_DIRECTION_FIRST_STRONG} 18485 * {@link #TEXT_DIRECTION_ANY_RTL}, 18486 * {@link #TEXT_DIRECTION_LTR}, 18487 * {@link #TEXT_DIRECTION_RTL}, 18488 * {@link #TEXT_DIRECTION_LOCALE} 18489 * 18490 * @attr ref android.R.styleable#View_textDirection 18491 * 18492 * @hide 18493 */ 18494 @ViewDebug.ExportedProperty(category = "text", mapping = { 18495 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 18496 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 18497 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 18498 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 18499 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 18500 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 18501 }) 18502 public int getRawTextDirection() { 18503 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 18504 } 18505 18506 /** 18507 * Set the text direction. 18508 * 18509 * @param textDirection the direction to set. Should be one of: 18510 * 18511 * {@link #TEXT_DIRECTION_INHERIT}, 18512 * {@link #TEXT_DIRECTION_FIRST_STRONG} 18513 * {@link #TEXT_DIRECTION_ANY_RTL}, 18514 * {@link #TEXT_DIRECTION_LTR}, 18515 * {@link #TEXT_DIRECTION_RTL}, 18516 * {@link #TEXT_DIRECTION_LOCALE} 18517 * 18518 * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution 18519 * proceeds up the parent chain of the view to get the value. If there is no parent, then it will 18520 * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}. 18521 * 18522 * @attr ref android.R.styleable#View_textDirection 18523 */ 18524 public void setTextDirection(int textDirection) { 18525 if (getRawTextDirection() != textDirection) { 18526 // Reset the current text direction and the resolved one 18527 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 18528 resetResolvedTextDirection(); 18529 // Set the new text direction 18530 mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK); 18531 // Do resolution 18532 resolveTextDirection(); 18533 // Notify change 18534 onRtlPropertiesChanged(getLayoutDirection()); 18535 // Refresh 18536 requestLayout(); 18537 invalidate(true); 18538 } 18539 } 18540 18541 /** 18542 * Return the resolved text direction. 18543 * 18544 * @return the resolved text direction. Returns one of: 18545 * 18546 * {@link #TEXT_DIRECTION_FIRST_STRONG} 18547 * {@link #TEXT_DIRECTION_ANY_RTL}, 18548 * {@link #TEXT_DIRECTION_LTR}, 18549 * {@link #TEXT_DIRECTION_RTL}, 18550 * {@link #TEXT_DIRECTION_LOCALE} 18551 * 18552 * @attr ref android.R.styleable#View_textDirection 18553 */ 18554 @ViewDebug.ExportedProperty(category = "text", mapping = { 18555 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 18556 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 18557 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 18558 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 18559 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 18560 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 18561 }) 18562 public int getTextDirection() { 18563 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 18564 } 18565 18566 /** 18567 * Resolve the text direction. 18568 * 18569 * @return true if resolution has been done, false otherwise. 18570 * 18571 * @hide 18572 */ 18573 public boolean resolveTextDirection() { 18574 // Reset any previous text direction resolution 18575 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 18576 18577 if (hasRtlSupport()) { 18578 // Set resolved text direction flag depending on text direction flag 18579 final int textDirection = getRawTextDirection(); 18580 switch(textDirection) { 18581 case TEXT_DIRECTION_INHERIT: 18582 if (!canResolveTextDirection()) { 18583 // We cannot do the resolution if there is no parent, so use the default one 18584 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18585 // Resolution will need to happen again later 18586 return false; 18587 } 18588 18589 // Parent has not yet resolved, so we still return the default 18590 try { 18591 if (!mParent.isTextDirectionResolved()) { 18592 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18593 // Resolution will need to happen again later 18594 return false; 18595 } 18596 } catch (AbstractMethodError e) { 18597 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18598 " does not fully implement ViewParent", e); 18599 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED | 18600 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18601 return true; 18602 } 18603 18604 // Set current resolved direction to the same value as the parent's one 18605 int parentResolvedDirection; 18606 try { 18607 parentResolvedDirection = mParent.getTextDirection(); 18608 } catch (AbstractMethodError e) { 18609 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18610 " does not fully implement ViewParent", e); 18611 parentResolvedDirection = TEXT_DIRECTION_LTR; 18612 } 18613 switch (parentResolvedDirection) { 18614 case TEXT_DIRECTION_FIRST_STRONG: 18615 case TEXT_DIRECTION_ANY_RTL: 18616 case TEXT_DIRECTION_LTR: 18617 case TEXT_DIRECTION_RTL: 18618 case TEXT_DIRECTION_LOCALE: 18619 mPrivateFlags2 |= 18620 (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 18621 break; 18622 default: 18623 // Default resolved direction is "first strong" heuristic 18624 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18625 } 18626 break; 18627 case TEXT_DIRECTION_FIRST_STRONG: 18628 case TEXT_DIRECTION_ANY_RTL: 18629 case TEXT_DIRECTION_LTR: 18630 case TEXT_DIRECTION_RTL: 18631 case TEXT_DIRECTION_LOCALE: 18632 // Resolved direction is the same as text direction 18633 mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 18634 break; 18635 default: 18636 // Default resolved direction is "first strong" heuristic 18637 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18638 } 18639 } else { 18640 // Default resolved direction is "first strong" heuristic 18641 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18642 } 18643 18644 // Set to resolved 18645 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED; 18646 return true; 18647 } 18648 18649 /** 18650 * Check if text direction resolution can be done. 18651 * 18652 * @return true if text direction resolution can be done otherwise return false. 18653 */ 18654 public boolean canResolveTextDirection() { 18655 switch (getRawTextDirection()) { 18656 case TEXT_DIRECTION_INHERIT: 18657 if (mParent != null) { 18658 try { 18659 return mParent.canResolveTextDirection(); 18660 } catch (AbstractMethodError e) { 18661 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18662 " does not fully implement ViewParent", e); 18663 } 18664 } 18665 return false; 18666 18667 default: 18668 return true; 18669 } 18670 } 18671 18672 /** 18673 * Reset resolved text direction. Text direction will be resolved during a call to 18674 * {@link #onMeasure(int, int)}. 18675 * 18676 * @hide 18677 */ 18678 public void resetResolvedTextDirection() { 18679 // Reset any previous text direction resolution 18680 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 18681 // Set to default value 18682 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18683 } 18684 18685 /** 18686 * @return true if text direction is inherited. 18687 * 18688 * @hide 18689 */ 18690 public boolean isTextDirectionInherited() { 18691 return (getRawTextDirection() == TEXT_DIRECTION_INHERIT); 18692 } 18693 18694 /** 18695 * @return true if text direction is resolved. 18696 */ 18697 public boolean isTextDirectionResolved() { 18698 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED; 18699 } 18700 18701 /** 18702 * Return the value specifying the text alignment or policy that was set with 18703 * {@link #setTextAlignment(int)}. 18704 * 18705 * @return the defined text alignment. It can be one of: 18706 * 18707 * {@link #TEXT_ALIGNMENT_INHERIT}, 18708 * {@link #TEXT_ALIGNMENT_GRAVITY}, 18709 * {@link #TEXT_ALIGNMENT_CENTER}, 18710 * {@link #TEXT_ALIGNMENT_TEXT_START}, 18711 * {@link #TEXT_ALIGNMENT_TEXT_END}, 18712 * {@link #TEXT_ALIGNMENT_VIEW_START}, 18713 * {@link #TEXT_ALIGNMENT_VIEW_END} 18714 * 18715 * @attr ref android.R.styleable#View_textAlignment 18716 * 18717 * @hide 18718 */ 18719 @ViewDebug.ExportedProperty(category = "text", mapping = { 18720 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 18721 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 18722 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 18723 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 18724 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 18725 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 18726 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 18727 }) 18728 @TextAlignment 18729 public int getRawTextAlignment() { 18730 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 18731 } 18732 18733 /** 18734 * Set the text alignment. 18735 * 18736 * @param textAlignment The text alignment to set. Should be one of 18737 * 18738 * {@link #TEXT_ALIGNMENT_INHERIT}, 18739 * {@link #TEXT_ALIGNMENT_GRAVITY}, 18740 * {@link #TEXT_ALIGNMENT_CENTER}, 18741 * {@link #TEXT_ALIGNMENT_TEXT_START}, 18742 * {@link #TEXT_ALIGNMENT_TEXT_END}, 18743 * {@link #TEXT_ALIGNMENT_VIEW_START}, 18744 * {@link #TEXT_ALIGNMENT_VIEW_END} 18745 * 18746 * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution 18747 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 18748 * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}. 18749 * 18750 * @attr ref android.R.styleable#View_textAlignment 18751 */ 18752 public void setTextAlignment(@TextAlignment int textAlignment) { 18753 if (textAlignment != getRawTextAlignment()) { 18754 // Reset the current and resolved text alignment 18755 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 18756 resetResolvedTextAlignment(); 18757 // Set the new text alignment 18758 mPrivateFlags2 |= 18759 ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK); 18760 // Do resolution 18761 resolveTextAlignment(); 18762 // Notify change 18763 onRtlPropertiesChanged(getLayoutDirection()); 18764 // Refresh 18765 requestLayout(); 18766 invalidate(true); 18767 } 18768 } 18769 18770 /** 18771 * Return the resolved text alignment. 18772 * 18773 * @return the resolved text alignment. Returns one of: 18774 * 18775 * {@link #TEXT_ALIGNMENT_GRAVITY}, 18776 * {@link #TEXT_ALIGNMENT_CENTER}, 18777 * {@link #TEXT_ALIGNMENT_TEXT_START}, 18778 * {@link #TEXT_ALIGNMENT_TEXT_END}, 18779 * {@link #TEXT_ALIGNMENT_VIEW_START}, 18780 * {@link #TEXT_ALIGNMENT_VIEW_END} 18781 * 18782 * @attr ref android.R.styleable#View_textAlignment 18783 */ 18784 @ViewDebug.ExportedProperty(category = "text", mapping = { 18785 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 18786 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 18787 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 18788 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 18789 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 18790 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 18791 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 18792 }) 18793 @TextAlignment 18794 public int getTextAlignment() { 18795 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >> 18796 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 18797 } 18798 18799 /** 18800 * Resolve the text alignment. 18801 * 18802 * @return true if resolution has been done, false otherwise. 18803 * 18804 * @hide 18805 */ 18806 public boolean resolveTextAlignment() { 18807 // Reset any previous text alignment resolution 18808 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 18809 18810 if (hasRtlSupport()) { 18811 // Set resolved text alignment flag depending on text alignment flag 18812 final int textAlignment = getRawTextAlignment(); 18813 switch (textAlignment) { 18814 case TEXT_ALIGNMENT_INHERIT: 18815 // Check if we can resolve the text alignment 18816 if (!canResolveTextAlignment()) { 18817 // We cannot do the resolution if there is no parent so use the default 18818 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18819 // Resolution will need to happen again later 18820 return false; 18821 } 18822 18823 // Parent has not yet resolved, so we still return the default 18824 try { 18825 if (!mParent.isTextAlignmentResolved()) { 18826 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18827 // Resolution will need to happen again later 18828 return false; 18829 } 18830 } catch (AbstractMethodError e) { 18831 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18832 " does not fully implement ViewParent", e); 18833 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED | 18834 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18835 return true; 18836 } 18837 18838 int parentResolvedTextAlignment; 18839 try { 18840 parentResolvedTextAlignment = mParent.getTextAlignment(); 18841 } catch (AbstractMethodError e) { 18842 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18843 " does not fully implement ViewParent", e); 18844 parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY; 18845 } 18846 switch (parentResolvedTextAlignment) { 18847 case TEXT_ALIGNMENT_GRAVITY: 18848 case TEXT_ALIGNMENT_TEXT_START: 18849 case TEXT_ALIGNMENT_TEXT_END: 18850 case TEXT_ALIGNMENT_CENTER: 18851 case TEXT_ALIGNMENT_VIEW_START: 18852 case TEXT_ALIGNMENT_VIEW_END: 18853 // Resolved text alignment is the same as the parent resolved 18854 // text alignment 18855 mPrivateFlags2 |= 18856 (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 18857 break; 18858 default: 18859 // Use default resolved text alignment 18860 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18861 } 18862 break; 18863 case TEXT_ALIGNMENT_GRAVITY: 18864 case TEXT_ALIGNMENT_TEXT_START: 18865 case TEXT_ALIGNMENT_TEXT_END: 18866 case TEXT_ALIGNMENT_CENTER: 18867 case TEXT_ALIGNMENT_VIEW_START: 18868 case TEXT_ALIGNMENT_VIEW_END: 18869 // Resolved text alignment is the same as text alignment 18870 mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 18871 break; 18872 default: 18873 // Use default resolved text alignment 18874 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18875 } 18876 } else { 18877 // Use default resolved text alignment 18878 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18879 } 18880 18881 // Set the resolved 18882 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED; 18883 return true; 18884 } 18885 18886 /** 18887 * Check if text alignment resolution can be done. 18888 * 18889 * @return true if text alignment resolution can be done otherwise return false. 18890 */ 18891 public boolean canResolveTextAlignment() { 18892 switch (getRawTextAlignment()) { 18893 case TEXT_DIRECTION_INHERIT: 18894 if (mParent != null) { 18895 try { 18896 return mParent.canResolveTextAlignment(); 18897 } catch (AbstractMethodError e) { 18898 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18899 " does not fully implement ViewParent", e); 18900 } 18901 } 18902 return false; 18903 18904 default: 18905 return true; 18906 } 18907 } 18908 18909 /** 18910 * Reset resolved text alignment. Text alignment will be resolved during a call to 18911 * {@link #onMeasure(int, int)}. 18912 * 18913 * @hide 18914 */ 18915 public void resetResolvedTextAlignment() { 18916 // Reset any previous text alignment resolution 18917 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 18918 // Set to default 18919 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18920 } 18921 18922 /** 18923 * @return true if text alignment is inherited. 18924 * 18925 * @hide 18926 */ 18927 public boolean isTextAlignmentInherited() { 18928 return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT); 18929 } 18930 18931 /** 18932 * @return true if text alignment is resolved. 18933 */ 18934 public boolean isTextAlignmentResolved() { 18935 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED; 18936 } 18937 18938 /** 18939 * Generate a value suitable for use in {@link #setId(int)}. 18940 * This value will not collide with ID values generated at build time by aapt for R.id. 18941 * 18942 * @return a generated ID value 18943 */ 18944 public static int generateViewId() { 18945 for (;;) { 18946 final int result = sNextGeneratedId.get(); 18947 // aapt-generated IDs have the high byte nonzero; clamp to the range under that. 18948 int newValue = result + 1; 18949 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. 18950 if (sNextGeneratedId.compareAndSet(result, newValue)) { 18951 return result; 18952 } 18953 } 18954 } 18955 18956 /** 18957 * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions. 18958 * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and 18959 * a normal View or a ViewGroup with 18960 * {@link android.view.ViewGroup#isTransitionGroup()} true. 18961 * @hide 18962 */ 18963 public void captureTransitioningViews(List<View> transitioningViews) { 18964 if (getVisibility() == View.VISIBLE) { 18965 transitioningViews.add(this); 18966 } 18967 } 18968 18969 /** 18970 * Adds all Views that have {@link #getTransitionName()} non-null to namedElements. 18971 * @param namedElements Will contain all Views in the hierarchy having a transitionName. 18972 * @hide 18973 */ 18974 public void findNamedViews(Map<String, View> namedElements) { 18975 if (getVisibility() == VISIBLE) { 18976 String transitionName = getTransitionName(); 18977 if (transitionName != null) { 18978 namedElements.put(transitionName, this); 18979 } 18980 } 18981 } 18982 18983 // 18984 // Properties 18985 // 18986 /** 18987 * A Property wrapper around the <code>alpha</code> functionality handled by the 18988 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 18989 */ 18990 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 18991 @Override 18992 public void setValue(View object, float value) { 18993 object.setAlpha(value); 18994 } 18995 18996 @Override 18997 public Float get(View object) { 18998 return object.getAlpha(); 18999 } 19000 }; 19001 19002 /** 19003 * A Property wrapper around the <code>translationX</code> functionality handled by the 19004 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 19005 */ 19006 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 19007 @Override 19008 public void setValue(View object, float value) { 19009 object.setTranslationX(value); 19010 } 19011 19012 @Override 19013 public Float get(View object) { 19014 return object.getTranslationX(); 19015 } 19016 }; 19017 19018 /** 19019 * A Property wrapper around the <code>translationY</code> functionality handled by the 19020 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 19021 */ 19022 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 19023 @Override 19024 public void setValue(View object, float value) { 19025 object.setTranslationY(value); 19026 } 19027 19028 @Override 19029 public Float get(View object) { 19030 return object.getTranslationY(); 19031 } 19032 }; 19033 19034 /** 19035 * A Property wrapper around the <code>translationZ</code> functionality handled by the 19036 * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods. 19037 */ 19038 public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") { 19039 @Override 19040 public void setValue(View object, float value) { 19041 object.setTranslationZ(value); 19042 } 19043 19044 @Override 19045 public Float get(View object) { 19046 return object.getTranslationZ(); 19047 } 19048 }; 19049 19050 /** 19051 * A Property wrapper around the <code>x</code> functionality handled by the 19052 * {@link View#setX(float)} and {@link View#getX()} methods. 19053 */ 19054 public static final Property<View, Float> X = new FloatProperty<View>("x") { 19055 @Override 19056 public void setValue(View object, float value) { 19057 object.setX(value); 19058 } 19059 19060 @Override 19061 public Float get(View object) { 19062 return object.getX(); 19063 } 19064 }; 19065 19066 /** 19067 * A Property wrapper around the <code>y</code> functionality handled by the 19068 * {@link View#setY(float)} and {@link View#getY()} methods. 19069 */ 19070 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 19071 @Override 19072 public void setValue(View object, float value) { 19073 object.setY(value); 19074 } 19075 19076 @Override 19077 public Float get(View object) { 19078 return object.getY(); 19079 } 19080 }; 19081 19082 /** 19083 * A Property wrapper around the <code>z</code> functionality handled by the 19084 * {@link View#setZ(float)} and {@link View#getZ()} methods. 19085 */ 19086 public static final Property<View, Float> Z = new FloatProperty<View>("z") { 19087 @Override 19088 public void setValue(View object, float value) { 19089 object.setZ(value); 19090 } 19091 19092 @Override 19093 public Float get(View object) { 19094 return object.getZ(); 19095 } 19096 }; 19097 19098 /** 19099 * A Property wrapper around the <code>rotation</code> functionality handled by the 19100 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 19101 */ 19102 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 19103 @Override 19104 public void setValue(View object, float value) { 19105 object.setRotation(value); 19106 } 19107 19108 @Override 19109 public Float get(View object) { 19110 return object.getRotation(); 19111 } 19112 }; 19113 19114 /** 19115 * A Property wrapper around the <code>rotationX</code> functionality handled by the 19116 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 19117 */ 19118 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 19119 @Override 19120 public void setValue(View object, float value) { 19121 object.setRotationX(value); 19122 } 19123 19124 @Override 19125 public Float get(View object) { 19126 return object.getRotationX(); 19127 } 19128 }; 19129 19130 /** 19131 * A Property wrapper around the <code>rotationY</code> functionality handled by the 19132 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 19133 */ 19134 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 19135 @Override 19136 public void setValue(View object, float value) { 19137 object.setRotationY(value); 19138 } 19139 19140 @Override 19141 public Float get(View object) { 19142 return object.getRotationY(); 19143 } 19144 }; 19145 19146 /** 19147 * A Property wrapper around the <code>scaleX</code> functionality handled by the 19148 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 19149 */ 19150 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 19151 @Override 19152 public void setValue(View object, float value) { 19153 object.setScaleX(value); 19154 } 19155 19156 @Override 19157 public Float get(View object) { 19158 return object.getScaleX(); 19159 } 19160 }; 19161 19162 /** 19163 * A Property wrapper around the <code>scaleY</code> functionality handled by the 19164 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 19165 */ 19166 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 19167 @Override 19168 public void setValue(View object, float value) { 19169 object.setScaleY(value); 19170 } 19171 19172 @Override 19173 public Float get(View object) { 19174 return object.getScaleY(); 19175 } 19176 }; 19177 19178 /** 19179 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 19180 * Each MeasureSpec represents a requirement for either the width or the height. 19181 * A MeasureSpec is comprised of a size and a mode. There are three possible 19182 * modes: 19183 * <dl> 19184 * <dt>UNSPECIFIED</dt> 19185 * <dd> 19186 * The parent has not imposed any constraint on the child. It can be whatever size 19187 * it wants. 19188 * </dd> 19189 * 19190 * <dt>EXACTLY</dt> 19191 * <dd> 19192 * The parent has determined an exact size for the child. The child is going to be 19193 * given those bounds regardless of how big it wants to be. 19194 * </dd> 19195 * 19196 * <dt>AT_MOST</dt> 19197 * <dd> 19198 * The child can be as large as it wants up to the specified size. 19199 * </dd> 19200 * </dl> 19201 * 19202 * MeasureSpecs are implemented as ints to reduce object allocation. This class 19203 * is provided to pack and unpack the <size, mode> tuple into the int. 19204 */ 19205 public static class MeasureSpec { 19206 private static final int MODE_SHIFT = 30; 19207 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 19208 19209 /** 19210 * Measure specification mode: The parent has not imposed any constraint 19211 * on the child. It can be whatever size it wants. 19212 */ 19213 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 19214 19215 /** 19216 * Measure specification mode: The parent has determined an exact size 19217 * for the child. The child is going to be given those bounds regardless 19218 * of how big it wants to be. 19219 */ 19220 public static final int EXACTLY = 1 << MODE_SHIFT; 19221 19222 /** 19223 * Measure specification mode: The child can be as large as it wants up 19224 * to the specified size. 19225 */ 19226 public static final int AT_MOST = 2 << MODE_SHIFT; 19227 19228 /** 19229 * Creates a measure specification based on the supplied size and mode. 19230 * 19231 * The mode must always be one of the following: 19232 * <ul> 19233 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 19234 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 19235 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 19236 * </ul> 19237 * 19238 * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's 19239 * implementation was such that the order of arguments did not matter 19240 * and overflow in either value could impact the resulting MeasureSpec. 19241 * {@link android.widget.RelativeLayout} was affected by this bug. 19242 * Apps targeting API levels greater than 17 will get the fixed, more strict 19243 * behavior.</p> 19244 * 19245 * @param size the size of the measure specification 19246 * @param mode the mode of the measure specification 19247 * @return the measure specification based on size and mode 19248 */ 19249 public static int makeMeasureSpec(int size, int mode) { 19250 if (sUseBrokenMakeMeasureSpec) { 19251 return size + mode; 19252 } else { 19253 return (size & ~MODE_MASK) | (mode & MODE_MASK); 19254 } 19255 } 19256 19257 /** 19258 * Extracts the mode from the supplied measure specification. 19259 * 19260 * @param measureSpec the measure specification to extract the mode from 19261 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 19262 * {@link android.view.View.MeasureSpec#AT_MOST} or 19263 * {@link android.view.View.MeasureSpec#EXACTLY} 19264 */ 19265 public static int getMode(int measureSpec) { 19266 return (measureSpec & MODE_MASK); 19267 } 19268 19269 /** 19270 * Extracts the size from the supplied measure specification. 19271 * 19272 * @param measureSpec the measure specification to extract the size from 19273 * @return the size in pixels defined in the supplied measure specification 19274 */ 19275 public static int getSize(int measureSpec) { 19276 return (measureSpec & ~MODE_MASK); 19277 } 19278 19279 static int adjust(int measureSpec, int delta) { 19280 final int mode = getMode(measureSpec); 19281 if (mode == UNSPECIFIED) { 19282 // No need to adjust size for UNSPECIFIED mode. 19283 return makeMeasureSpec(0, UNSPECIFIED); 19284 } 19285 int size = getSize(measureSpec) + delta; 19286 if (size < 0) { 19287 Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size + 19288 ") spec: " + toString(measureSpec) + " delta: " + delta); 19289 size = 0; 19290 } 19291 return makeMeasureSpec(size, mode); 19292 } 19293 19294 /** 19295 * Returns a String representation of the specified measure 19296 * specification. 19297 * 19298 * @param measureSpec the measure specification to convert to a String 19299 * @return a String with the following format: "MeasureSpec: MODE SIZE" 19300 */ 19301 public static String toString(int measureSpec) { 19302 int mode = getMode(measureSpec); 19303 int size = getSize(measureSpec); 19304 19305 StringBuilder sb = new StringBuilder("MeasureSpec: "); 19306 19307 if (mode == UNSPECIFIED) 19308 sb.append("UNSPECIFIED "); 19309 else if (mode == EXACTLY) 19310 sb.append("EXACTLY "); 19311 else if (mode == AT_MOST) 19312 sb.append("AT_MOST "); 19313 else 19314 sb.append(mode).append(" "); 19315 19316 sb.append(size); 19317 return sb.toString(); 19318 } 19319 } 19320 19321 private final class CheckForLongPress implements Runnable { 19322 private int mOriginalWindowAttachCount; 19323 19324 @Override 19325 public void run() { 19326 if (isPressed() && (mParent != null) 19327 && mOriginalWindowAttachCount == mWindowAttachCount) { 19328 if (performLongClick()) { 19329 mHasPerformedLongPress = true; 19330 } 19331 } 19332 } 19333 19334 public void rememberWindowAttachCount() { 19335 mOriginalWindowAttachCount = mWindowAttachCount; 19336 } 19337 } 19338 19339 private final class CheckForTap implements Runnable { 19340 public float x; 19341 public float y; 19342 19343 @Override 19344 public void run() { 19345 mPrivateFlags &= ~PFLAG_PREPRESSED; 19346 setPressed(true, x, y); 19347 checkForLongClick(ViewConfiguration.getTapTimeout()); 19348 } 19349 } 19350 19351 private final class PerformClick implements Runnable { 19352 @Override 19353 public void run() { 19354 performClick(); 19355 } 19356 } 19357 19358 /** @hide */ 19359 public void hackTurnOffWindowResizeAnim(boolean off) { 19360 mAttachInfo.mTurnOffWindowResizeAnim = off; 19361 } 19362 19363 /** 19364 * This method returns a ViewPropertyAnimator object, which can be used to animate 19365 * specific properties on this View. 19366 * 19367 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 19368 */ 19369 public ViewPropertyAnimator animate() { 19370 if (mAnimator == null) { 19371 mAnimator = new ViewPropertyAnimator(this); 19372 } 19373 return mAnimator; 19374 } 19375 19376 /** 19377 * Sets the name of the View to be used to identify Views in Transitions. 19378 * Names should be unique in the View hierarchy. 19379 * 19380 * @param transitionName The name of the View to uniquely identify it for Transitions. 19381 */ 19382 public final void setTransitionName(String transitionName) { 19383 mTransitionName = transitionName; 19384 } 19385 19386 /** 19387 * Returns the name of the View to be used to identify Views in Transitions. 19388 * Names should be unique in the View hierarchy. 19389 * 19390 * <p>This returns null if the View has not been given a name.</p> 19391 * 19392 * @return The name used of the View to be used to identify Views in Transitions or null 19393 * if no name has been given. 19394 */ 19395 public String getTransitionName() { 19396 return mTransitionName; 19397 } 19398 19399 /** 19400 * Interface definition for a callback to be invoked when a hardware key event is 19401 * dispatched to this view. The callback will be invoked before the key event is 19402 * given to the view. This is only useful for hardware keyboards; a software input 19403 * method has no obligation to trigger this listener. 19404 */ 19405 public interface OnKeyListener { 19406 /** 19407 * Called when a hardware key is dispatched to a view. This allows listeners to 19408 * get a chance to respond before the target view. 19409 * <p>Key presses in software keyboards will generally NOT trigger this method, 19410 * although some may elect to do so in some situations. Do not assume a 19411 * software input method has to be key-based; even if it is, it may use key presses 19412 * in a different way than you expect, so there is no way to reliably catch soft 19413 * input key presses. 19414 * 19415 * @param v The view the key has been dispatched to. 19416 * @param keyCode The code for the physical key that was pressed 19417 * @param event The KeyEvent object containing full information about 19418 * the event. 19419 * @return True if the listener has consumed the event, false otherwise. 19420 */ 19421 boolean onKey(View v, int keyCode, KeyEvent event); 19422 } 19423 19424 /** 19425 * Interface definition for a callback to be invoked when a touch event is 19426 * dispatched to this view. The callback will be invoked before the touch 19427 * event is given to the view. 19428 */ 19429 public interface OnTouchListener { 19430 /** 19431 * Called when a touch event is dispatched to a view. This allows listeners to 19432 * get a chance to respond before the target view. 19433 * 19434 * @param v The view the touch event has been dispatched to. 19435 * @param event The MotionEvent object containing full information about 19436 * the event. 19437 * @return True if the listener has consumed the event, false otherwise. 19438 */ 19439 boolean onTouch(View v, MotionEvent event); 19440 } 19441 19442 /** 19443 * Interface definition for a callback to be invoked when a hover event is 19444 * dispatched to this view. The callback will be invoked before the hover 19445 * event is given to the view. 19446 */ 19447 public interface OnHoverListener { 19448 /** 19449 * Called when a hover event is dispatched to a view. This allows listeners to 19450 * get a chance to respond before the target view. 19451 * 19452 * @param v The view the hover event has been dispatched to. 19453 * @param event The MotionEvent object containing full information about 19454 * the event. 19455 * @return True if the listener has consumed the event, false otherwise. 19456 */ 19457 boolean onHover(View v, MotionEvent event); 19458 } 19459 19460 /** 19461 * Interface definition for a callback to be invoked when a generic motion event is 19462 * dispatched to this view. The callback will be invoked before the generic motion 19463 * event is given to the view. 19464 */ 19465 public interface OnGenericMotionListener { 19466 /** 19467 * Called when a generic motion event is dispatched to a view. This allows listeners to 19468 * get a chance to respond before the target view. 19469 * 19470 * @param v The view the generic motion event has been dispatched to. 19471 * @param event The MotionEvent object containing full information about 19472 * the event. 19473 * @return True if the listener has consumed the event, false otherwise. 19474 */ 19475 boolean onGenericMotion(View v, MotionEvent event); 19476 } 19477 19478 /** 19479 * Interface definition for a callback to be invoked when a view has been clicked and held. 19480 */ 19481 public interface OnLongClickListener { 19482 /** 19483 * Called when a view has been clicked and held. 19484 * 19485 * @param v The view that was clicked and held. 19486 * 19487 * @return true if the callback consumed the long click, false otherwise. 19488 */ 19489 boolean onLongClick(View v); 19490 } 19491 19492 /** 19493 * Interface definition for a callback to be invoked when a drag is being dispatched 19494 * to this view. The callback will be invoked before the hosting view's own 19495 * onDrag(event) method. If the listener wants to fall back to the hosting view's 19496 * onDrag(event) behavior, it should return 'false' from this callback. 19497 * 19498 * <div class="special reference"> 19499 * <h3>Developer Guides</h3> 19500 * <p>For a guide to implementing drag and drop features, read the 19501 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 19502 * </div> 19503 */ 19504 public interface OnDragListener { 19505 /** 19506 * Called when a drag event is dispatched to a view. This allows listeners 19507 * to get a chance to override base View behavior. 19508 * 19509 * @param v The View that received the drag event. 19510 * @param event The {@link android.view.DragEvent} object for the drag event. 19511 * @return {@code true} if the drag event was handled successfully, or {@code false} 19512 * if the drag event was not handled. Note that {@code false} will trigger the View 19513 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 19514 */ 19515 boolean onDrag(View v, DragEvent event); 19516 } 19517 19518 /** 19519 * Interface definition for a callback to be invoked when the focus state of 19520 * a view changed. 19521 */ 19522 public interface OnFocusChangeListener { 19523 /** 19524 * Called when the focus state of a view has changed. 19525 * 19526 * @param v The view whose state has changed. 19527 * @param hasFocus The new focus state of v. 19528 */ 19529 void onFocusChange(View v, boolean hasFocus); 19530 } 19531 19532 /** 19533 * Interface definition for a callback to be invoked when a view is clicked. 19534 */ 19535 public interface OnClickListener { 19536 /** 19537 * Called when a view has been clicked. 19538 * 19539 * @param v The view that was clicked. 19540 */ 19541 void onClick(View v); 19542 } 19543 19544 /** 19545 * Interface definition for a callback to be invoked when the context menu 19546 * for this view is being built. 19547 */ 19548 public interface OnCreateContextMenuListener { 19549 /** 19550 * Called when the context menu for this view is being built. It is not 19551 * safe to hold onto the menu after this method returns. 19552 * 19553 * @param menu The context menu that is being built 19554 * @param v The view for which the context menu is being built 19555 * @param menuInfo Extra information about the item for which the 19556 * context menu should be shown. This information will vary 19557 * depending on the class of v. 19558 */ 19559 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 19560 } 19561 19562 /** 19563 * Interface definition for a callback to be invoked when the status bar changes 19564 * visibility. This reports <strong>global</strong> changes to the system UI 19565 * state, not what the application is requesting. 19566 * 19567 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 19568 */ 19569 public interface OnSystemUiVisibilityChangeListener { 19570 /** 19571 * Called when the status bar changes visibility because of a call to 19572 * {@link View#setSystemUiVisibility(int)}. 19573 * 19574 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 19575 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}. 19576 * This tells you the <strong>global</strong> state of these UI visibility 19577 * flags, not what your app is currently applying. 19578 */ 19579 public void onSystemUiVisibilityChange(int visibility); 19580 } 19581 19582 /** 19583 * Interface definition for a callback to be invoked when this view is attached 19584 * or detached from its window. 19585 */ 19586 public interface OnAttachStateChangeListener { 19587 /** 19588 * Called when the view is attached to a window. 19589 * @param v The view that was attached 19590 */ 19591 public void onViewAttachedToWindow(View v); 19592 /** 19593 * Called when the view is detached from a window. 19594 * @param v The view that was detached 19595 */ 19596 public void onViewDetachedFromWindow(View v); 19597 } 19598 19599 /** 19600 * Listener for applying window insets on a view in a custom way. 19601 * 19602 * <p>Apps may choose to implement this interface if they want to apply custom policy 19603 * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener 19604 * is set, its 19605 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 19606 * method will be called instead of the View's own 19607 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener 19608 * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply 19609 * the View's normal behavior as part of its own.</p> 19610 */ 19611 public interface OnApplyWindowInsetsListener { 19612 /** 19613 * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set} 19614 * on a View, this listener method will be called instead of the view's own 19615 * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 19616 * 19617 * @param v The view applying window insets 19618 * @param insets The insets to apply 19619 * @return The insets supplied, minus any insets that were consumed 19620 */ 19621 public WindowInsets onApplyWindowInsets(View v, WindowInsets insets); 19622 } 19623 19624 private final class UnsetPressedState implements Runnable { 19625 @Override 19626 public void run() { 19627 setPressed(false); 19628 } 19629 } 19630 19631 /** 19632 * Base class for derived classes that want to save and restore their own 19633 * state in {@link android.view.View#onSaveInstanceState()}. 19634 */ 19635 public static class BaseSavedState extends AbsSavedState { 19636 /** 19637 * Constructor used when reading from a parcel. Reads the state of the superclass. 19638 * 19639 * @param source 19640 */ 19641 public BaseSavedState(Parcel source) { 19642 super(source); 19643 } 19644 19645 /** 19646 * Constructor called by derived classes when creating their SavedState objects 19647 * 19648 * @param superState The state of the superclass of this view 19649 */ 19650 public BaseSavedState(Parcelable superState) { 19651 super(superState); 19652 } 19653 19654 public static final Parcelable.Creator<BaseSavedState> CREATOR = 19655 new Parcelable.Creator<BaseSavedState>() { 19656 public BaseSavedState createFromParcel(Parcel in) { 19657 return new BaseSavedState(in); 19658 } 19659 19660 public BaseSavedState[] newArray(int size) { 19661 return new BaseSavedState[size]; 19662 } 19663 }; 19664 } 19665 19666 /** 19667 * A set of information given to a view when it is attached to its parent 19668 * window. 19669 */ 19670 final static class AttachInfo { 19671 interface Callbacks { 19672 void playSoundEffect(int effectId); 19673 boolean performHapticFeedback(int effectId, boolean always); 19674 } 19675 19676 /** 19677 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 19678 * to a Handler. This class contains the target (View) to invalidate and 19679 * the coordinates of the dirty rectangle. 19680 * 19681 * For performance purposes, this class also implements a pool of up to 19682 * POOL_LIMIT objects that get reused. This reduces memory allocations 19683 * whenever possible. 19684 */ 19685 static class InvalidateInfo { 19686 private static final int POOL_LIMIT = 10; 19687 19688 private static final SynchronizedPool<InvalidateInfo> sPool = 19689 new SynchronizedPool<InvalidateInfo>(POOL_LIMIT); 19690 19691 View target; 19692 19693 int left; 19694 int top; 19695 int right; 19696 int bottom; 19697 19698 public static InvalidateInfo obtain() { 19699 InvalidateInfo instance = sPool.acquire(); 19700 return (instance != null) ? instance : new InvalidateInfo(); 19701 } 19702 19703 public void recycle() { 19704 target = null; 19705 sPool.release(this); 19706 } 19707 } 19708 19709 final IWindowSession mSession; 19710 19711 final IWindow mWindow; 19712 19713 final IBinder mWindowToken; 19714 19715 final Display mDisplay; 19716 19717 final Callbacks mRootCallbacks; 19718 19719 IWindowId mIWindowId; 19720 WindowId mWindowId; 19721 19722 /** 19723 * The top view of the hierarchy. 19724 */ 19725 View mRootView; 19726 19727 IBinder mPanelParentWindowToken; 19728 19729 boolean mHardwareAccelerated; 19730 boolean mHardwareAccelerationRequested; 19731 HardwareRenderer mHardwareRenderer; 19732 19733 /** 19734 * The state of the display to which the window is attached, as reported 19735 * by {@link Display#getState()}. Note that the display state constants 19736 * declared by {@link Display} do not exactly line up with the screen state 19737 * constants declared by {@link View} (there are more display states than 19738 * screen states). 19739 */ 19740 int mDisplayState = Display.STATE_UNKNOWN; 19741 19742 /** 19743 * Scale factor used by the compatibility mode 19744 */ 19745 float mApplicationScale; 19746 19747 /** 19748 * Indicates whether the application is in compatibility mode 19749 */ 19750 boolean mScalingRequired; 19751 19752 /** 19753 * If set, ViewRootImpl doesn't use its lame animation for when the window resizes. 19754 */ 19755 boolean mTurnOffWindowResizeAnim; 19756 19757 /** 19758 * Left position of this view's window 19759 */ 19760 int mWindowLeft; 19761 19762 /** 19763 * Top position of this view's window 19764 */ 19765 int mWindowTop; 19766 19767 /** 19768 * Indicates whether views need to use 32-bit drawing caches 19769 */ 19770 boolean mUse32BitDrawingCache; 19771 19772 /** 19773 * For windows that are full-screen but using insets to layout inside 19774 * of the screen areas, these are the current insets to appear inside 19775 * the overscan area of the display. 19776 */ 19777 final Rect mOverscanInsets = new Rect(); 19778 19779 /** 19780 * For windows that are full-screen but using insets to layout inside 19781 * of the screen decorations, these are the current insets for the 19782 * content of the window. 19783 */ 19784 final Rect mContentInsets = new Rect(); 19785 19786 /** 19787 * For windows that are full-screen but using insets to layout inside 19788 * of the screen decorations, these are the current insets for the 19789 * actual visible parts of the window. 19790 */ 19791 final Rect mVisibleInsets = new Rect(); 19792 19793 /** 19794 * For windows that are full-screen but using insets to layout inside 19795 * of the screen decorations, these are the current insets for the 19796 * stable system windows. 19797 */ 19798 final Rect mStableInsets = new Rect(); 19799 19800 /** 19801 * The internal insets given by this window. This value is 19802 * supplied by the client (through 19803 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 19804 * be given to the window manager when changed to be used in laying 19805 * out windows behind it. 19806 */ 19807 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 19808 = new ViewTreeObserver.InternalInsetsInfo(); 19809 19810 /** 19811 * Set to true when mGivenInternalInsets is non-empty. 19812 */ 19813 boolean mHasNonEmptyGivenInternalInsets; 19814 19815 /** 19816 * All views in the window's hierarchy that serve as scroll containers, 19817 * used to determine if the window can be resized or must be panned 19818 * to adjust for a soft input area. 19819 */ 19820 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 19821 19822 final KeyEvent.DispatcherState mKeyDispatchState 19823 = new KeyEvent.DispatcherState(); 19824 19825 /** 19826 * Indicates whether the view's window currently has the focus. 19827 */ 19828 boolean mHasWindowFocus; 19829 19830 /** 19831 * The current visibility of the window. 19832 */ 19833 int mWindowVisibility; 19834 19835 /** 19836 * Indicates the time at which drawing started to occur. 19837 */ 19838 long mDrawingTime; 19839 19840 /** 19841 * Indicates whether or not ignoring the DIRTY_MASK flags. 19842 */ 19843 boolean mIgnoreDirtyState; 19844 19845 /** 19846 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 19847 * to avoid clearing that flag prematurely. 19848 */ 19849 boolean mSetIgnoreDirtyState = false; 19850 19851 /** 19852 * Indicates whether the view's window is currently in touch mode. 19853 */ 19854 boolean mInTouchMode; 19855 19856 /** 19857 * Indicates whether the view has requested unbuffered input dispatching for the current 19858 * event stream. 19859 */ 19860 boolean mUnbufferedDispatchRequested; 19861 19862 /** 19863 * Indicates that ViewAncestor should trigger a global layout change 19864 * the next time it performs a traversal 19865 */ 19866 boolean mRecomputeGlobalAttributes; 19867 19868 /** 19869 * Always report new attributes at next traversal. 19870 */ 19871 boolean mForceReportNewAttributes; 19872 19873 /** 19874 * Set during a traveral if any views want to keep the screen on. 19875 */ 19876 boolean mKeepScreenOn; 19877 19878 /** 19879 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 19880 */ 19881 int mSystemUiVisibility; 19882 19883 /** 19884 * Hack to force certain system UI visibility flags to be cleared. 19885 */ 19886 int mDisabledSystemUiVisibility; 19887 19888 /** 19889 * Last global system UI visibility reported by the window manager. 19890 */ 19891 int mGlobalSystemUiVisibility; 19892 19893 /** 19894 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 19895 * attached. 19896 */ 19897 boolean mHasSystemUiListeners; 19898 19899 /** 19900 * Set if the window has requested to extend into the overscan region 19901 * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN. 19902 */ 19903 boolean mOverscanRequested; 19904 19905 /** 19906 * Set if the visibility of any views has changed. 19907 */ 19908 boolean mViewVisibilityChanged; 19909 19910 /** 19911 * Set to true if a view has been scrolled. 19912 */ 19913 boolean mViewScrollChanged; 19914 19915 /** 19916 * Global to the view hierarchy used as a temporary for dealing with 19917 * x/y points in the transparent region computations. 19918 */ 19919 final int[] mTransparentLocation = new int[2]; 19920 19921 /** 19922 * Global to the view hierarchy used as a temporary for dealing with 19923 * x/y points in the ViewGroup.invalidateChild implementation. 19924 */ 19925 final int[] mInvalidateChildLocation = new int[2]; 19926 19927 /** 19928 * Global to the view hierarchy used as a temporary for dealng with 19929 * computing absolute on-screen location. 19930 */ 19931 final int[] mTmpLocation = new int[2]; 19932 19933 /** 19934 * Global to the view hierarchy used as a temporary for dealing with 19935 * x/y location when view is transformed. 19936 */ 19937 final float[] mTmpTransformLocation = new float[2]; 19938 19939 /** 19940 * The view tree observer used to dispatch global events like 19941 * layout, pre-draw, touch mode change, etc. 19942 */ 19943 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 19944 19945 /** 19946 * A Canvas used by the view hierarchy to perform bitmap caching. 19947 */ 19948 Canvas mCanvas; 19949 19950 /** 19951 * The view root impl. 19952 */ 19953 final ViewRootImpl mViewRootImpl; 19954 19955 /** 19956 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 19957 * handler can be used to pump events in the UI events queue. 19958 */ 19959 final Handler mHandler; 19960 19961 /** 19962 * Temporary for use in computing invalidate rectangles while 19963 * calling up the hierarchy. 19964 */ 19965 final Rect mTmpInvalRect = new Rect(); 19966 19967 /** 19968 * Temporary for use in computing hit areas with transformed views 19969 */ 19970 final RectF mTmpTransformRect = new RectF(); 19971 19972 /** 19973 * Temporary for use in transforming invalidation rect 19974 */ 19975 final Matrix mTmpMatrix = new Matrix(); 19976 19977 /** 19978 * Temporary for use in transforming invalidation rect 19979 */ 19980 final Transformation mTmpTransformation = new Transformation(); 19981 19982 /** 19983 * Temporary for use in querying outlines from OutlineProviders 19984 */ 19985 final Outline mTmpOutline = new Outline(); 19986 19987 /** 19988 * Temporary list for use in collecting focusable descendents of a view. 19989 */ 19990 final ArrayList<View> mTempArrayList = new ArrayList<View>(24); 19991 19992 /** 19993 * The id of the window for accessibility purposes. 19994 */ 19995 int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 19996 19997 /** 19998 * Flags related to accessibility processing. 19999 * 20000 * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS 20001 * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS 20002 */ 20003 int mAccessibilityFetchFlags; 20004 20005 /** 20006 * The drawable for highlighting accessibility focus. 20007 */ 20008 Drawable mAccessibilityFocusDrawable; 20009 20010 /** 20011 * Show where the margins, bounds and layout bounds are for each view. 20012 */ 20013 boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false); 20014 20015 /** 20016 * Point used to compute visible regions. 20017 */ 20018 final Point mPoint = new Point(); 20019 20020 /** 20021 * Used to track which View originated a requestLayout() call, used when 20022 * requestLayout() is called during layout. 20023 */ 20024 View mViewRequestingLayout; 20025 20026 /** 20027 * Creates a new set of attachment information with the specified 20028 * events handler and thread. 20029 * 20030 * @param handler the events handler the view must use 20031 */ 20032 AttachInfo(IWindowSession session, IWindow window, Display display, 20033 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) { 20034 mSession = session; 20035 mWindow = window; 20036 mWindowToken = window.asBinder(); 20037 mDisplay = display; 20038 mViewRootImpl = viewRootImpl; 20039 mHandler = handler; 20040 mRootCallbacks = effectPlayer; 20041 } 20042 } 20043 20044 /** 20045 * <p>ScrollabilityCache holds various fields used by a View when scrolling 20046 * is supported. This avoids keeping too many unused fields in most 20047 * instances of View.</p> 20048 */ 20049 private static class ScrollabilityCache implements Runnable { 20050 20051 /** 20052 * Scrollbars are not visible 20053 */ 20054 public static final int OFF = 0; 20055 20056 /** 20057 * Scrollbars are visible 20058 */ 20059 public static final int ON = 1; 20060 20061 /** 20062 * Scrollbars are fading away 20063 */ 20064 public static final int FADING = 2; 20065 20066 public boolean fadeScrollBars; 20067 20068 public int fadingEdgeLength; 20069 public int scrollBarDefaultDelayBeforeFade; 20070 public int scrollBarFadeDuration; 20071 20072 public int scrollBarSize; 20073 public ScrollBarDrawable scrollBar; 20074 public float[] interpolatorValues; 20075 public View host; 20076 20077 public final Paint paint; 20078 public final Matrix matrix; 20079 public Shader shader; 20080 20081 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 20082 20083 private static final float[] OPAQUE = { 255 }; 20084 private static final float[] TRANSPARENT = { 0.0f }; 20085 20086 /** 20087 * When fading should start. This time moves into the future every time 20088 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 20089 */ 20090 public long fadeStartTime; 20091 20092 20093 /** 20094 * The current state of the scrollbars: ON, OFF, or FADING 20095 */ 20096 public int state = OFF; 20097 20098 private int mLastColor; 20099 20100 public ScrollabilityCache(ViewConfiguration configuration, View host) { 20101 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 20102 scrollBarSize = configuration.getScaledScrollBarSize(); 20103 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 20104 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 20105 20106 paint = new Paint(); 20107 matrix = new Matrix(); 20108 // use use a height of 1, and then wack the matrix each time we 20109 // actually use it. 20110 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 20111 paint.setShader(shader); 20112 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 20113 20114 this.host = host; 20115 } 20116 20117 public void setFadeColor(int color) { 20118 if (color != mLastColor) { 20119 mLastColor = color; 20120 20121 if (color != 0) { 20122 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 20123 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 20124 paint.setShader(shader); 20125 // Restore the default transfer mode (src_over) 20126 paint.setXfermode(null); 20127 } else { 20128 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 20129 paint.setShader(shader); 20130 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 20131 } 20132 } 20133 } 20134 20135 public void run() { 20136 long now = AnimationUtils.currentAnimationTimeMillis(); 20137 if (now >= fadeStartTime) { 20138 20139 // the animation fades the scrollbars out by changing 20140 // the opacity (alpha) from fully opaque to fully 20141 // transparent 20142 int nextFrame = (int) now; 20143 int framesCount = 0; 20144 20145 Interpolator interpolator = scrollBarInterpolator; 20146 20147 // Start opaque 20148 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 20149 20150 // End transparent 20151 nextFrame += scrollBarFadeDuration; 20152 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 20153 20154 state = FADING; 20155 20156 // Kick off the fade animation 20157 host.invalidate(true); 20158 } 20159 } 20160 } 20161 20162 /** 20163 * Resuable callback for sending 20164 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 20165 */ 20166 private class SendViewScrolledAccessibilityEvent implements Runnable { 20167 public volatile boolean mIsPending; 20168 20169 public void run() { 20170 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 20171 mIsPending = false; 20172 } 20173 } 20174 20175 /** 20176 * <p> 20177 * This class represents a delegate that can be registered in a {@link View} 20178 * to enhance accessibility support via composition rather via inheritance. 20179 * It is specifically targeted to widget developers that extend basic View 20180 * classes i.e. classes in package android.view, that would like their 20181 * applications to be backwards compatible. 20182 * </p> 20183 * <div class="special reference"> 20184 * <h3>Developer Guides</h3> 20185 * <p>For more information about making applications accessible, read the 20186 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a> 20187 * developer guide.</p> 20188 * </div> 20189 * <p> 20190 * A scenario in which a developer would like to use an accessibility delegate 20191 * is overriding a method introduced in a later API version then the minimal API 20192 * version supported by the application. For example, the method 20193 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 20194 * in API version 4 when the accessibility APIs were first introduced. If a 20195 * developer would like his application to run on API version 4 devices (assuming 20196 * all other APIs used by the application are version 4 or lower) and take advantage 20197 * of this method, instead of overriding the method which would break the application's 20198 * backwards compatibility, he can override the corresponding method in this 20199 * delegate and register the delegate in the target View if the API version of 20200 * the system is high enough i.e. the API version is same or higher to the API 20201 * version that introduced 20202 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 20203 * </p> 20204 * <p> 20205 * Here is an example implementation: 20206 * </p> 20207 * <code><pre><p> 20208 * if (Build.VERSION.SDK_INT >= 14) { 20209 * // If the API version is equal of higher than the version in 20210 * // which onInitializeAccessibilityNodeInfo was introduced we 20211 * // register a delegate with a customized implementation. 20212 * View view = findViewById(R.id.view_id); 20213 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 20214 * public void onInitializeAccessibilityNodeInfo(View host, 20215 * AccessibilityNodeInfo info) { 20216 * // Let the default implementation populate the info. 20217 * super.onInitializeAccessibilityNodeInfo(host, info); 20218 * // Set some other information. 20219 * info.setEnabled(host.isEnabled()); 20220 * } 20221 * }); 20222 * } 20223 * </code></pre></p> 20224 * <p> 20225 * This delegate contains methods that correspond to the accessibility methods 20226 * in View. If a delegate has been specified the implementation in View hands 20227 * off handling to the corresponding method in this delegate. The default 20228 * implementation the delegate methods behaves exactly as the corresponding 20229 * method in View for the case of no accessibility delegate been set. Hence, 20230 * to customize the behavior of a View method, clients can override only the 20231 * corresponding delegate method without altering the behavior of the rest 20232 * accessibility related methods of the host view. 20233 * </p> 20234 */ 20235 public static class AccessibilityDelegate { 20236 20237 /** 20238 * Sends an accessibility event of the given type. If accessibility is not 20239 * enabled this method has no effect. 20240 * <p> 20241 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 20242 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 20243 * been set. 20244 * </p> 20245 * 20246 * @param host The View hosting the delegate. 20247 * @param eventType The type of the event to send. 20248 * 20249 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 20250 */ 20251 public void sendAccessibilityEvent(View host, int eventType) { 20252 host.sendAccessibilityEventInternal(eventType); 20253 } 20254 20255 /** 20256 * Performs the specified accessibility action on the view. For 20257 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 20258 * <p> 20259 * The default implementation behaves as 20260 * {@link View#performAccessibilityAction(int, Bundle) 20261 * View#performAccessibilityAction(int, Bundle)} for the case of 20262 * no accessibility delegate been set. 20263 * </p> 20264 * 20265 * @param action The action to perform. 20266 * @return Whether the action was performed. 20267 * 20268 * @see View#performAccessibilityAction(int, Bundle) 20269 * View#performAccessibilityAction(int, Bundle) 20270 */ 20271 public boolean performAccessibilityAction(View host, int action, Bundle args) { 20272 return host.performAccessibilityActionInternal(action, args); 20273 } 20274 20275 /** 20276 * Sends an accessibility event. This method behaves exactly as 20277 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 20278 * empty {@link AccessibilityEvent} and does not perform a check whether 20279 * accessibility is enabled. 20280 * <p> 20281 * The default implementation behaves as 20282 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20283 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 20284 * the case of no accessibility delegate been set. 20285 * </p> 20286 * 20287 * @param host The View hosting the delegate. 20288 * @param event The event to send. 20289 * 20290 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20291 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20292 */ 20293 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 20294 host.sendAccessibilityEventUncheckedInternal(event); 20295 } 20296 20297 /** 20298 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 20299 * to its children for adding their text content to the event. 20300 * <p> 20301 * The default implementation behaves as 20302 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20303 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 20304 * the case of no accessibility delegate been set. 20305 * </p> 20306 * 20307 * @param host The View hosting the delegate. 20308 * @param event The event. 20309 * @return True if the event population was completed. 20310 * 20311 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20312 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20313 */ 20314 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 20315 return host.dispatchPopulateAccessibilityEventInternal(event); 20316 } 20317 20318 /** 20319 * Gives a chance to the host View to populate the accessibility event with its 20320 * text content. 20321 * <p> 20322 * The default implementation behaves as 20323 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 20324 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 20325 * the case of no accessibility delegate been set. 20326 * </p> 20327 * 20328 * @param host The View hosting the delegate. 20329 * @param event The accessibility event which to populate. 20330 * 20331 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 20332 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 20333 */ 20334 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 20335 host.onPopulateAccessibilityEventInternal(event); 20336 } 20337 20338 /** 20339 * Initializes an {@link AccessibilityEvent} with information about the 20340 * the host View which is the event source. 20341 * <p> 20342 * The default implementation behaves as 20343 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 20344 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 20345 * the case of no accessibility delegate been set. 20346 * </p> 20347 * 20348 * @param host The View hosting the delegate. 20349 * @param event The event to initialize. 20350 * 20351 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 20352 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 20353 */ 20354 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 20355 host.onInitializeAccessibilityEventInternal(event); 20356 } 20357 20358 /** 20359 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 20360 * <p> 20361 * The default implementation behaves as 20362 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20363 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 20364 * the case of no accessibility delegate been set. 20365 * </p> 20366 * 20367 * @param host The View hosting the delegate. 20368 * @param info The instance to initialize. 20369 * 20370 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20371 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20372 */ 20373 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 20374 host.onInitializeAccessibilityNodeInfoInternal(info); 20375 } 20376 20377 /** 20378 * Called when a child of the host View has requested sending an 20379 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 20380 * to augment the event. 20381 * <p> 20382 * The default implementation behaves as 20383 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20384 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 20385 * the case of no accessibility delegate been set. 20386 * </p> 20387 * 20388 * @param host The View hosting the delegate. 20389 * @param child The child which requests sending the event. 20390 * @param event The event to be sent. 20391 * @return True if the event should be sent 20392 * 20393 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20394 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20395 */ 20396 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 20397 AccessibilityEvent event) { 20398 return host.onRequestSendAccessibilityEventInternal(child, event); 20399 } 20400 20401 /** 20402 * Gets the provider for managing a virtual view hierarchy rooted at this View 20403 * and reported to {@link android.accessibilityservice.AccessibilityService}s 20404 * that explore the window content. 20405 * <p> 20406 * The default implementation behaves as 20407 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 20408 * the case of no accessibility delegate been set. 20409 * </p> 20410 * 20411 * @return The provider. 20412 * 20413 * @see AccessibilityNodeProvider 20414 */ 20415 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 20416 return null; 20417 } 20418 20419 /** 20420 * Returns an {@link AccessibilityNodeInfo} representing the host view from the 20421 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 20422 * This method is responsible for obtaining an accessibility node info from a 20423 * pool of reusable instances and calling 20424 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host 20425 * view to initialize the former. 20426 * <p> 20427 * <strong>Note:</strong> The client is responsible for recycling the obtained 20428 * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object 20429 * creation. 20430 * </p> 20431 * <p> 20432 * The default implementation behaves as 20433 * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for 20434 * the case of no accessibility delegate been set. 20435 * </p> 20436 * @return A populated {@link AccessibilityNodeInfo}. 20437 * 20438 * @see AccessibilityNodeInfo 20439 * 20440 * @hide 20441 */ 20442 public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) { 20443 return host.createAccessibilityNodeInfoInternal(); 20444 } 20445 } 20446 20447 private class MatchIdPredicate implements Predicate<View> { 20448 public int mId; 20449 20450 @Override 20451 public boolean apply(View view) { 20452 return (view.mID == mId); 20453 } 20454 } 20455 20456 private class MatchLabelForPredicate implements Predicate<View> { 20457 private int mLabeledId; 20458 20459 @Override 20460 public boolean apply(View view) { 20461 return (view.mLabelForId == mLabeledId); 20462 } 20463 } 20464 20465 private class SendViewStateChangedAccessibilityEvent implements Runnable { 20466 private int mChangeTypes = 0; 20467 private boolean mPosted; 20468 private boolean mPostedWithDelay; 20469 private long mLastEventTimeMillis; 20470 20471 @Override 20472 public void run() { 20473 mPosted = false; 20474 mPostedWithDelay = false; 20475 mLastEventTimeMillis = SystemClock.uptimeMillis(); 20476 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 20477 final AccessibilityEvent event = AccessibilityEvent.obtain(); 20478 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 20479 event.setContentChangeTypes(mChangeTypes); 20480 sendAccessibilityEventUnchecked(event); 20481 } 20482 mChangeTypes = 0; 20483 } 20484 20485 public void runOrPost(int changeType) { 20486 mChangeTypes |= changeType; 20487 20488 // If this is a live region or the child of a live region, collect 20489 // all events from this frame and send them on the next frame. 20490 if (inLiveRegion()) { 20491 // If we're already posted with a delay, remove that. 20492 if (mPostedWithDelay) { 20493 removeCallbacks(this); 20494 mPostedWithDelay = false; 20495 } 20496 // Only post if we're not already posted. 20497 if (!mPosted) { 20498 post(this); 20499 mPosted = true; 20500 } 20501 return; 20502 } 20503 20504 if (mPosted) { 20505 return; 20506 } 20507 final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis; 20508 final long minEventIntevalMillis = 20509 ViewConfiguration.getSendRecurringAccessibilityEventsInterval(); 20510 if (timeSinceLastMillis >= minEventIntevalMillis) { 20511 removeCallbacks(this); 20512 run(); 20513 } else { 20514 postDelayed(this, minEventIntevalMillis - timeSinceLastMillis); 20515 mPosted = true; 20516 mPostedWithDelay = true; 20517 } 20518 } 20519 } 20520 20521 private boolean inLiveRegion() { 20522 if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) { 20523 return true; 20524 } 20525 20526 ViewParent parent = getParent(); 20527 while (parent instanceof View) { 20528 if (((View) parent).getAccessibilityLiveRegion() 20529 != View.ACCESSIBILITY_LIVE_REGION_NONE) { 20530 return true; 20531 } 20532 parent = parent.getParent(); 20533 } 20534 20535 return false; 20536 } 20537 20538 /** 20539 * Dump all private flags in readable format, useful for documentation and 20540 * sanity checking. 20541 */ 20542 private static void dumpFlags() { 20543 final HashMap<String, String> found = Maps.newHashMap(); 20544 try { 20545 for (Field field : View.class.getDeclaredFields()) { 20546 final int modifiers = field.getModifiers(); 20547 if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { 20548 if (field.getType().equals(int.class)) { 20549 final int value = field.getInt(null); 20550 dumpFlag(found, field.getName(), value); 20551 } else if (field.getType().equals(int[].class)) { 20552 final int[] values = (int[]) field.get(null); 20553 for (int i = 0; i < values.length; i++) { 20554 dumpFlag(found, field.getName() + "[" + i + "]", values[i]); 20555 } 20556 } 20557 } 20558 } 20559 } catch (IllegalAccessException e) { 20560 throw new RuntimeException(e); 20561 } 20562 20563 final ArrayList<String> keys = Lists.newArrayList(); 20564 keys.addAll(found.keySet()); 20565 Collections.sort(keys); 20566 for (String key : keys) { 20567 Log.d(VIEW_LOG_TAG, found.get(key)); 20568 } 20569 } 20570 20571 private static void dumpFlag(HashMap<String, String> found, String name, int value) { 20572 // Sort flags by prefix, then by bits, always keeping unique keys 20573 final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' '); 20574 final int prefix = name.indexOf('_'); 20575 final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name; 20576 final String output = bits + " " + name; 20577 found.put(key, output); 20578 } 20579} 20580