View.java revision 42dda81e15490193fe5a9d10464dd9049c3362cc
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.RevealAnimator; 20import android.animation.ValueAnimator; 21import android.annotation.IntDef; 22import android.annotation.NonNull; 23import android.annotation.Nullable; 24import android.content.ClipData; 25import android.content.Context; 26import android.content.res.Configuration; 27import android.content.res.Resources; 28import android.content.res.TypedArray; 29import android.graphics.Bitmap; 30import android.graphics.Camera; 31import android.graphics.Canvas; 32import android.graphics.Insets; 33import android.graphics.Interpolator; 34import android.graphics.LinearGradient; 35import android.graphics.Matrix; 36import android.graphics.Outline; 37import android.graphics.Paint; 38import android.graphics.PixelFormat; 39import android.graphics.Point; 40import android.graphics.PorterDuff; 41import android.graphics.PorterDuffXfermode; 42import android.graphics.Rect; 43import android.graphics.RectF; 44import android.graphics.Region; 45import android.graphics.Shader; 46import android.graphics.drawable.ColorDrawable; 47import android.graphics.drawable.Drawable; 48import android.hardware.display.DisplayManagerGlobal; 49import android.os.Bundle; 50import android.os.Handler; 51import android.os.IBinder; 52import android.os.Parcel; 53import android.os.Parcelable; 54import android.os.RemoteException; 55import android.os.SystemClock; 56import android.os.SystemProperties; 57import android.text.TextUtils; 58import android.util.AttributeSet; 59import android.util.FloatProperty; 60import android.util.LayoutDirection; 61import android.util.Log; 62import android.util.LongSparseLongArray; 63import android.util.Pools.SynchronizedPool; 64import android.util.Property; 65import android.util.SparseArray; 66import android.util.SuperNotCalledException; 67import android.util.TypedValue; 68import android.view.ContextMenu.ContextMenuInfo; 69import android.view.AccessibilityIterators.TextSegmentIterator; 70import android.view.AccessibilityIterators.CharacterTextSegmentIterator; 71import android.view.AccessibilityIterators.WordTextSegmentIterator; 72import android.view.AccessibilityIterators.ParagraphTextSegmentIterator; 73import android.view.accessibility.AccessibilityEvent; 74import android.view.accessibility.AccessibilityEventSource; 75import android.view.accessibility.AccessibilityManager; 76import android.view.accessibility.AccessibilityNodeInfo; 77import android.view.accessibility.AccessibilityNodeProvider; 78import android.view.animation.Animation; 79import android.view.animation.AnimationUtils; 80import android.view.animation.Transformation; 81import android.view.inputmethod.EditorInfo; 82import android.view.inputmethod.InputConnection; 83import android.view.inputmethod.InputMethodManager; 84import android.widget.ScrollBarDrawable; 85 86import static android.os.Build.VERSION_CODES.*; 87import static java.lang.Math.max; 88 89import com.android.internal.R; 90import com.android.internal.util.Predicate; 91import com.android.internal.view.menu.MenuBuilder; 92import com.google.android.collect.Lists; 93import com.google.android.collect.Maps; 94 95import java.lang.annotation.Retention; 96import java.lang.annotation.RetentionPolicy; 97import java.lang.ref.WeakReference; 98import java.lang.reflect.Field; 99import java.lang.reflect.InvocationTargetException; 100import java.lang.reflect.Method; 101import java.lang.reflect.Modifier; 102import java.util.ArrayList; 103import java.util.Arrays; 104import java.util.Collections; 105import java.util.HashMap; 106import java.util.List; 107import java.util.Locale; 108import java.util.Map; 109import java.util.concurrent.CopyOnWriteArrayList; 110import java.util.concurrent.atomic.AtomicInteger; 111 112/** 113 * <p> 114 * This class represents the basic building block for user interface components. A View 115 * occupies a rectangular area on the screen and is responsible for drawing and 116 * event handling. View is the base class for <em>widgets</em>, which are 117 * used to create interactive UI components (buttons, text fields, etc.). The 118 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which 119 * are invisible containers that hold other Views (or other ViewGroups) and define 120 * their layout properties. 121 * </p> 122 * 123 * <div class="special reference"> 124 * <h3>Developer Guides</h3> 125 * <p>For information about using this class to develop your application's user interface, 126 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide. 127 * </div> 128 * 129 * <a name="Using"></a> 130 * <h3>Using Views</h3> 131 * <p> 132 * All of the views in a window are arranged in a single tree. You can add views 133 * either from code or by specifying a tree of views in one or more XML layout 134 * files. There are many specialized subclasses of views that act as controls or 135 * are capable of displaying text, images, or other content. 136 * </p> 137 * <p> 138 * Once you have created a tree of views, there are typically a few types of 139 * common operations you may wish to perform: 140 * <ul> 141 * <li><strong>Set properties:</strong> for example setting the text of a 142 * {@link android.widget.TextView}. The available properties and the methods 143 * that set them will vary among the different subclasses of views. Note that 144 * properties that are known at build time can be set in the XML layout 145 * files.</li> 146 * <li><strong>Set focus:</strong> The framework will handled moving focus in 147 * response to user input. To force focus to a specific view, call 148 * {@link #requestFocus}.</li> 149 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 150 * that will be notified when something interesting happens to the view. For 151 * example, all views will let you set a listener to be notified when the view 152 * gains or loses focus. You can register such a listener using 153 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}. 154 * Other view subclasses offer more specialized listeners. For example, a Button 155 * exposes a listener to notify clients when the button is clicked.</li> 156 * <li><strong>Set visibility:</strong> You can hide or show views using 157 * {@link #setVisibility(int)}.</li> 158 * </ul> 159 * </p> 160 * <p><em> 161 * Note: The Android framework is responsible for measuring, laying out and 162 * drawing views. You should not call methods that perform these actions on 163 * views yourself unless you are actually implementing a 164 * {@link android.view.ViewGroup}. 165 * </em></p> 166 * 167 * <a name="Lifecycle"></a> 168 * <h3>Implementing a Custom View</h3> 169 * 170 * <p> 171 * To implement a custom view, you will usually begin by providing overrides for 172 * some of the standard methods that the framework calls on all views. You do 173 * not need to override all of these methods. In fact, you can start by just 174 * overriding {@link #onDraw(android.graphics.Canvas)}. 175 * <table border="2" width="85%" align="center" cellpadding="5"> 176 * <thead> 177 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 178 * </thead> 179 * 180 * <tbody> 181 * <tr> 182 * <td rowspan="2">Creation</td> 183 * <td>Constructors</td> 184 * <td>There is a form of the constructor that are called when the view 185 * is created from code and a form that is called when the view is 186 * inflated from a layout file. The second form should parse and apply 187 * any attributes defined in the layout file. 188 * </td> 189 * </tr> 190 * <tr> 191 * <td><code>{@link #onFinishInflate()}</code></td> 192 * <td>Called after a view and all of its children has been inflated 193 * from XML.</td> 194 * </tr> 195 * 196 * <tr> 197 * <td rowspan="3">Layout</td> 198 * <td><code>{@link #onMeasure(int, int)}</code></td> 199 * <td>Called to determine the size requirements for this view and all 200 * of its children. 201 * </td> 202 * </tr> 203 * <tr> 204 * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td> 205 * <td>Called when this view should assign a size and position to all 206 * of its children. 207 * </td> 208 * </tr> 209 * <tr> 210 * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td> 211 * <td>Called when the size of this view has changed. 212 * </td> 213 * </tr> 214 * 215 * <tr> 216 * <td>Drawing</td> 217 * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td> 218 * <td>Called when the view should render its content. 219 * </td> 220 * </tr> 221 * 222 * <tr> 223 * <td rowspan="4">Event processing</td> 224 * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td> 225 * <td>Called when a new hardware key event occurs. 226 * </td> 227 * </tr> 228 * <tr> 229 * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td> 230 * <td>Called when a hardware key up event occurs. 231 * </td> 232 * </tr> 233 * <tr> 234 * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td> 235 * <td>Called when a trackball motion event occurs. 236 * </td> 237 * </tr> 238 * <tr> 239 * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td> 240 * <td>Called when a touch screen motion event occurs. 241 * </td> 242 * </tr> 243 * 244 * <tr> 245 * <td rowspan="2">Focus</td> 246 * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td> 247 * <td>Called when the view gains or loses focus. 248 * </td> 249 * </tr> 250 * 251 * <tr> 252 * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td> 253 * <td>Called when the window containing the view gains or loses focus. 254 * </td> 255 * </tr> 256 * 257 * <tr> 258 * <td rowspan="3">Attaching</td> 259 * <td><code>{@link #onAttachedToWindow()}</code></td> 260 * <td>Called when the view is attached to a window. 261 * </td> 262 * </tr> 263 * 264 * <tr> 265 * <td><code>{@link #onDetachedFromWindow}</code></td> 266 * <td>Called when the view is detached from its window. 267 * </td> 268 * </tr> 269 * 270 * <tr> 271 * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td> 272 * <td>Called when the visibility of the window containing the view 273 * has changed. 274 * </td> 275 * </tr> 276 * </tbody> 277 * 278 * </table> 279 * </p> 280 * 281 * <a name="IDs"></a> 282 * <h3>IDs</h3> 283 * Views may have an integer id associated with them. These ids are typically 284 * assigned in the layout XML files, and are used to find specific views within 285 * the view tree. A common pattern is to: 286 * <ul> 287 * <li>Define a Button in the layout file and assign it a unique ID. 288 * <pre> 289 * <Button 290 * android:id="@+id/my_button" 291 * android:layout_width="wrap_content" 292 * android:layout_height="wrap_content" 293 * android:text="@string/my_button_text"/> 294 * </pre></li> 295 * <li>From the onCreate method of an Activity, find the Button 296 * <pre class="prettyprint"> 297 * Button myButton = (Button) findViewById(R.id.my_button); 298 * </pre></li> 299 * </ul> 300 * <p> 301 * View IDs need not be unique throughout the tree, but it is good practice to 302 * ensure that they are at least unique within the part of the tree you are 303 * searching. 304 * </p> 305 * 306 * <a name="Position"></a> 307 * <h3>Position</h3> 308 * <p> 309 * The geometry of a view is that of a rectangle. A view has a location, 310 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 311 * two dimensions, expressed as a width and a height. The unit for location 312 * and dimensions is the pixel. 313 * </p> 314 * 315 * <p> 316 * It is possible to retrieve the location of a view by invoking the methods 317 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 318 * coordinate of the rectangle representing the view. The latter returns the 319 * top, or Y, coordinate of the rectangle representing the view. These methods 320 * both return the location of the view relative to its parent. For instance, 321 * when getLeft() returns 20, that means the view is located 20 pixels to the 322 * right of the left edge of its direct parent. 323 * </p> 324 * 325 * <p> 326 * In addition, several convenience methods are offered to avoid unnecessary 327 * computations, namely {@link #getRight()} and {@link #getBottom()}. 328 * These methods return the coordinates of the right and bottom edges of the 329 * rectangle representing the view. For instance, calling {@link #getRight()} 330 * is similar to the following computation: <code>getLeft() + getWidth()</code> 331 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 332 * </p> 333 * 334 * <a name="SizePaddingMargins"></a> 335 * <h3>Size, padding and margins</h3> 336 * <p> 337 * The size of a view is expressed with a width and a height. A view actually 338 * possess two pairs of width and height values. 339 * </p> 340 * 341 * <p> 342 * The first pair is known as <em>measured width</em> and 343 * <em>measured height</em>. These dimensions define how big a view wants to be 344 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 345 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 346 * and {@link #getMeasuredHeight()}. 347 * </p> 348 * 349 * <p> 350 * The second pair is simply known as <em>width</em> and <em>height</em>, or 351 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 352 * dimensions define the actual size of the view on screen, at drawing time and 353 * after layout. These values may, but do not have to, be different from the 354 * measured width and height. The width and height can be obtained by calling 355 * {@link #getWidth()} and {@link #getHeight()}. 356 * </p> 357 * 358 * <p> 359 * To measure its dimensions, a view takes into account its padding. The padding 360 * is expressed in pixels for the left, top, right and bottom parts of the view. 361 * Padding can be used to offset the content of the view by a specific amount of 362 * pixels. For instance, a left padding of 2 will push the view's content by 363 * 2 pixels to the right of the left edge. Padding can be set using the 364 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)} 365 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 366 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()}, 367 * {@link #getPaddingEnd()}. 368 * </p> 369 * 370 * <p> 371 * Even though a view can define a padding, it does not provide any support for 372 * margins. However, view groups provide such a support. Refer to 373 * {@link android.view.ViewGroup} and 374 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 375 * </p> 376 * 377 * <a name="Layout"></a> 378 * <h3>Layout</h3> 379 * <p> 380 * Layout is a two pass process: a measure pass and a layout pass. The measuring 381 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 382 * of the view tree. Each view pushes dimension specifications down the tree 383 * during the recursion. At the end of the measure pass, every view has stored 384 * its measurements. The second pass happens in 385 * {@link #layout(int,int,int,int)} and is also top-down. During 386 * this pass each parent is responsible for positioning all of its children 387 * using the sizes computed in the measure pass. 388 * </p> 389 * 390 * <p> 391 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 392 * {@link #getMeasuredHeight()} values must be set, along with those for all of 393 * that view's descendants. A view's measured width and measured height values 394 * must respect the constraints imposed by the view's parents. This guarantees 395 * that at the end of the measure pass, all parents accept all of their 396 * children's measurements. A parent view may call measure() more than once on 397 * its children. For example, the parent may measure each child once with 398 * unspecified dimensions to find out how big they want to be, then call 399 * measure() on them again with actual numbers if the sum of all the children's 400 * unconstrained sizes is too big or too small. 401 * </p> 402 * 403 * <p> 404 * The measure pass uses two classes to communicate dimensions. The 405 * {@link MeasureSpec} class is used by views to tell their parents how they 406 * want to be measured and positioned. The base LayoutParams class just 407 * describes how big the view wants to be for both width and height. For each 408 * dimension, it can specify one of: 409 * <ul> 410 * <li> an exact number 411 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 412 * (minus padding) 413 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 414 * enclose its content (plus padding). 415 * </ul> 416 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 417 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 418 * an X and Y value. 419 * </p> 420 * 421 * <p> 422 * MeasureSpecs are used to push requirements down the tree from parent to 423 * child. A MeasureSpec can be in one of three modes: 424 * <ul> 425 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 426 * of a child view. For example, a LinearLayout may call measure() on its child 427 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 428 * tall the child view wants to be given a width of 240 pixels. 429 * <li>EXACTLY: This is used by the parent to impose an exact size on the 430 * child. The child must use this size, and guarantee that all of its 431 * descendants will fit within this size. 432 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 433 * child. The child must gurantee that it and all of its descendants will fit 434 * within this size. 435 * </ul> 436 * </p> 437 * 438 * <p> 439 * To intiate a layout, call {@link #requestLayout}. This method is typically 440 * called by a view on itself when it believes that is can no longer fit within 441 * its current bounds. 442 * </p> 443 * 444 * <a name="Drawing"></a> 445 * <h3>Drawing</h3> 446 * <p> 447 * Drawing is handled by walking the tree and rendering each view that 448 * intersects the invalid region. Because the tree is traversed in-order, 449 * this means that parents will draw before (i.e., behind) their children, with 450 * siblings drawn in the order they appear in the tree. 451 * If you set a background drawable for a View, then the View will draw it for you 452 * before calling back to its <code>onDraw()</code> method. 453 * </p> 454 * 455 * <p> 456 * Note that the framework will not draw views that are not in the invalid region. 457 * </p> 458 * 459 * <p> 460 * To force a view to draw, call {@link #invalidate()}. 461 * </p> 462 * 463 * <a name="EventHandlingThreading"></a> 464 * <h3>Event Handling and Threading</h3> 465 * <p> 466 * The basic cycle of a view is as follows: 467 * <ol> 468 * <li>An event comes in and is dispatched to the appropriate view. The view 469 * handles the event and notifies any listeners.</li> 470 * <li>If in the course of processing the event, the view's bounds may need 471 * to be changed, the view will call {@link #requestLayout()}.</li> 472 * <li>Similarly, if in the course of processing the event the view's appearance 473 * may need to be changed, the view will call {@link #invalidate()}.</li> 474 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 475 * the framework will take care of measuring, laying out, and drawing the tree 476 * as appropriate.</li> 477 * </ol> 478 * </p> 479 * 480 * <p><em>Note: The entire view tree is single threaded. You must always be on 481 * the UI thread when calling any method on any view.</em> 482 * If you are doing work on other threads and want to update the state of a view 483 * from that thread, you should use a {@link Handler}. 484 * </p> 485 * 486 * <a name="FocusHandling"></a> 487 * <h3>Focus Handling</h3> 488 * <p> 489 * The framework will handle routine focus movement in response to user input. 490 * This includes changing the focus as views are removed or hidden, or as new 491 * views become available. Views indicate their willingness to take focus 492 * through the {@link #isFocusable} method. To change whether a view can take 493 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 494 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 495 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 496 * </p> 497 * <p> 498 * Focus movement is based on an algorithm which finds the nearest neighbor in a 499 * given direction. In rare cases, the default algorithm may not match the 500 * intended behavior of the developer. In these situations, you can provide 501 * explicit overrides by using these XML attributes in the layout file: 502 * <pre> 503 * nextFocusDown 504 * nextFocusLeft 505 * nextFocusRight 506 * nextFocusUp 507 * </pre> 508 * </p> 509 * 510 * 511 * <p> 512 * To get a particular view to take focus, call {@link #requestFocus()}. 513 * </p> 514 * 515 * <a name="TouchMode"></a> 516 * <h3>Touch Mode</h3> 517 * <p> 518 * When a user is navigating a user interface via directional keys such as a D-pad, it is 519 * necessary to give focus to actionable items such as buttons so the user can see 520 * what will take input. If the device has touch capabilities, however, and the user 521 * begins interacting with the interface by touching it, it is no longer necessary to 522 * always highlight, or give focus to, a particular view. This motivates a mode 523 * for interaction named 'touch mode'. 524 * </p> 525 * <p> 526 * For a touch capable device, once the user touches the screen, the device 527 * will enter touch mode. From this point onward, only views for which 528 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 529 * Other views that are touchable, like buttons, will not take focus when touched; they will 530 * only fire the on click listeners. 531 * </p> 532 * <p> 533 * Any time a user hits a directional key, such as a D-pad direction, the view device will 534 * exit touch mode, and find a view to take focus, so that the user may resume interacting 535 * with the user interface without touching the screen again. 536 * </p> 537 * <p> 538 * The touch mode state is maintained across {@link android.app.Activity}s. Call 539 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 540 * </p> 541 * 542 * <a name="Scrolling"></a> 543 * <h3>Scrolling</h3> 544 * <p> 545 * The framework provides basic support for views that wish to internally 546 * scroll their content. This includes keeping track of the X and Y scroll 547 * offset as well as mechanisms for drawing scrollbars. See 548 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 549 * {@link #awakenScrollBars()} for more details. 550 * </p> 551 * 552 * <a name="Tags"></a> 553 * <h3>Tags</h3> 554 * <p> 555 * Unlike IDs, tags are not used to identify views. Tags are essentially an 556 * extra piece of information that can be associated with a view. They are most 557 * often used as a convenience to store data related to views in the views 558 * themselves rather than by putting them in a separate structure. 559 * </p> 560 * 561 * <a name="Properties"></a> 562 * <h3>Properties</h3> 563 * <p> 564 * The View class exposes an {@link #ALPHA} property, as well as several transform-related 565 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are 566 * available both in the {@link Property} form as well as in similarly-named setter/getter 567 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can 568 * be used to set persistent state associated with these rendering-related properties on the view. 569 * The properties and methods can also be used in conjunction with 570 * {@link android.animation.Animator Animator}-based animations, described more in the 571 * <a href="#Animation">Animation</a> section. 572 * </p> 573 * 574 * <a name="Animation"></a> 575 * <h3>Animation</h3> 576 * <p> 577 * Starting with Android 3.0, the preferred way of animating views is to use the 578 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based 579 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and 580 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0 581 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only 582 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class 583 * makes animating these View properties particularly easy and efficient. 584 * </p> 585 * <p> 586 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered. 587 * You can attach an {@link Animation} object to a view using 588 * {@link #setAnimation(Animation)} or 589 * {@link #startAnimation(Animation)}. The animation can alter the scale, 590 * rotation, translation and alpha of a view over time. If the animation is 591 * attached to a view that has children, the animation will affect the entire 592 * subtree rooted by that node. When an animation is started, the framework will 593 * take care of redrawing the appropriate views until the animation completes. 594 * </p> 595 * 596 * <a name="Security"></a> 597 * <h3>Security</h3> 598 * <p> 599 * Sometimes it is essential that an application be able to verify that an action 600 * is being performed with the full knowledge and consent of the user, such as 601 * granting a permission request, making a purchase or clicking on an advertisement. 602 * Unfortunately, a malicious application could try to spoof the user into 603 * performing these actions, unaware, by concealing the intended purpose of the view. 604 * As a remedy, the framework offers a touch filtering mechanism that can be used to 605 * improve the security of views that provide access to sensitive functionality. 606 * </p><p> 607 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 608 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 609 * will discard touches that are received whenever the view's window is obscured by 610 * another visible window. As a result, the view will not receive touches whenever a 611 * toast, dialog or other window appears above the view's window. 612 * </p><p> 613 * For more fine-grained control over security, consider overriding the 614 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 615 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 616 * </p> 617 * 618 * @attr ref android.R.styleable#View_alpha 619 * @attr ref android.R.styleable#View_background 620 * @attr ref android.R.styleable#View_clickable 621 * @attr ref android.R.styleable#View_contentDescription 622 * @attr ref android.R.styleable#View_drawingCacheQuality 623 * @attr ref android.R.styleable#View_duplicateParentState 624 * @attr ref android.R.styleable#View_id 625 * @attr ref android.R.styleable#View_requiresFadingEdge 626 * @attr ref android.R.styleable#View_fadeScrollbars 627 * @attr ref android.R.styleable#View_fadingEdgeLength 628 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 629 * @attr ref android.R.styleable#View_fitsSystemWindows 630 * @attr ref android.R.styleable#View_isScrollContainer 631 * @attr ref android.R.styleable#View_focusable 632 * @attr ref android.R.styleable#View_focusableInTouchMode 633 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 634 * @attr ref android.R.styleable#View_keepScreenOn 635 * @attr ref android.R.styleable#View_layerType 636 * @attr ref android.R.styleable#View_layoutDirection 637 * @attr ref android.R.styleable#View_longClickable 638 * @attr ref android.R.styleable#View_minHeight 639 * @attr ref android.R.styleable#View_minWidth 640 * @attr ref android.R.styleable#View_nextFocusDown 641 * @attr ref android.R.styleable#View_nextFocusLeft 642 * @attr ref android.R.styleable#View_nextFocusRight 643 * @attr ref android.R.styleable#View_nextFocusUp 644 * @attr ref android.R.styleable#View_onClick 645 * @attr ref android.R.styleable#View_padding 646 * @attr ref android.R.styleable#View_paddingBottom 647 * @attr ref android.R.styleable#View_paddingLeft 648 * @attr ref android.R.styleable#View_paddingRight 649 * @attr ref android.R.styleable#View_paddingTop 650 * @attr ref android.R.styleable#View_paddingStart 651 * @attr ref android.R.styleable#View_paddingEnd 652 * @attr ref android.R.styleable#View_saveEnabled 653 * @attr ref android.R.styleable#View_rotation 654 * @attr ref android.R.styleable#View_rotationX 655 * @attr ref android.R.styleable#View_rotationY 656 * @attr ref android.R.styleable#View_scaleX 657 * @attr ref android.R.styleable#View_scaleY 658 * @attr ref android.R.styleable#View_scrollX 659 * @attr ref android.R.styleable#View_scrollY 660 * @attr ref android.R.styleable#View_scrollbarSize 661 * @attr ref android.R.styleable#View_scrollbarStyle 662 * @attr ref android.R.styleable#View_scrollbars 663 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 664 * @attr ref android.R.styleable#View_scrollbarFadeDuration 665 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 666 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 667 * @attr ref android.R.styleable#View_scrollbarThumbVertical 668 * @attr ref android.R.styleable#View_scrollbarTrackVertical 669 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 670 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 671 * @attr ref android.R.styleable#View_sharedElementName 672 * @attr ref android.R.styleable#View_soundEffectsEnabled 673 * @attr ref android.R.styleable#View_tag 674 * @attr ref android.R.styleable#View_textAlignment 675 * @attr ref android.R.styleable#View_textDirection 676 * @attr ref android.R.styleable#View_transformPivotX 677 * @attr ref android.R.styleable#View_transformPivotY 678 * @attr ref android.R.styleable#View_translationX 679 * @attr ref android.R.styleable#View_translationY 680 * @attr ref android.R.styleable#View_translationZ 681 * @attr ref android.R.styleable#View_visibility 682 * 683 * @see android.view.ViewGroup 684 */ 685public class View implements Drawable.Callback, KeyEvent.Callback, 686 AccessibilityEventSource { 687 private static final boolean DBG = false; 688 689 /** 690 * The logging tag used by this class with android.util.Log. 691 */ 692 protected static final String VIEW_LOG_TAG = "View"; 693 694 /** 695 * When set to true, apps will draw debugging information about their layouts. 696 * 697 * @hide 698 */ 699 public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout"; 700 701 /** 702 * Used to mark a View that has no ID. 703 */ 704 public static final int NO_ID = -1; 705 706 /** 707 * Signals that compatibility booleans have been initialized according to 708 * target SDK versions. 709 */ 710 private static boolean sCompatibilityDone = false; 711 712 /** 713 * Use the old (broken) way of building MeasureSpecs. 714 */ 715 private static boolean sUseBrokenMakeMeasureSpec = false; 716 717 /** 718 * Ignore any optimizations using the measure cache. 719 */ 720 private static boolean sIgnoreMeasureCache = false; 721 722 /** 723 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 724 * calling setFlags. 725 */ 726 private static final int NOT_FOCUSABLE = 0x00000000; 727 728 /** 729 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 730 * setFlags. 731 */ 732 private static final int FOCUSABLE = 0x00000001; 733 734 /** 735 * Mask for use with setFlags indicating bits used for focus. 736 */ 737 private static final int FOCUSABLE_MASK = 0x00000001; 738 739 /** 740 * This view will adjust its padding to fit sytem windows (e.g. status bar) 741 */ 742 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 743 744 /** @hide */ 745 @IntDef({VISIBLE, INVISIBLE, GONE}) 746 @Retention(RetentionPolicy.SOURCE) 747 public @interface Visibility {} 748 749 /** 750 * This view is visible. 751 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 752 * android:visibility}. 753 */ 754 public static final int VISIBLE = 0x00000000; 755 756 /** 757 * This view is invisible, but it still takes up space for layout purposes. 758 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 759 * android:visibility}. 760 */ 761 public static final int INVISIBLE = 0x00000004; 762 763 /** 764 * This view is invisible, and it doesn't take any space for layout 765 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 766 * android:visibility}. 767 */ 768 public static final int GONE = 0x00000008; 769 770 /** 771 * Mask for use with setFlags indicating bits used for visibility. 772 * {@hide} 773 */ 774 static final int VISIBILITY_MASK = 0x0000000C; 775 776 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 777 778 /** 779 * This view is enabled. Interpretation varies by subclass. 780 * Use with ENABLED_MASK when calling setFlags. 781 * {@hide} 782 */ 783 static final int ENABLED = 0x00000000; 784 785 /** 786 * This view is disabled. Interpretation varies by subclass. 787 * Use with ENABLED_MASK when calling setFlags. 788 * {@hide} 789 */ 790 static final int DISABLED = 0x00000020; 791 792 /** 793 * Mask for use with setFlags indicating bits used for indicating whether 794 * this view is enabled 795 * {@hide} 796 */ 797 static final int ENABLED_MASK = 0x00000020; 798 799 /** 800 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 801 * called and further optimizations will be performed. It is okay to have 802 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 803 * {@hide} 804 */ 805 static final int WILL_NOT_DRAW = 0x00000080; 806 807 /** 808 * Mask for use with setFlags indicating bits used for indicating whether 809 * this view is will draw 810 * {@hide} 811 */ 812 static final int DRAW_MASK = 0x00000080; 813 814 /** 815 * <p>This view doesn't show scrollbars.</p> 816 * {@hide} 817 */ 818 static final int SCROLLBARS_NONE = 0x00000000; 819 820 /** 821 * <p>This view shows horizontal scrollbars.</p> 822 * {@hide} 823 */ 824 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 825 826 /** 827 * <p>This view shows vertical scrollbars.</p> 828 * {@hide} 829 */ 830 static final int SCROLLBARS_VERTICAL = 0x00000200; 831 832 /** 833 * <p>Mask for use with setFlags indicating bits used for indicating which 834 * scrollbars are enabled.</p> 835 * {@hide} 836 */ 837 static final int SCROLLBARS_MASK = 0x00000300; 838 839 /** 840 * Indicates that the view should filter touches when its window is obscured. 841 * Refer to the class comments for more information about this security feature. 842 * {@hide} 843 */ 844 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 845 846 /** 847 * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate 848 * that they are optional and should be skipped if the window has 849 * requested system UI flags that ignore those insets for layout. 850 */ 851 static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800; 852 853 /** 854 * <p>This view doesn't show fading edges.</p> 855 * {@hide} 856 */ 857 static final int FADING_EDGE_NONE = 0x00000000; 858 859 /** 860 * <p>This view shows horizontal fading edges.</p> 861 * {@hide} 862 */ 863 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 864 865 /** 866 * <p>This view shows vertical fading edges.</p> 867 * {@hide} 868 */ 869 static final int FADING_EDGE_VERTICAL = 0x00002000; 870 871 /** 872 * <p>Mask for use with setFlags indicating bits used for indicating which 873 * fading edges are enabled.</p> 874 * {@hide} 875 */ 876 static final int FADING_EDGE_MASK = 0x00003000; 877 878 /** 879 * <p>Indicates this view can be clicked. When clickable, a View reacts 880 * to clicks by notifying the OnClickListener.<p> 881 * {@hide} 882 */ 883 static final int CLICKABLE = 0x00004000; 884 885 /** 886 * <p>Indicates this view is caching its drawing into a bitmap.</p> 887 * {@hide} 888 */ 889 static final int DRAWING_CACHE_ENABLED = 0x00008000; 890 891 /** 892 * <p>Indicates that no icicle should be saved for this view.<p> 893 * {@hide} 894 */ 895 static final int SAVE_DISABLED = 0x000010000; 896 897 /** 898 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 899 * property.</p> 900 * {@hide} 901 */ 902 static final int SAVE_DISABLED_MASK = 0x000010000; 903 904 /** 905 * <p>Indicates that no drawing cache should ever be created for this view.<p> 906 * {@hide} 907 */ 908 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 909 910 /** 911 * <p>Indicates this view can take / keep focus when int touch mode.</p> 912 * {@hide} 913 */ 914 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 915 916 /** @hide */ 917 @Retention(RetentionPolicy.SOURCE) 918 @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO}) 919 public @interface DrawingCacheQuality {} 920 921 /** 922 * <p>Enables low quality mode for the drawing cache.</p> 923 */ 924 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 925 926 /** 927 * <p>Enables high quality mode for the drawing cache.</p> 928 */ 929 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 930 931 /** 932 * <p>Enables automatic quality mode for the drawing cache.</p> 933 */ 934 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 935 936 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 937 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 938 }; 939 940 /** 941 * <p>Mask for use with setFlags indicating bits used for the cache 942 * quality property.</p> 943 * {@hide} 944 */ 945 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 946 947 /** 948 * <p> 949 * Indicates this view can be long clicked. When long clickable, a View 950 * reacts to long clicks by notifying the OnLongClickListener or showing a 951 * context menu. 952 * </p> 953 * {@hide} 954 */ 955 static final int LONG_CLICKABLE = 0x00200000; 956 957 /** 958 * <p>Indicates that this view gets its drawable states from its direct parent 959 * and ignores its original internal states.</p> 960 * 961 * @hide 962 */ 963 static final int DUPLICATE_PARENT_STATE = 0x00400000; 964 965 /** @hide */ 966 @IntDef({ 967 SCROLLBARS_INSIDE_OVERLAY, 968 SCROLLBARS_INSIDE_INSET, 969 SCROLLBARS_OUTSIDE_OVERLAY, 970 SCROLLBARS_OUTSIDE_INSET 971 }) 972 @Retention(RetentionPolicy.SOURCE) 973 public @interface ScrollBarStyle {} 974 975 /** 976 * The scrollbar style to display the scrollbars inside the content area, 977 * without increasing the padding. The scrollbars will be overlaid with 978 * translucency on the view's content. 979 */ 980 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 981 982 /** 983 * The scrollbar style to display the scrollbars inside the padded area, 984 * increasing the padding of the view. The scrollbars will not overlap the 985 * content area of the view. 986 */ 987 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 988 989 /** 990 * The scrollbar style to display the scrollbars at the edge of the view, 991 * without increasing the padding. The scrollbars will be overlaid with 992 * translucency. 993 */ 994 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 995 996 /** 997 * The scrollbar style to display the scrollbars at the edge of the view, 998 * increasing the padding of the view. The scrollbars will only overlap the 999 * background, if any. 1000 */ 1001 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 1002 1003 /** 1004 * Mask to check if the scrollbar style is overlay or inset. 1005 * {@hide} 1006 */ 1007 static final int SCROLLBARS_INSET_MASK = 0x01000000; 1008 1009 /** 1010 * Mask to check if the scrollbar style is inside or outside. 1011 * {@hide} 1012 */ 1013 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 1014 1015 /** 1016 * Mask for scrollbar style. 1017 * {@hide} 1018 */ 1019 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 1020 1021 /** 1022 * View flag indicating that the screen should remain on while the 1023 * window containing this view is visible to the user. This effectively 1024 * takes care of automatically setting the WindowManager's 1025 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 1026 */ 1027 public static final int KEEP_SCREEN_ON = 0x04000000; 1028 1029 /** 1030 * View flag indicating whether this view should have sound effects enabled 1031 * for events such as clicking and touching. 1032 */ 1033 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 1034 1035 /** 1036 * View flag indicating whether this view should have haptic feedback 1037 * enabled for events such as long presses. 1038 */ 1039 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 1040 1041 /** 1042 * <p>Indicates that the view hierarchy should stop saving state when 1043 * it reaches this view. If state saving is initiated immediately at 1044 * the view, it will be allowed. 1045 * {@hide} 1046 */ 1047 static final int PARENT_SAVE_DISABLED = 0x20000000; 1048 1049 /** 1050 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 1051 * {@hide} 1052 */ 1053 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 1054 1055 /** @hide */ 1056 @IntDef(flag = true, 1057 value = { 1058 FOCUSABLES_ALL, 1059 FOCUSABLES_TOUCH_MODE 1060 }) 1061 @Retention(RetentionPolicy.SOURCE) 1062 public @interface FocusableMode {} 1063 1064 /** 1065 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1066 * should add all focusable Views regardless if they are focusable in touch mode. 1067 */ 1068 public static final int FOCUSABLES_ALL = 0x00000000; 1069 1070 /** 1071 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1072 * should add only Views focusable in touch mode. 1073 */ 1074 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 1075 1076 /** @hide */ 1077 @IntDef({ 1078 FOCUS_BACKWARD, 1079 FOCUS_FORWARD, 1080 FOCUS_LEFT, 1081 FOCUS_UP, 1082 FOCUS_RIGHT, 1083 FOCUS_DOWN 1084 }) 1085 @Retention(RetentionPolicy.SOURCE) 1086 public @interface FocusDirection {} 1087 1088 /** @hide */ 1089 @IntDef({ 1090 FOCUS_LEFT, 1091 FOCUS_UP, 1092 FOCUS_RIGHT, 1093 FOCUS_DOWN 1094 }) 1095 @Retention(RetentionPolicy.SOURCE) 1096 public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward 1097 1098 /** 1099 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 1100 * item. 1101 */ 1102 public static final int FOCUS_BACKWARD = 0x00000001; 1103 1104 /** 1105 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 1106 * item. 1107 */ 1108 public static final int FOCUS_FORWARD = 0x00000002; 1109 1110 /** 1111 * Use with {@link #focusSearch(int)}. Move focus to the left. 1112 */ 1113 public static final int FOCUS_LEFT = 0x00000011; 1114 1115 /** 1116 * Use with {@link #focusSearch(int)}. Move focus up. 1117 */ 1118 public static final int FOCUS_UP = 0x00000021; 1119 1120 /** 1121 * Use with {@link #focusSearch(int)}. Move focus to the right. 1122 */ 1123 public static final int FOCUS_RIGHT = 0x00000042; 1124 1125 /** 1126 * Use with {@link #focusSearch(int)}. Move focus down. 1127 */ 1128 public static final int FOCUS_DOWN = 0x00000082; 1129 1130 /** 1131 * Bits of {@link #getMeasuredWidthAndState()} and 1132 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1133 */ 1134 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1135 1136 /** 1137 * Bits of {@link #getMeasuredWidthAndState()} and 1138 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1139 */ 1140 public static final int MEASURED_STATE_MASK = 0xff000000; 1141 1142 /** 1143 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1144 * for functions that combine both width and height into a single int, 1145 * such as {@link #getMeasuredState()} and the childState argument of 1146 * {@link #resolveSizeAndState(int, int, int)}. 1147 */ 1148 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1149 1150 /** 1151 * Bit of {@link #getMeasuredWidthAndState()} and 1152 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1153 * is smaller that the space the view would like to have. 1154 */ 1155 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1156 1157 /** 1158 * Base View state sets 1159 */ 1160 // Singles 1161 /** 1162 * Indicates the view has no states set. States are used with 1163 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1164 * view depending on its state. 1165 * 1166 * @see android.graphics.drawable.Drawable 1167 * @see #getDrawableState() 1168 */ 1169 protected static final int[] EMPTY_STATE_SET; 1170 /** 1171 * Indicates the view is enabled. 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[] ENABLED_STATE_SET; 1179 /** 1180 * Indicates the view is focused. 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[] FOCUSED_STATE_SET; 1188 /** 1189 * Indicates the view is selected. 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[] SELECTED_STATE_SET; 1197 /** 1198 * Indicates the view is pressed. 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[] PRESSED_STATE_SET; 1206 /** 1207 * Indicates the view's window has focus. 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[] WINDOW_FOCUSED_STATE_SET; 1215 // Doubles 1216 /** 1217 * Indicates the view is enabled and has the focus. 1218 * 1219 * @see #ENABLED_STATE_SET 1220 * @see #FOCUSED_STATE_SET 1221 */ 1222 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1223 /** 1224 * Indicates the view is enabled and selected. 1225 * 1226 * @see #ENABLED_STATE_SET 1227 * @see #SELECTED_STATE_SET 1228 */ 1229 protected static final int[] ENABLED_SELECTED_STATE_SET; 1230 /** 1231 * Indicates the view is enabled and that its window has focus. 1232 * 1233 * @see #ENABLED_STATE_SET 1234 * @see #WINDOW_FOCUSED_STATE_SET 1235 */ 1236 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1237 /** 1238 * Indicates the view is focused and selected. 1239 * 1240 * @see #FOCUSED_STATE_SET 1241 * @see #SELECTED_STATE_SET 1242 */ 1243 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1244 /** 1245 * Indicates the view has the focus and that its window has the focus. 1246 * 1247 * @see #FOCUSED_STATE_SET 1248 * @see #WINDOW_FOCUSED_STATE_SET 1249 */ 1250 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1251 /** 1252 * Indicates the view is selected and that its window has the focus. 1253 * 1254 * @see #SELECTED_STATE_SET 1255 * @see #WINDOW_FOCUSED_STATE_SET 1256 */ 1257 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1258 // Triples 1259 /** 1260 * Indicates the view is enabled, focused and selected. 1261 * 1262 * @see #ENABLED_STATE_SET 1263 * @see #FOCUSED_STATE_SET 1264 * @see #SELECTED_STATE_SET 1265 */ 1266 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1267 /** 1268 * Indicates the view is enabled, focused and its window has the focus. 1269 * 1270 * @see #ENABLED_STATE_SET 1271 * @see #FOCUSED_STATE_SET 1272 * @see #WINDOW_FOCUSED_STATE_SET 1273 */ 1274 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1275 /** 1276 * Indicates the view is enabled, selected and its window has the focus. 1277 * 1278 * @see #ENABLED_STATE_SET 1279 * @see #SELECTED_STATE_SET 1280 * @see #WINDOW_FOCUSED_STATE_SET 1281 */ 1282 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1283 /** 1284 * Indicates the view is focused, selected and its window has the focus. 1285 * 1286 * @see #FOCUSED_STATE_SET 1287 * @see #SELECTED_STATE_SET 1288 * @see #WINDOW_FOCUSED_STATE_SET 1289 */ 1290 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1291 /** 1292 * Indicates the view is enabled, focused, selected and its window 1293 * has the focus. 1294 * 1295 * @see #ENABLED_STATE_SET 1296 * @see #FOCUSED_STATE_SET 1297 * @see #SELECTED_STATE_SET 1298 * @see #WINDOW_FOCUSED_STATE_SET 1299 */ 1300 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1301 /** 1302 * Indicates the view is pressed and its window has the focus. 1303 * 1304 * @see #PRESSED_STATE_SET 1305 * @see #WINDOW_FOCUSED_STATE_SET 1306 */ 1307 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1308 /** 1309 * Indicates the view is pressed and selected. 1310 * 1311 * @see #PRESSED_STATE_SET 1312 * @see #SELECTED_STATE_SET 1313 */ 1314 protected static final int[] PRESSED_SELECTED_STATE_SET; 1315 /** 1316 * Indicates the view is pressed, selected and its window has the focus. 1317 * 1318 * @see #PRESSED_STATE_SET 1319 * @see #SELECTED_STATE_SET 1320 * @see #WINDOW_FOCUSED_STATE_SET 1321 */ 1322 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1323 /** 1324 * Indicates the view is pressed and focused. 1325 * 1326 * @see #PRESSED_STATE_SET 1327 * @see #FOCUSED_STATE_SET 1328 */ 1329 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1330 /** 1331 * Indicates the view is pressed, focused and its window has the focus. 1332 * 1333 * @see #PRESSED_STATE_SET 1334 * @see #FOCUSED_STATE_SET 1335 * @see #WINDOW_FOCUSED_STATE_SET 1336 */ 1337 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1338 /** 1339 * Indicates the view is pressed, focused and selected. 1340 * 1341 * @see #PRESSED_STATE_SET 1342 * @see #SELECTED_STATE_SET 1343 * @see #FOCUSED_STATE_SET 1344 */ 1345 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1346 /** 1347 * Indicates the view is pressed, focused, selected and its window has the focus. 1348 * 1349 * @see #PRESSED_STATE_SET 1350 * @see #FOCUSED_STATE_SET 1351 * @see #SELECTED_STATE_SET 1352 * @see #WINDOW_FOCUSED_STATE_SET 1353 */ 1354 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1355 /** 1356 * Indicates the view is pressed and enabled. 1357 * 1358 * @see #PRESSED_STATE_SET 1359 * @see #ENABLED_STATE_SET 1360 */ 1361 protected static final int[] PRESSED_ENABLED_STATE_SET; 1362 /** 1363 * Indicates the view is pressed, enabled and its window has the focus. 1364 * 1365 * @see #PRESSED_STATE_SET 1366 * @see #ENABLED_STATE_SET 1367 * @see #WINDOW_FOCUSED_STATE_SET 1368 */ 1369 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1370 /** 1371 * Indicates the view is pressed, enabled and selected. 1372 * 1373 * @see #PRESSED_STATE_SET 1374 * @see #ENABLED_STATE_SET 1375 * @see #SELECTED_STATE_SET 1376 */ 1377 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1378 /** 1379 * Indicates the view is pressed, enabled, selected and its window has the 1380 * focus. 1381 * 1382 * @see #PRESSED_STATE_SET 1383 * @see #ENABLED_STATE_SET 1384 * @see #SELECTED_STATE_SET 1385 * @see #WINDOW_FOCUSED_STATE_SET 1386 */ 1387 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1388 /** 1389 * Indicates the view is pressed, enabled and focused. 1390 * 1391 * @see #PRESSED_STATE_SET 1392 * @see #ENABLED_STATE_SET 1393 * @see #FOCUSED_STATE_SET 1394 */ 1395 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1396 /** 1397 * Indicates the view is pressed, enabled, focused and its window has the 1398 * focus. 1399 * 1400 * @see #PRESSED_STATE_SET 1401 * @see #ENABLED_STATE_SET 1402 * @see #FOCUSED_STATE_SET 1403 * @see #WINDOW_FOCUSED_STATE_SET 1404 */ 1405 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1406 /** 1407 * Indicates the view is pressed, enabled, focused and selected. 1408 * 1409 * @see #PRESSED_STATE_SET 1410 * @see #ENABLED_STATE_SET 1411 * @see #SELECTED_STATE_SET 1412 * @see #FOCUSED_STATE_SET 1413 */ 1414 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1415 /** 1416 * Indicates the view is pressed, enabled, focused, selected and its window 1417 * has the focus. 1418 * 1419 * @see #PRESSED_STATE_SET 1420 * @see #ENABLED_STATE_SET 1421 * @see #SELECTED_STATE_SET 1422 * @see #FOCUSED_STATE_SET 1423 * @see #WINDOW_FOCUSED_STATE_SET 1424 */ 1425 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1426 1427 /** 1428 * The order here is very important to {@link #getDrawableState()} 1429 */ 1430 private static final int[][] VIEW_STATE_SETS; 1431 1432 static final int VIEW_STATE_WINDOW_FOCUSED = 1; 1433 static final int VIEW_STATE_SELECTED = 1 << 1; 1434 static final int VIEW_STATE_FOCUSED = 1 << 2; 1435 static final int VIEW_STATE_ENABLED = 1 << 3; 1436 static final int VIEW_STATE_PRESSED = 1 << 4; 1437 static final int VIEW_STATE_ACTIVATED = 1 << 5; 1438 static final int VIEW_STATE_ACCELERATED = 1 << 6; 1439 static final int VIEW_STATE_HOVERED = 1 << 7; 1440 static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8; 1441 static final int VIEW_STATE_DRAG_HOVERED = 1 << 9; 1442 1443 static final int[] VIEW_STATE_IDS = new int[] { 1444 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED, 1445 R.attr.state_selected, VIEW_STATE_SELECTED, 1446 R.attr.state_focused, VIEW_STATE_FOCUSED, 1447 R.attr.state_enabled, VIEW_STATE_ENABLED, 1448 R.attr.state_pressed, VIEW_STATE_PRESSED, 1449 R.attr.state_activated, VIEW_STATE_ACTIVATED, 1450 R.attr.state_accelerated, VIEW_STATE_ACCELERATED, 1451 R.attr.state_hovered, VIEW_STATE_HOVERED, 1452 R.attr.state_drag_can_accept, VIEW_STATE_DRAG_CAN_ACCEPT, 1453 R.attr.state_drag_hovered, VIEW_STATE_DRAG_HOVERED 1454 }; 1455 1456 static { 1457 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) { 1458 throw new IllegalStateException( 1459 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array"); 1460 } 1461 int[] orderedIds = new int[VIEW_STATE_IDS.length]; 1462 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) { 1463 int viewState = R.styleable.ViewDrawableStates[i]; 1464 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) { 1465 if (VIEW_STATE_IDS[j] == viewState) { 1466 orderedIds[i * 2] = viewState; 1467 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1]; 1468 } 1469 } 1470 } 1471 final int NUM_BITS = VIEW_STATE_IDS.length / 2; 1472 VIEW_STATE_SETS = new int[1 << NUM_BITS][]; 1473 for (int i = 0; i < VIEW_STATE_SETS.length; i++) { 1474 int numBits = Integer.bitCount(i); 1475 int[] set = new int[numBits]; 1476 int pos = 0; 1477 for (int j = 0; j < orderedIds.length; j += 2) { 1478 if ((i & orderedIds[j+1]) != 0) { 1479 set[pos++] = orderedIds[j]; 1480 } 1481 } 1482 VIEW_STATE_SETS[i] = set; 1483 } 1484 1485 EMPTY_STATE_SET = VIEW_STATE_SETS[0]; 1486 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED]; 1487 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED]; 1488 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1489 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED]; 1490 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED]; 1491 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1492 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED]; 1493 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1494 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED]; 1495 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1496 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1497 | VIEW_STATE_FOCUSED]; 1498 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED]; 1499 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1500 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED]; 1501 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1502 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED]; 1503 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1504 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1505 | VIEW_STATE_ENABLED]; 1506 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1507 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED]; 1508 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1509 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1510 | VIEW_STATE_ENABLED]; 1511 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1512 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1513 | VIEW_STATE_ENABLED]; 1514 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1515 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1516 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED]; 1517 1518 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED]; 1519 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1520 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED]; 1521 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1522 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED]; 1523 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1524 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1525 | VIEW_STATE_PRESSED]; 1526 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1527 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1528 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1529 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1530 | VIEW_STATE_PRESSED]; 1531 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1532 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1533 | VIEW_STATE_PRESSED]; 1534 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1535 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1536 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1537 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[ 1538 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1539 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1540 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED 1541 | VIEW_STATE_PRESSED]; 1542 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1543 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED 1544 | VIEW_STATE_PRESSED]; 1545 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1546 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1547 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1548 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1549 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED 1550 | VIEW_STATE_PRESSED]; 1551 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1552 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1553 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1554 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1555 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1556 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1557 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1558 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1559 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED 1560 | VIEW_STATE_PRESSED]; 1561 } 1562 1563 /** 1564 * Accessibility event types that are dispatched for text population. 1565 */ 1566 private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES = 1567 AccessibilityEvent.TYPE_VIEW_CLICKED 1568 | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED 1569 | AccessibilityEvent.TYPE_VIEW_SELECTED 1570 | AccessibilityEvent.TYPE_VIEW_FOCUSED 1571 | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED 1572 | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER 1573 | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT 1574 | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED 1575 | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED 1576 | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED 1577 | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY; 1578 1579 /** 1580 * Temporary Rect currently for use in setBackground(). This will probably 1581 * be extended in the future to hold our own class with more than just 1582 * a Rect. :) 1583 */ 1584 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1585 1586 /** 1587 * Map used to store views' tags. 1588 */ 1589 private SparseArray<Object> mKeyedTags; 1590 1591 /** 1592 * The next available accessibility id. 1593 */ 1594 private static int sNextAccessibilityViewId; 1595 1596 /** 1597 * The animation currently associated with this view. 1598 * @hide 1599 */ 1600 protected Animation mCurrentAnimation = null; 1601 1602 /** 1603 * Width as measured during measure pass. 1604 * {@hide} 1605 */ 1606 @ViewDebug.ExportedProperty(category = "measurement") 1607 int mMeasuredWidth; 1608 1609 /** 1610 * Height as measured during measure pass. 1611 * {@hide} 1612 */ 1613 @ViewDebug.ExportedProperty(category = "measurement") 1614 int mMeasuredHeight; 1615 1616 /** 1617 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1618 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1619 * its display list. This flag, used only when hw accelerated, allows us to clear the 1620 * flag while retaining this information until it's needed (at getDisplayList() time and 1621 * in drawChild(), when we decide to draw a view's children's display lists into our own). 1622 * 1623 * {@hide} 1624 */ 1625 boolean mRecreateDisplayList = false; 1626 1627 /** 1628 * The view's identifier. 1629 * {@hide} 1630 * 1631 * @see #setId(int) 1632 * @see #getId() 1633 */ 1634 @ViewDebug.ExportedProperty(resolveId = true) 1635 int mID = NO_ID; 1636 1637 /** 1638 * The stable ID of this view for accessibility purposes. 1639 */ 1640 int mAccessibilityViewId = NO_ID; 1641 1642 private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 1643 1644 SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent; 1645 1646 /** 1647 * The view's tag. 1648 * {@hide} 1649 * 1650 * @see #setTag(Object) 1651 * @see #getTag() 1652 */ 1653 protected Object mTag = null; 1654 1655 // for mPrivateFlags: 1656 /** {@hide} */ 1657 static final int PFLAG_WANTS_FOCUS = 0x00000001; 1658 /** {@hide} */ 1659 static final int PFLAG_FOCUSED = 0x00000002; 1660 /** {@hide} */ 1661 static final int PFLAG_SELECTED = 0x00000004; 1662 /** {@hide} */ 1663 static final int PFLAG_IS_ROOT_NAMESPACE = 0x00000008; 1664 /** {@hide} */ 1665 static final int PFLAG_HAS_BOUNDS = 0x00000010; 1666 /** {@hide} */ 1667 static final int PFLAG_DRAWN = 0x00000020; 1668 /** 1669 * When this flag is set, this view is running an animation on behalf of its 1670 * children and should therefore not cancel invalidate requests, even if they 1671 * lie outside of this view's bounds. 1672 * 1673 * {@hide} 1674 */ 1675 static final int PFLAG_DRAW_ANIMATION = 0x00000040; 1676 /** {@hide} */ 1677 static final int PFLAG_SKIP_DRAW = 0x00000080; 1678 /** {@hide} */ 1679 static final int PFLAG_ONLY_DRAWS_BACKGROUND = 0x00000100; 1680 /** {@hide} */ 1681 static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1682 /** {@hide} */ 1683 static final int PFLAG_DRAWABLE_STATE_DIRTY = 0x00000400; 1684 /** {@hide} */ 1685 static final int PFLAG_MEASURED_DIMENSION_SET = 0x00000800; 1686 /** {@hide} */ 1687 static final int PFLAG_FORCE_LAYOUT = 0x00001000; 1688 /** {@hide} */ 1689 static final int PFLAG_LAYOUT_REQUIRED = 0x00002000; 1690 1691 private static final int PFLAG_PRESSED = 0x00004000; 1692 1693 /** {@hide} */ 1694 static final int PFLAG_DRAWING_CACHE_VALID = 0x00008000; 1695 /** 1696 * Flag used to indicate that this view should be drawn once more (and only once 1697 * more) after its animation has completed. 1698 * {@hide} 1699 */ 1700 static final int PFLAG_ANIMATION_STARTED = 0x00010000; 1701 1702 private static final int PFLAG_SAVE_STATE_CALLED = 0x00020000; 1703 1704 /** 1705 * Indicates that the View returned true when onSetAlpha() was called and that 1706 * the alpha must be restored. 1707 * {@hide} 1708 */ 1709 static final int PFLAG_ALPHA_SET = 0x00040000; 1710 1711 /** 1712 * Set by {@link #setScrollContainer(boolean)}. 1713 */ 1714 static final int PFLAG_SCROLL_CONTAINER = 0x00080000; 1715 1716 /** 1717 * Set by {@link #setScrollContainer(boolean)}. 1718 */ 1719 static final int PFLAG_SCROLL_CONTAINER_ADDED = 0x00100000; 1720 1721 /** 1722 * View flag indicating whether this view was invalidated (fully or partially.) 1723 * 1724 * @hide 1725 */ 1726 static final int PFLAG_DIRTY = 0x00200000; 1727 1728 /** 1729 * View flag indicating whether this view was invalidated by an opaque 1730 * invalidate request. 1731 * 1732 * @hide 1733 */ 1734 static final int PFLAG_DIRTY_OPAQUE = 0x00400000; 1735 1736 /** 1737 * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}. 1738 * 1739 * @hide 1740 */ 1741 static final int PFLAG_DIRTY_MASK = 0x00600000; 1742 1743 /** 1744 * Indicates whether the background is opaque. 1745 * 1746 * @hide 1747 */ 1748 static final int PFLAG_OPAQUE_BACKGROUND = 0x00800000; 1749 1750 /** 1751 * Indicates whether the scrollbars are opaque. 1752 * 1753 * @hide 1754 */ 1755 static final int PFLAG_OPAQUE_SCROLLBARS = 0x01000000; 1756 1757 /** 1758 * Indicates whether the view is opaque. 1759 * 1760 * @hide 1761 */ 1762 static final int PFLAG_OPAQUE_MASK = 0x01800000; 1763 1764 /** 1765 * Indicates a prepressed state; 1766 * the short time between ACTION_DOWN and recognizing 1767 * a 'real' press. Prepressed is used to recognize quick taps 1768 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1769 * 1770 * @hide 1771 */ 1772 private static final int PFLAG_PREPRESSED = 0x02000000; 1773 1774 /** 1775 * Indicates whether the view is temporarily detached. 1776 * 1777 * @hide 1778 */ 1779 static final int PFLAG_CANCEL_NEXT_UP_EVENT = 0x04000000; 1780 1781 /** 1782 * Indicates that we should awaken scroll bars once attached 1783 * 1784 * @hide 1785 */ 1786 private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1787 1788 /** 1789 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 1790 * @hide 1791 */ 1792 private static final int PFLAG_HOVERED = 0x10000000; 1793 1794 /** 1795 * Indicates that pivotX or pivotY were explicitly set and we should not assume the center 1796 * for transform operations 1797 * 1798 * @hide 1799 */ 1800 private static final int PFLAG_PIVOT_EXPLICITLY_SET = 0x20000000; 1801 1802 /** {@hide} */ 1803 static final int PFLAG_ACTIVATED = 0x40000000; 1804 1805 /** 1806 * Indicates that this view was specifically invalidated, not just dirtied because some 1807 * child view was invalidated. The flag is used to determine when we need to recreate 1808 * a view's display list (as opposed to just returning a reference to its existing 1809 * display list). 1810 * 1811 * @hide 1812 */ 1813 static final int PFLAG_INVALIDATED = 0x80000000; 1814 1815 /** 1816 * Masks for mPrivateFlags2, as generated by dumpFlags(): 1817 * 1818 * |-------|-------|-------|-------| 1819 * 1 PFLAG2_DRAG_CAN_ACCEPT 1820 * 1 PFLAG2_DRAG_HOVERED 1821 * 11 PFLAG2_LAYOUT_DIRECTION_MASK 1822 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL 1823 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED 1824 * 11 PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK 1825 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[1] 1826 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[2] 1827 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[3] 1828 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[4] 1829 * 1 1 PFLAG2_TEXT_DIRECTION_FLAGS[5] 1830 * 111 PFLAG2_TEXT_DIRECTION_MASK 1831 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED 1832 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT 1833 * 111 PFLAG2_TEXT_DIRECTION_RESOLVED_MASK 1834 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[1] 1835 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[2] 1836 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[3] 1837 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[4] 1838 * 1 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[5] 1839 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[6] 1840 * 111 PFLAG2_TEXT_ALIGNMENT_MASK 1841 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED 1842 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT 1843 * 111 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK 1844 * 111 PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK 1845 * 11 PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK 1846 * 1 PFLAG2_ACCESSIBILITY_FOCUSED 1847 * 1 PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED 1848 * 1 PFLAG2_VIEW_QUICK_REJECTED 1849 * 1 PFLAG2_PADDING_RESOLVED 1850 * 1 PFLAG2_DRAWABLE_RESOLVED 1851 * 1 PFLAG2_HAS_TRANSIENT_STATE 1852 * |-------|-------|-------|-------| 1853 */ 1854 1855 /** 1856 * Indicates that this view has reported that it can accept the current drag's content. 1857 * Cleared when the drag operation concludes. 1858 * @hide 1859 */ 1860 static final int PFLAG2_DRAG_CAN_ACCEPT = 0x00000001; 1861 1862 /** 1863 * Indicates that this view is currently directly under the drag location in a 1864 * drag-and-drop operation involving content that it can accept. Cleared when 1865 * the drag exits the view, or when the drag operation concludes. 1866 * @hide 1867 */ 1868 static final int PFLAG2_DRAG_HOVERED = 0x00000002; 1869 1870 /** @hide */ 1871 @IntDef({ 1872 LAYOUT_DIRECTION_LTR, 1873 LAYOUT_DIRECTION_RTL, 1874 LAYOUT_DIRECTION_INHERIT, 1875 LAYOUT_DIRECTION_LOCALE 1876 }) 1877 @Retention(RetentionPolicy.SOURCE) 1878 // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection 1879 public @interface LayoutDir {} 1880 1881 /** @hide */ 1882 @IntDef({ 1883 LAYOUT_DIRECTION_LTR, 1884 LAYOUT_DIRECTION_RTL 1885 }) 1886 @Retention(RetentionPolicy.SOURCE) 1887 public @interface ResolvedLayoutDir {} 1888 1889 /** 1890 * Horizontal layout direction of this view is from Left to Right. 1891 * Use with {@link #setLayoutDirection}. 1892 */ 1893 public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR; 1894 1895 /** 1896 * Horizontal layout direction of this view is from Right to Left. 1897 * Use with {@link #setLayoutDirection}. 1898 */ 1899 public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL; 1900 1901 /** 1902 * Horizontal layout direction of this view is inherited from its parent. 1903 * Use with {@link #setLayoutDirection}. 1904 */ 1905 public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT; 1906 1907 /** 1908 * Horizontal layout direction of this view is from deduced from the default language 1909 * script for the locale. Use with {@link #setLayoutDirection}. 1910 */ 1911 public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE; 1912 1913 /** 1914 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 1915 * @hide 1916 */ 1917 static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2; 1918 1919 /** 1920 * Mask for use with private flags indicating bits used for horizontal layout direction. 1921 * @hide 1922 */ 1923 static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1924 1925 /** 1926 * Indicates whether the view horizontal layout direction has been resolved and drawn to the 1927 * right-to-left direction. 1928 * @hide 1929 */ 1930 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1931 1932 /** 1933 * Indicates whether the view horizontal layout direction has been resolved. 1934 * @hide 1935 */ 1936 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1937 1938 /** 1939 * Mask for use with private flags indicating bits used for resolved horizontal layout direction. 1940 * @hide 1941 */ 1942 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C 1943 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1944 1945 /* 1946 * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct 1947 * flag value. 1948 * @hide 1949 */ 1950 private static final int[] LAYOUT_DIRECTION_FLAGS = { 1951 LAYOUT_DIRECTION_LTR, 1952 LAYOUT_DIRECTION_RTL, 1953 LAYOUT_DIRECTION_INHERIT, 1954 LAYOUT_DIRECTION_LOCALE 1955 }; 1956 1957 /** 1958 * Default horizontal layout direction. 1959 */ 1960 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 1961 1962 /** 1963 * Default horizontal layout direction. 1964 * @hide 1965 */ 1966 static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR; 1967 1968 /** 1969 * Text direction is inherited thru {@link ViewGroup} 1970 */ 1971 public static final int TEXT_DIRECTION_INHERIT = 0; 1972 1973 /** 1974 * Text direction is using "first strong algorithm". The first strong directional character 1975 * determines the paragraph direction. If there is no strong directional character, the 1976 * paragraph direction is the view's resolved layout direction. 1977 */ 1978 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 1979 1980 /** 1981 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 1982 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 1983 * If there are neither, the paragraph direction is the view's resolved layout direction. 1984 */ 1985 public static final int TEXT_DIRECTION_ANY_RTL = 2; 1986 1987 /** 1988 * Text direction is forced to LTR. 1989 */ 1990 public static final int TEXT_DIRECTION_LTR = 3; 1991 1992 /** 1993 * Text direction is forced to RTL. 1994 */ 1995 public static final int TEXT_DIRECTION_RTL = 4; 1996 1997 /** 1998 * Text direction is coming from the system Locale. 1999 */ 2000 public static final int TEXT_DIRECTION_LOCALE = 5; 2001 2002 /** 2003 * Default text direction is inherited 2004 */ 2005 private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT; 2006 2007 /** 2008 * Default resolved text direction 2009 * @hide 2010 */ 2011 static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG; 2012 2013 /** 2014 * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED) 2015 * @hide 2016 */ 2017 static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6; 2018 2019 /** 2020 * Mask for use with private flags indicating bits used for text direction. 2021 * @hide 2022 */ 2023 static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007 2024 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2025 2026 /** 2027 * Array of text direction flags for mapping attribute "textDirection" to correct 2028 * flag value. 2029 * @hide 2030 */ 2031 private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = { 2032 TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2033 TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2034 TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2035 TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2036 TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2037 TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT 2038 }; 2039 2040 /** 2041 * Indicates whether the view text direction has been resolved. 2042 * @hide 2043 */ 2044 static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008 2045 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2046 2047 /** 2048 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2049 * @hide 2050 */ 2051 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10; 2052 2053 /** 2054 * Mask for use with private flags indicating bits used for resolved text direction. 2055 * @hide 2056 */ 2057 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 2058 << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2059 2060 /** 2061 * Indicates whether the view text direction has been resolved to the "first strong" heuristic. 2062 * @hide 2063 */ 2064 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT = 2065 TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2066 2067 /** @hide */ 2068 @IntDef({ 2069 TEXT_ALIGNMENT_INHERIT, 2070 TEXT_ALIGNMENT_GRAVITY, 2071 TEXT_ALIGNMENT_CENTER, 2072 TEXT_ALIGNMENT_TEXT_START, 2073 TEXT_ALIGNMENT_TEXT_END, 2074 TEXT_ALIGNMENT_VIEW_START, 2075 TEXT_ALIGNMENT_VIEW_END 2076 }) 2077 @Retention(RetentionPolicy.SOURCE) 2078 public @interface TextAlignment {} 2079 2080 /** 2081 * Default text alignment. The text alignment of this View is inherited from its parent. 2082 * Use with {@link #setTextAlignment(int)} 2083 */ 2084 public static final int TEXT_ALIGNMENT_INHERIT = 0; 2085 2086 /** 2087 * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL, 2088 * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction. 2089 * 2090 * Use with {@link #setTextAlignment(int)} 2091 */ 2092 public static final int TEXT_ALIGNMENT_GRAVITY = 1; 2093 2094 /** 2095 * Align to the start of the paragraph, e.g. ALIGN_NORMAL. 2096 * 2097 * Use with {@link #setTextAlignment(int)} 2098 */ 2099 public static final int TEXT_ALIGNMENT_TEXT_START = 2; 2100 2101 /** 2102 * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE. 2103 * 2104 * Use with {@link #setTextAlignment(int)} 2105 */ 2106 public static final int TEXT_ALIGNMENT_TEXT_END = 3; 2107 2108 /** 2109 * Center the paragraph, e.g. ALIGN_CENTER. 2110 * 2111 * Use with {@link #setTextAlignment(int)} 2112 */ 2113 public static final int TEXT_ALIGNMENT_CENTER = 4; 2114 2115 /** 2116 * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved 2117 * layoutDirection is LTR, and ALIGN_RIGHT otherwise. 2118 * 2119 * Use with {@link #setTextAlignment(int)} 2120 */ 2121 public static final int TEXT_ALIGNMENT_VIEW_START = 5; 2122 2123 /** 2124 * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved 2125 * layoutDirection is LTR, and ALIGN_LEFT otherwise. 2126 * 2127 * Use with {@link #setTextAlignment(int)} 2128 */ 2129 public static final int TEXT_ALIGNMENT_VIEW_END = 6; 2130 2131 /** 2132 * Default text alignment is inherited 2133 */ 2134 private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2135 2136 /** 2137 * Default resolved text alignment 2138 * @hide 2139 */ 2140 static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2141 2142 /** 2143 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2144 * @hide 2145 */ 2146 static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13; 2147 2148 /** 2149 * Mask for use with private flags indicating bits used for text alignment. 2150 * @hide 2151 */ 2152 static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2153 2154 /** 2155 * Array of text direction flags for mapping attribute "textAlignment" to correct 2156 * flag value. 2157 * @hide 2158 */ 2159 private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = { 2160 TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2161 TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2162 TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2163 TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2164 TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2165 TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2166 TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT 2167 }; 2168 2169 /** 2170 * Indicates whether the view text alignment has been resolved. 2171 * @hide 2172 */ 2173 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2174 2175 /** 2176 * Bit shift to get the resolved text alignment. 2177 * @hide 2178 */ 2179 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17; 2180 2181 /** 2182 * Mask for use with private flags indicating bits used for text alignment. 2183 * @hide 2184 */ 2185 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 2186 << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2187 2188 /** 2189 * Indicates whether if the view text alignment has been resolved to gravity 2190 */ 2191 private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT = 2192 TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2193 2194 // Accessiblity constants for mPrivateFlags2 2195 2196 /** 2197 * Shift for the bits in {@link #mPrivateFlags2} related to the 2198 * "importantForAccessibility" attribute. 2199 */ 2200 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20; 2201 2202 /** 2203 * Automatically determine whether a view is important for accessibility. 2204 */ 2205 public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000; 2206 2207 /** 2208 * The view is important for accessibility. 2209 */ 2210 public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001; 2211 2212 /** 2213 * The view is not important for accessibility. 2214 */ 2215 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002; 2216 2217 /** 2218 * The view is not important for accessibility, nor are any of its 2219 * descendant views. 2220 */ 2221 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004; 2222 2223 /** 2224 * The default whether the view is important for accessibility. 2225 */ 2226 static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO; 2227 2228 /** 2229 * Mask for obtainig the bits which specify how to determine 2230 * whether a view is important for accessibility. 2231 */ 2232 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO 2233 | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO 2234 | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) 2235 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2236 2237 /** 2238 * Shift for the bits in {@link #mPrivateFlags2} related to the 2239 * "accessibilityLiveRegion" attribute. 2240 */ 2241 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23; 2242 2243 /** 2244 * Live region mode specifying that accessibility services should not 2245 * automatically announce changes to this view. This is the default live 2246 * region mode for most views. 2247 * <p> 2248 * Use with {@link #setAccessibilityLiveRegion(int)}. 2249 */ 2250 public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000; 2251 2252 /** 2253 * Live region mode specifying that accessibility services should announce 2254 * changes to this view. 2255 * <p> 2256 * Use with {@link #setAccessibilityLiveRegion(int)}. 2257 */ 2258 public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001; 2259 2260 /** 2261 * Live region mode specifying that accessibility services should interrupt 2262 * ongoing speech to immediately announce changes to this view. 2263 * <p> 2264 * Use with {@link #setAccessibilityLiveRegion(int)}. 2265 */ 2266 public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002; 2267 2268 /** 2269 * The default whether the view is important for accessibility. 2270 */ 2271 static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE; 2272 2273 /** 2274 * Mask for obtaining the bits which specify a view's accessibility live 2275 * region mode. 2276 */ 2277 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE 2278 | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE) 2279 << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 2280 2281 /** 2282 * Flag indicating whether a view has accessibility focus. 2283 */ 2284 static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000; 2285 2286 /** 2287 * Flag whether the accessibility state of the subtree rooted at this view changed. 2288 */ 2289 static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000; 2290 2291 /** 2292 * Flag indicating whether a view failed the quickReject() check in draw(). This condition 2293 * is used to check whether later changes to the view's transform should invalidate the 2294 * view to force the quickReject test to run again. 2295 */ 2296 static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000; 2297 2298 /** 2299 * Flag indicating that start/end padding has been resolved into left/right padding 2300 * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()} 2301 * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved 2302 * during measurement. In some special cases this is required such as when an adapter-based 2303 * view measures prospective children without attaching them to a window. 2304 */ 2305 static final int PFLAG2_PADDING_RESOLVED = 0x20000000; 2306 2307 /** 2308 * Flag indicating that the start/end drawables has been resolved into left/right ones. 2309 */ 2310 static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000; 2311 2312 /** 2313 * Indicates that the view is tracking some sort of transient state 2314 * that the app should not need to be aware of, but that the framework 2315 * should take special care to preserve. 2316 */ 2317 static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000; 2318 2319 /** 2320 * Group of bits indicating that RTL properties resolution is done. 2321 */ 2322 static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED | 2323 PFLAG2_TEXT_DIRECTION_RESOLVED | 2324 PFLAG2_TEXT_ALIGNMENT_RESOLVED | 2325 PFLAG2_PADDING_RESOLVED | 2326 PFLAG2_DRAWABLE_RESOLVED; 2327 2328 // There are a couple of flags left in mPrivateFlags2 2329 2330 /* End of masks for mPrivateFlags2 */ 2331 2332 /** 2333 * Masks for mPrivateFlags3, as generated by dumpFlags(): 2334 * 2335 * |-------|-------|-------|-------| 2336 * 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM 2337 * 1 PFLAG3_VIEW_IS_ANIMATING_ALPHA 2338 * 1 PFLAG3_IS_LAID_OUT 2339 * 1 PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT 2340 * 1 PFLAG3_CALLED_SUPER 2341 * |-------|-------|-------|-------| 2342 */ 2343 2344 /** 2345 * Flag indicating that view has a transform animation set on it. This is used to track whether 2346 * an animation is cleared between successive frames, in order to tell the associated 2347 * DisplayList to clear its animation matrix. 2348 */ 2349 static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1; 2350 2351 /** 2352 * Flag indicating that view has an alpha animation set on it. This is used to track whether an 2353 * animation is cleared between successive frames, in order to tell the associated 2354 * DisplayList to restore its alpha value. 2355 */ 2356 static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2; 2357 2358 /** 2359 * Flag indicating that the view has been through at least one layout since it 2360 * was last attached to a window. 2361 */ 2362 static final int PFLAG3_IS_LAID_OUT = 0x4; 2363 2364 /** 2365 * Flag indicating that a call to measure() was skipped and should be done 2366 * instead when layout() is invoked. 2367 */ 2368 static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8; 2369 2370 /** 2371 * Flag indicating that an overridden method correctly called down to 2372 * the superclass implementation as required by the API spec. 2373 */ 2374 static final int PFLAG3_CALLED_SUPER = 0x10; 2375 2376 /** 2377 * Flag indicating that an view will be clipped to its outline. 2378 */ 2379 static final int PFLAG3_CLIP_TO_OUTLINE = 0x20; 2380 2381 /** 2382 * Flag indicating that a view's outline has been specifically defined. 2383 */ 2384 static final int PFLAG3_OUTLINE_DEFINED = 0x40; 2385 2386 /** 2387 * Flag indicating that we're in the process of applying window insets. 2388 */ 2389 static final int PFLAG3_APPLYING_INSETS = 0x80; 2390 2391 /** 2392 * Flag indicating that we're in the process of fitting system windows using the old method. 2393 */ 2394 static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x100; 2395 2396 /* End of masks for mPrivateFlags3 */ 2397 2398 static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED; 2399 2400 /** 2401 * Always allow a user to over-scroll this view, provided it is a 2402 * view that can scroll. 2403 * 2404 * @see #getOverScrollMode() 2405 * @see #setOverScrollMode(int) 2406 */ 2407 public static final int OVER_SCROLL_ALWAYS = 0; 2408 2409 /** 2410 * Allow a user to over-scroll this view only if the content is large 2411 * enough to meaningfully scroll, provided it is a view that can scroll. 2412 * 2413 * @see #getOverScrollMode() 2414 * @see #setOverScrollMode(int) 2415 */ 2416 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 2417 2418 /** 2419 * Never allow a user to over-scroll this view. 2420 * 2421 * @see #getOverScrollMode() 2422 * @see #setOverScrollMode(int) 2423 */ 2424 public static final int OVER_SCROLL_NEVER = 2; 2425 2426 /** 2427 * Special constant for {@link #setSystemUiVisibility(int)}: View has 2428 * requested the system UI (status bar) to be visible (the default). 2429 * 2430 * @see #setSystemUiVisibility(int) 2431 */ 2432 public static final int SYSTEM_UI_FLAG_VISIBLE = 0; 2433 2434 /** 2435 * Flag for {@link #setSystemUiVisibility(int)}: View has requested the 2436 * system UI to enter an unobtrusive "low profile" mode. 2437 * 2438 * <p>This is for use in games, book readers, video players, or any other 2439 * "immersive" application where the usual system chrome is deemed too distracting. 2440 * 2441 * <p>In low profile mode, the status bar and/or navigation icons may dim. 2442 * 2443 * @see #setSystemUiVisibility(int) 2444 */ 2445 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001; 2446 2447 /** 2448 * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the 2449 * system navigation be temporarily hidden. 2450 * 2451 * <p>This is an even less obtrusive state than that called for by 2452 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls 2453 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause 2454 * those to disappear. This is useful (in conjunction with the 2455 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and 2456 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN} 2457 * window flags) for displaying content using every last pixel on the display. 2458 * 2459 * <p>There is a limitation: because navigation controls are so important, the least user 2460 * interaction will cause them to reappear immediately. When this happens, both 2461 * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically, 2462 * so that both elements reappear at the same time. 2463 * 2464 * @see #setSystemUiVisibility(int) 2465 */ 2466 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002; 2467 2468 /** 2469 * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go 2470 * into the normal fullscreen mode so that its content can take over the screen 2471 * while still allowing the user to interact with the application. 2472 * 2473 * <p>This has the same visual effect as 2474 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN 2475 * WindowManager.LayoutParams.FLAG_FULLSCREEN}, 2476 * meaning that non-critical screen decorations (such as the status bar) will be 2477 * hidden while the user is in the View's window, focusing the experience on 2478 * that content. Unlike the window flag, if you are using ActionBar in 2479 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2480 * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also 2481 * hide the action bar. 2482 * 2483 * <p>This approach to going fullscreen is best used over the window flag when 2484 * it is a transient state -- that is, the application does this at certain 2485 * points in its user interaction where it wants to allow the user to focus 2486 * on content, but not as a continuous state. For situations where the application 2487 * would like to simply stay full screen the entire time (such as a game that 2488 * wants to take over the screen), the 2489 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag} 2490 * is usually a better approach. The state set here will be removed by the system 2491 * in various situations (such as the user moving to another application) like 2492 * the other system UI states. 2493 * 2494 * <p>When using this flag, the application should provide some easy facility 2495 * for the user to go out of it. A common example would be in an e-book 2496 * reader, where tapping on the screen brings back whatever screen and UI 2497 * decorations that had been hidden while the user was immersed in reading 2498 * the book. 2499 * 2500 * @see #setSystemUiVisibility(int) 2501 */ 2502 public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004; 2503 2504 /** 2505 * Flag for {@link #setSystemUiVisibility(int)}: When using other layout 2506 * flags, we would like a stable view of the content insets given to 2507 * {@link #fitSystemWindows(Rect)}. This means that the insets seen there 2508 * will always represent the worst case that the application can expect 2509 * as a continuous state. In the stock Android UI this is the space for 2510 * the system bar, nav bar, and status bar, but not more transient elements 2511 * such as an input method. 2512 * 2513 * The stable layout your UI sees is based on the system UI modes you can 2514 * switch to. That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 2515 * then you will get a stable layout for changes of the 2516 * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify 2517 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and 2518 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition 2519 * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} 2520 * with a stable layout. (Note that you should avoid using 2521 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.) 2522 * 2523 * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN} 2524 * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}), 2525 * then a hidden status bar will be considered a "stable" state for purposes 2526 * here. This allows your UI to continually hide the status bar, while still 2527 * using the system UI flags to hide the action bar while still retaining 2528 * a stable layout. Note that changing the window fullscreen flag will never 2529 * provide a stable layout for a clean transition. 2530 * 2531 * <p>If you are using ActionBar in 2532 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2533 * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the 2534 * insets it adds to those given to the application. 2535 */ 2536 public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100; 2537 2538 /** 2539 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2540 * to be layed out as if it has requested 2541 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't. This 2542 * allows it to avoid artifacts when switching in and out of that mode, at 2543 * the expense that some of its user interface may be covered by screen 2544 * decorations when they are shown. You can perform layout of your inner 2545 * UI elements to account for the navigation system UI through the 2546 * {@link #fitSystemWindows(Rect)} method. 2547 */ 2548 public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200; 2549 2550 /** 2551 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2552 * to be layed out as if it has requested 2553 * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't. This 2554 * allows it to avoid artifacts when switching in and out of that mode, at 2555 * the expense that some of its user interface may be covered by screen 2556 * decorations when they are shown. You can perform layout of your inner 2557 * UI elements to account for non-fullscreen system UI through the 2558 * {@link #fitSystemWindows(Rect)} method. 2559 */ 2560 public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400; 2561 2562 /** 2563 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2564 * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. If this flag is 2565 * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any 2566 * user interaction. 2567 * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only 2568 * has an effect when used in combination with that flag.</p> 2569 */ 2570 public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800; 2571 2572 /** 2573 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2574 * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation 2575 * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. Use this flag to create an immersive 2576 * experience while also hiding the system bars. If this flag is not set, 2577 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user 2578 * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system 2579 * if the user swipes from the top of the screen. 2580 * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with 2581 * system gestures, such as swiping from the top of the screen. These transient system bars 2582 * will overlay app’s content, may have some degree of transparency, and will automatically 2583 * hide after a short timeout. 2584 * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and 2585 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination 2586 * with one or both of those flags.</p> 2587 */ 2588 public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000; 2589 2590 /** 2591 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead. 2592 */ 2593 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE; 2594 2595 /** 2596 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead. 2597 */ 2598 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE; 2599 2600 /** 2601 * @hide 2602 * 2603 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2604 * out of the public fields to keep the undefined bits out of the developer's way. 2605 * 2606 * Flag to make the status bar not expandable. Unless you also 2607 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 2608 */ 2609 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 2610 2611 /** 2612 * @hide 2613 * 2614 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2615 * out of the public fields to keep the undefined bits out of the developer's way. 2616 * 2617 * Flag to hide notification icons and scrolling ticker text. 2618 */ 2619 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 2620 2621 /** 2622 * @hide 2623 * 2624 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2625 * out of the public fields to keep the undefined bits out of the developer's way. 2626 * 2627 * Flag to disable incoming notification alerts. This will not block 2628 * icons, but it will block sound, vibrating and other visual or aural notifications. 2629 */ 2630 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 2631 2632 /** 2633 * @hide 2634 * 2635 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2636 * out of the public fields to keep the undefined bits out of the developer's way. 2637 * 2638 * Flag to hide only the scrolling ticker. Note that 2639 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 2640 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 2641 */ 2642 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 2643 2644 /** 2645 * @hide 2646 * 2647 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2648 * out of the public fields to keep the undefined bits out of the developer's way. 2649 * 2650 * Flag to hide the center system info area. 2651 */ 2652 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 2653 2654 /** 2655 * @hide 2656 * 2657 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2658 * out of the public fields to keep the undefined bits out of the developer's way. 2659 * 2660 * Flag to hide only the home button. Don't use this 2661 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2662 */ 2663 public static final int STATUS_BAR_DISABLE_HOME = 0x00200000; 2664 2665 /** 2666 * @hide 2667 * 2668 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2669 * out of the public fields to keep the undefined bits out of the developer's way. 2670 * 2671 * Flag to hide only the back button. Don't use this 2672 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2673 */ 2674 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 2675 2676 /** 2677 * @hide 2678 * 2679 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2680 * out of the public fields to keep the undefined bits out of the developer's way. 2681 * 2682 * Flag to hide only the clock. You might use this if your activity has 2683 * its own clock making the status bar's clock redundant. 2684 */ 2685 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 2686 2687 /** 2688 * @hide 2689 * 2690 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2691 * out of the public fields to keep the undefined bits out of the developer's way. 2692 * 2693 * Flag to hide only the recent apps button. Don't use this 2694 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2695 */ 2696 public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000; 2697 2698 /** 2699 * @hide 2700 * 2701 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2702 * out of the public fields to keep the undefined bits out of the developer's way. 2703 * 2704 * Flag to disable the global search gesture. Don't use this 2705 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2706 */ 2707 public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000; 2708 2709 /** 2710 * @hide 2711 * 2712 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2713 * out of the public fields to keep the undefined bits out of the developer's way. 2714 * 2715 * Flag to specify that the status bar is displayed in transient mode. 2716 */ 2717 public static final int STATUS_BAR_TRANSIENT = 0x04000000; 2718 2719 /** 2720 * @hide 2721 * 2722 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2723 * out of the public fields to keep the undefined bits out of the developer's way. 2724 * 2725 * Flag to specify that the navigation bar is displayed in transient mode. 2726 */ 2727 public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000; 2728 2729 /** 2730 * @hide 2731 * 2732 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2733 * out of the public fields to keep the undefined bits out of the developer's way. 2734 * 2735 * Flag to specify that the hidden status bar would like to be shown. 2736 */ 2737 public static final int STATUS_BAR_UNHIDE = 0x10000000; 2738 2739 /** 2740 * @hide 2741 * 2742 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2743 * out of the public fields to keep the undefined bits out of the developer's way. 2744 * 2745 * Flag to specify that the hidden navigation bar would like to be shown. 2746 */ 2747 public static final int NAVIGATION_BAR_UNHIDE = 0x20000000; 2748 2749 /** 2750 * @hide 2751 * 2752 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2753 * out of the public fields to keep the undefined bits out of the developer's way. 2754 * 2755 * Flag to specify that the status bar is displayed in translucent mode. 2756 */ 2757 public static final int STATUS_BAR_TRANSLUCENT = 0x40000000; 2758 2759 /** 2760 * @hide 2761 * 2762 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2763 * out of the public fields to keep the undefined bits out of the developer's way. 2764 * 2765 * Flag to specify that the navigation bar is displayed in translucent mode. 2766 */ 2767 public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000; 2768 2769 /** 2770 * @hide 2771 */ 2772 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF; 2773 2774 /** 2775 * These are the system UI flags that can be cleared by events outside 2776 * of an application. Currently this is just the ability to tap on the 2777 * screen while hiding the navigation bar to have it return. 2778 * @hide 2779 */ 2780 public static final int SYSTEM_UI_CLEARABLE_FLAGS = 2781 SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION 2782 | SYSTEM_UI_FLAG_FULLSCREEN; 2783 2784 /** 2785 * Flags that can impact the layout in relation to system UI. 2786 */ 2787 public static final int SYSTEM_UI_LAYOUT_FLAGS = 2788 SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 2789 | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; 2790 2791 /** @hide */ 2792 @IntDef(flag = true, 2793 value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION }) 2794 @Retention(RetentionPolicy.SOURCE) 2795 public @interface FindViewFlags {} 2796 2797 /** 2798 * Find views that render the specified text. 2799 * 2800 * @see #findViewsWithText(ArrayList, CharSequence, int) 2801 */ 2802 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001; 2803 2804 /** 2805 * Find find views that contain the specified content description. 2806 * 2807 * @see #findViewsWithText(ArrayList, CharSequence, int) 2808 */ 2809 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002; 2810 2811 /** 2812 * Find views that contain {@link AccessibilityNodeProvider}. Such 2813 * a View is a root of virtual view hierarchy and may contain the searched 2814 * text. If this flag is set Views with providers are automatically 2815 * added and it is a responsibility of the client to call the APIs of 2816 * the provider to determine whether the virtual tree rooted at this View 2817 * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s 2818 * representing the virtual views with this text. 2819 * 2820 * @see #findViewsWithText(ArrayList, CharSequence, int) 2821 * 2822 * @hide 2823 */ 2824 public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004; 2825 2826 /** 2827 * The undefined cursor position. 2828 * 2829 * @hide 2830 */ 2831 public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1; 2832 2833 /** 2834 * Indicates that the screen has changed state and is now off. 2835 * 2836 * @see #onScreenStateChanged(int) 2837 */ 2838 public static final int SCREEN_STATE_OFF = 0x0; 2839 2840 /** 2841 * Indicates that the screen has changed state and is now on. 2842 * 2843 * @see #onScreenStateChanged(int) 2844 */ 2845 public static final int SCREEN_STATE_ON = 0x1; 2846 2847 /** 2848 * Controls the over-scroll mode for this view. 2849 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 2850 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 2851 * and {@link #OVER_SCROLL_NEVER}. 2852 */ 2853 private int mOverScrollMode; 2854 2855 /** 2856 * The parent this view is attached to. 2857 * {@hide} 2858 * 2859 * @see #getParent() 2860 */ 2861 protected ViewParent mParent; 2862 2863 /** 2864 * {@hide} 2865 */ 2866 AttachInfo mAttachInfo; 2867 2868 /** 2869 * {@hide} 2870 */ 2871 @ViewDebug.ExportedProperty(flagMapping = { 2872 @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT, 2873 name = "FORCE_LAYOUT"), 2874 @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED, 2875 name = "LAYOUT_REQUIRED"), 2876 @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID, 2877 name = "DRAWING_CACHE_INVALID", outputIf = false), 2878 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true), 2879 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false), 2880 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 2881 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY") 2882 }) 2883 int mPrivateFlags; 2884 int mPrivateFlags2; 2885 int mPrivateFlags3; 2886 2887 /** 2888 * This view's request for the visibility of the status bar. 2889 * @hide 2890 */ 2891 @ViewDebug.ExportedProperty(flagMapping = { 2892 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 2893 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 2894 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 2895 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2896 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2897 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 2898 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 2899 equals = SYSTEM_UI_FLAG_VISIBLE, 2900 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 2901 }) 2902 int mSystemUiVisibility; 2903 2904 /** 2905 * Reference count for transient state. 2906 * @see #setHasTransientState(boolean) 2907 */ 2908 int mTransientStateCount = 0; 2909 2910 /** 2911 * Count of how many windows this view has been attached to. 2912 */ 2913 int mWindowAttachCount; 2914 2915 /** 2916 * The layout parameters associated with this view and used by the parent 2917 * {@link android.view.ViewGroup} to determine how this view should be 2918 * laid out. 2919 * {@hide} 2920 */ 2921 protected ViewGroup.LayoutParams mLayoutParams; 2922 2923 /** 2924 * The view flags hold various views states. 2925 * {@hide} 2926 */ 2927 @ViewDebug.ExportedProperty 2928 int mViewFlags; 2929 2930 static class TransformationInfo { 2931 /** 2932 * The transform matrix for the View. This transform is calculated internally 2933 * based on the rotation, scaleX, and scaleY properties. The identity matrix 2934 * is used by default. Do *not* use this variable directly; instead call 2935 * getMatrix(), which will automatically recalculate the matrix if necessary 2936 * to get the correct matrix based on the latest rotation and scale properties. 2937 */ 2938 private final Matrix mMatrix = new Matrix(); 2939 2940 /** 2941 * The transform matrix for the View. This transform is calculated internally 2942 * based on the rotation, scaleX, and scaleY properties. The identity matrix 2943 * is used by default. Do *not* use this variable directly; instead call 2944 * getInverseMatrix(), which will automatically recalculate the matrix if necessary 2945 * to get the correct matrix based on the latest rotation and scale properties. 2946 */ 2947 private Matrix mInverseMatrix; 2948 2949 /** 2950 * An internal variable that tracks whether we need to recalculate the 2951 * transform matrix, based on whether the rotation or scaleX/Y properties 2952 * have changed since the matrix was last calculated. 2953 */ 2954 boolean mMatrixDirty = false; 2955 2956 /** 2957 * An internal variable that tracks whether we need to recalculate the 2958 * transform matrix, based on whether the rotation or scaleX/Y properties 2959 * have changed since the matrix was last calculated. 2960 */ 2961 private boolean mInverseMatrixDirty = true; 2962 2963 /** 2964 * A variable that tracks whether we need to recalculate the 2965 * transform matrix, based on whether the rotation or scaleX/Y properties 2966 * have changed since the matrix was last calculated. This variable 2967 * is only valid after a call to updateMatrix() or to a function that 2968 * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix(). 2969 */ 2970 private boolean mMatrixIsIdentity = true; 2971 2972 /** 2973 * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set. 2974 */ 2975 private Camera mCamera = null; 2976 2977 /** 2978 * This matrix is used when computing the matrix for 3D rotations. 2979 */ 2980 private Matrix matrix3D = null; 2981 2982 /** 2983 * These prev values are used to recalculate a centered pivot point when necessary. The 2984 * pivot point is only used in matrix operations (when rotation, scale, or translation are 2985 * set), so thes values are only used then as well. 2986 */ 2987 private int mPrevWidth = -1; 2988 private int mPrevHeight = -1; 2989 2990 /** 2991 * The degrees rotation around the vertical axis through the pivot point. 2992 */ 2993 @ViewDebug.ExportedProperty 2994 float mRotationY = 0f; 2995 2996 /** 2997 * The degrees rotation around the horizontal axis through the pivot point. 2998 */ 2999 @ViewDebug.ExportedProperty 3000 float mRotationX = 0f; 3001 3002 /** 3003 * The degrees rotation around the pivot point. 3004 */ 3005 @ViewDebug.ExportedProperty 3006 float mRotation = 0f; 3007 3008 /** 3009 * The amount of translation of the object away from its left property (post-layout). 3010 */ 3011 @ViewDebug.ExportedProperty 3012 float mTranslationX = 0f; 3013 3014 /** 3015 * The amount of translation of the object away from its top property (post-layout). 3016 */ 3017 @ViewDebug.ExportedProperty 3018 float mTranslationY = 0f; 3019 3020 @ViewDebug.ExportedProperty 3021 float mTranslationZ = 0f; 3022 3023 /** 3024 * The amount of scale in the x direction around the pivot point. A 3025 * value of 1 means no scaling is applied. 3026 */ 3027 @ViewDebug.ExportedProperty 3028 float mScaleX = 1f; 3029 3030 /** 3031 * The amount of scale in the y direction around the pivot point. A 3032 * value of 1 means no scaling is applied. 3033 */ 3034 @ViewDebug.ExportedProperty 3035 float mScaleY = 1f; 3036 3037 /** 3038 * The x location of the point around which the view is rotated and scaled. 3039 */ 3040 @ViewDebug.ExportedProperty 3041 float mPivotX = 0f; 3042 3043 /** 3044 * The y location of the point around which the view is rotated and scaled. 3045 */ 3046 @ViewDebug.ExportedProperty 3047 float mPivotY = 0f; 3048 3049 /** 3050 * The opacity of the View. This is a value from 0 to 1, where 0 means 3051 * completely transparent and 1 means completely opaque. 3052 */ 3053 @ViewDebug.ExportedProperty 3054 float mAlpha = 1f; 3055 3056 /** 3057 * The opacity of the view as manipulated by the Fade transition. This is a hidden 3058 * property only used by transitions, which is composited with the other alpha 3059 * values to calculate the final visual alpha value. 3060 */ 3061 float mTransitionAlpha = 1f; 3062 } 3063 3064 TransformationInfo mTransformationInfo; 3065 3066 /** 3067 * Current clip bounds. to which all drawing of this view are constrained. 3068 */ 3069 private Rect mClipBounds = null; 3070 3071 private boolean mLastIsOpaque; 3072 3073 /** 3074 * Convenience value to check for float values that are close enough to zero to be considered 3075 * zero. 3076 */ 3077 private static final float NONZERO_EPSILON = .001f; 3078 3079 /** 3080 * The distance in pixels from the left edge of this view's parent 3081 * to the left edge of this view. 3082 * {@hide} 3083 */ 3084 @ViewDebug.ExportedProperty(category = "layout") 3085 protected int mLeft; 3086 /** 3087 * The distance in pixels from the left edge of this view's parent 3088 * to the right edge of this view. 3089 * {@hide} 3090 */ 3091 @ViewDebug.ExportedProperty(category = "layout") 3092 protected int mRight; 3093 /** 3094 * The distance in pixels from the top edge of this view's parent 3095 * to the top edge of this view. 3096 * {@hide} 3097 */ 3098 @ViewDebug.ExportedProperty(category = "layout") 3099 protected int mTop; 3100 /** 3101 * The distance in pixels from the top edge of this view's parent 3102 * to the bottom edge of this view. 3103 * {@hide} 3104 */ 3105 @ViewDebug.ExportedProperty(category = "layout") 3106 protected int mBottom; 3107 3108 /** 3109 * The offset, in pixels, by which the content of this view is scrolled 3110 * horizontally. 3111 * {@hide} 3112 */ 3113 @ViewDebug.ExportedProperty(category = "scrolling") 3114 protected int mScrollX; 3115 /** 3116 * The offset, in pixels, by which the content of this view is scrolled 3117 * vertically. 3118 * {@hide} 3119 */ 3120 @ViewDebug.ExportedProperty(category = "scrolling") 3121 protected int mScrollY; 3122 3123 /** 3124 * The left padding in pixels, that is the distance in pixels between the 3125 * left edge of this view and the left edge of its content. 3126 * {@hide} 3127 */ 3128 @ViewDebug.ExportedProperty(category = "padding") 3129 protected int mPaddingLeft = 0; 3130 /** 3131 * The right padding in pixels, that is the distance in pixels between the 3132 * right edge of this view and the right edge of its content. 3133 * {@hide} 3134 */ 3135 @ViewDebug.ExportedProperty(category = "padding") 3136 protected int mPaddingRight = 0; 3137 /** 3138 * The top padding in pixels, that is the distance in pixels between the 3139 * top edge of this view and the top edge of its content. 3140 * {@hide} 3141 */ 3142 @ViewDebug.ExportedProperty(category = "padding") 3143 protected int mPaddingTop; 3144 /** 3145 * The bottom padding in pixels, that is the distance in pixels between the 3146 * bottom edge of this view and the bottom edge of its content. 3147 * {@hide} 3148 */ 3149 @ViewDebug.ExportedProperty(category = "padding") 3150 protected int mPaddingBottom; 3151 3152 /** 3153 * The layout insets in pixels, that is the distance in pixels between the 3154 * visible edges of this view its bounds. 3155 */ 3156 private Insets mLayoutInsets; 3157 3158 /** 3159 * Briefly describes the view and is primarily used for accessibility support. 3160 */ 3161 private CharSequence mContentDescription; 3162 3163 /** 3164 * Specifies the id of a view for which this view serves as a label for 3165 * accessibility purposes. 3166 */ 3167 private int mLabelForId = View.NO_ID; 3168 3169 /** 3170 * Predicate for matching labeled view id with its label for 3171 * accessibility purposes. 3172 */ 3173 private MatchLabelForPredicate mMatchLabelForPredicate; 3174 3175 /** 3176 * Predicate for matching a view by its id. 3177 */ 3178 private MatchIdPredicate mMatchIdPredicate; 3179 3180 /** 3181 * Cache the paddingRight set by the user to append to the scrollbar's size. 3182 * 3183 * @hide 3184 */ 3185 @ViewDebug.ExportedProperty(category = "padding") 3186 protected int mUserPaddingRight; 3187 3188 /** 3189 * Cache the paddingBottom set by the user to append to the scrollbar's size. 3190 * 3191 * @hide 3192 */ 3193 @ViewDebug.ExportedProperty(category = "padding") 3194 protected int mUserPaddingBottom; 3195 3196 /** 3197 * Cache the paddingLeft set by the user to append to the scrollbar's size. 3198 * 3199 * @hide 3200 */ 3201 @ViewDebug.ExportedProperty(category = "padding") 3202 protected int mUserPaddingLeft; 3203 3204 /** 3205 * Cache the paddingStart set by the user to append to the scrollbar's size. 3206 * 3207 */ 3208 @ViewDebug.ExportedProperty(category = "padding") 3209 int mUserPaddingStart; 3210 3211 /** 3212 * Cache the paddingEnd set by the user to append to the scrollbar's size. 3213 * 3214 */ 3215 @ViewDebug.ExportedProperty(category = "padding") 3216 int mUserPaddingEnd; 3217 3218 /** 3219 * Cache initial left padding. 3220 * 3221 * @hide 3222 */ 3223 int mUserPaddingLeftInitial; 3224 3225 /** 3226 * Cache initial right padding. 3227 * 3228 * @hide 3229 */ 3230 int mUserPaddingRightInitial; 3231 3232 /** 3233 * Default undefined padding 3234 */ 3235 private static final int UNDEFINED_PADDING = Integer.MIN_VALUE; 3236 3237 /** 3238 * Cache if a left padding has been defined 3239 */ 3240 private boolean mLeftPaddingDefined = false; 3241 3242 /** 3243 * Cache if a right padding has been defined 3244 */ 3245 private boolean mRightPaddingDefined = false; 3246 3247 /** 3248 * @hide 3249 */ 3250 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 3251 /** 3252 * @hide 3253 */ 3254 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 3255 3256 private LongSparseLongArray mMeasureCache; 3257 3258 @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_") 3259 private Drawable mBackground; 3260 3261 /** 3262 * Display list used for backgrounds. 3263 * <p> 3264 * When non-null and valid, this is expected to contain an up-to-date copy 3265 * of the background drawable. It is cleared on temporary detach and reset 3266 * on cleanup. 3267 */ 3268 private RenderNode mBackgroundDisplayList; 3269 3270 private int mBackgroundResource; 3271 private boolean mBackgroundSizeChanged; 3272 3273 static class ListenerInfo { 3274 /** 3275 * Listener used to dispatch focus change events. 3276 * This field should be made private, so it is hidden from the SDK. 3277 * {@hide} 3278 */ 3279 protected OnFocusChangeListener mOnFocusChangeListener; 3280 3281 /** 3282 * Listeners for layout change events. 3283 */ 3284 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 3285 3286 /** 3287 * Listeners for attach events. 3288 */ 3289 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 3290 3291 /** 3292 * Listener used to dispatch click events. 3293 * This field should be made private, so it is hidden from the SDK. 3294 * {@hide} 3295 */ 3296 public OnClickListener mOnClickListener; 3297 3298 /** 3299 * Listener used to dispatch long click events. 3300 * This field should be made private, so it is hidden from the SDK. 3301 * {@hide} 3302 */ 3303 protected OnLongClickListener mOnLongClickListener; 3304 3305 /** 3306 * Listener used to build the context menu. 3307 * This field should be made private, so it is hidden from the SDK. 3308 * {@hide} 3309 */ 3310 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 3311 3312 private OnKeyListener mOnKeyListener; 3313 3314 private OnTouchListener mOnTouchListener; 3315 3316 private OnHoverListener mOnHoverListener; 3317 3318 private OnGenericMotionListener mOnGenericMotionListener; 3319 3320 private OnDragListener mOnDragListener; 3321 3322 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 3323 3324 OnApplyWindowInsetsListener mOnApplyWindowInsetsListener; 3325 } 3326 3327 ListenerInfo mListenerInfo; 3328 3329 /** 3330 * The application environment this view lives in. 3331 * This field should be made private, so it is hidden from the SDK. 3332 * {@hide} 3333 */ 3334 protected Context mContext; 3335 3336 private final Resources mResources; 3337 3338 private ScrollabilityCache mScrollCache; 3339 3340 private int[] mDrawableState = null; 3341 3342 /** 3343 * Stores the outline of the view, passed down to the DisplayList level for 3344 * defining shadow shape and clipping. 3345 * 3346 * TODO: once RenderNode is long-lived, remove this and rely on native copy. 3347 */ 3348 private Outline mOutline; 3349 3350 /** 3351 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 3352 * the user may specify which view to go to next. 3353 */ 3354 private int mNextFocusLeftId = View.NO_ID; 3355 3356 /** 3357 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 3358 * the user may specify which view to go to next. 3359 */ 3360 private int mNextFocusRightId = View.NO_ID; 3361 3362 /** 3363 * When this view has focus and the next focus is {@link #FOCUS_UP}, 3364 * the user may specify which view to go to next. 3365 */ 3366 private int mNextFocusUpId = View.NO_ID; 3367 3368 /** 3369 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 3370 * the user may specify which view to go to next. 3371 */ 3372 private int mNextFocusDownId = View.NO_ID; 3373 3374 /** 3375 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 3376 * the user may specify which view to go to next. 3377 */ 3378 int mNextFocusForwardId = View.NO_ID; 3379 3380 private CheckForLongPress mPendingCheckForLongPress; 3381 private CheckForTap mPendingCheckForTap = null; 3382 private PerformClick mPerformClick; 3383 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 3384 3385 private UnsetPressedState mUnsetPressedState; 3386 3387 /** 3388 * Whether the long press's action has been invoked. The tap's action is invoked on the 3389 * up event while a long press is invoked as soon as the long press duration is reached, so 3390 * a long press could be performed before the tap is checked, in which case the tap's action 3391 * should not be invoked. 3392 */ 3393 private boolean mHasPerformedLongPress; 3394 3395 /** 3396 * The minimum height of the view. We'll try our best to have the height 3397 * of this view to at least this amount. 3398 */ 3399 @ViewDebug.ExportedProperty(category = "measurement") 3400 private int mMinHeight; 3401 3402 /** 3403 * The minimum width of the view. We'll try our best to have the width 3404 * of this view to at least this amount. 3405 */ 3406 @ViewDebug.ExportedProperty(category = "measurement") 3407 private int mMinWidth; 3408 3409 /** 3410 * The delegate to handle touch events that are physically in this view 3411 * but should be handled by another view. 3412 */ 3413 private TouchDelegate mTouchDelegate = null; 3414 3415 /** 3416 * Solid color to use as a background when creating the drawing cache. Enables 3417 * the cache to use 16 bit bitmaps instead of 32 bit. 3418 */ 3419 private int mDrawingCacheBackgroundColor = 0; 3420 3421 /** 3422 * Special tree observer used when mAttachInfo is null. 3423 */ 3424 private ViewTreeObserver mFloatingTreeObserver; 3425 3426 /** 3427 * Cache the touch slop from the context that created the view. 3428 */ 3429 private int mTouchSlop; 3430 3431 /** 3432 * Object that handles automatic animation of view properties. 3433 */ 3434 private ViewPropertyAnimator mAnimator = null; 3435 3436 /** 3437 * Flag indicating that a drag can cross window boundaries. When 3438 * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called 3439 * with this flag set, all visible applications will be able to participate 3440 * in the drag operation and receive the dragged content. 3441 * 3442 * @hide 3443 */ 3444 public static final int DRAG_FLAG_GLOBAL = 1; 3445 3446 /** 3447 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 3448 */ 3449 private float mVerticalScrollFactor; 3450 3451 /** 3452 * Position of the vertical scroll bar. 3453 */ 3454 private int mVerticalScrollbarPosition; 3455 3456 /** 3457 * Position the scroll bar at the default position as determined by the system. 3458 */ 3459 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 3460 3461 /** 3462 * Position the scroll bar along the left edge. 3463 */ 3464 public static final int SCROLLBAR_POSITION_LEFT = 1; 3465 3466 /** 3467 * Position the scroll bar along the right edge. 3468 */ 3469 public static final int SCROLLBAR_POSITION_RIGHT = 2; 3470 3471 /** 3472 * Indicates that the view does not have a layer. 3473 * 3474 * @see #getLayerType() 3475 * @see #setLayerType(int, android.graphics.Paint) 3476 * @see #LAYER_TYPE_SOFTWARE 3477 * @see #LAYER_TYPE_HARDWARE 3478 */ 3479 public static final int LAYER_TYPE_NONE = 0; 3480 3481 /** 3482 * <p>Indicates that the view has a software layer. A software layer is backed 3483 * by a bitmap and causes the view to be rendered using Android's software 3484 * rendering pipeline, even if hardware acceleration is enabled.</p> 3485 * 3486 * <p>Software layers have various usages:</p> 3487 * <p>When the application is not using hardware acceleration, a software layer 3488 * is useful to apply a specific color filter and/or blending mode and/or 3489 * translucency to a view and all its children.</p> 3490 * <p>When the application is using hardware acceleration, a software layer 3491 * is useful to render drawing primitives not supported by the hardware 3492 * accelerated pipeline. It can also be used to cache a complex view tree 3493 * into a texture and reduce the complexity of drawing operations. For instance, 3494 * when animating a complex view tree with a translation, a software layer can 3495 * be used to render the view tree only once.</p> 3496 * <p>Software layers should be avoided when the affected view tree updates 3497 * often. Every update will require to re-render the software layer, which can 3498 * potentially be slow (particularly when hardware acceleration is turned on 3499 * since the layer will have to be uploaded into a hardware texture after every 3500 * update.)</p> 3501 * 3502 * @see #getLayerType() 3503 * @see #setLayerType(int, android.graphics.Paint) 3504 * @see #LAYER_TYPE_NONE 3505 * @see #LAYER_TYPE_HARDWARE 3506 */ 3507 public static final int LAYER_TYPE_SOFTWARE = 1; 3508 3509 /** 3510 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 3511 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 3512 * OpenGL hardware) and causes the view to be rendered using Android's hardware 3513 * rendering pipeline, but only if hardware acceleration is turned on for the 3514 * view hierarchy. When hardware acceleration is turned off, hardware layers 3515 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 3516 * 3517 * <p>A hardware layer is useful to apply a specific color filter and/or 3518 * blending mode and/or translucency to a view and all its children.</p> 3519 * <p>A hardware layer can be used to cache a complex view tree into a 3520 * texture and reduce the complexity of drawing operations. For instance, 3521 * when animating a complex view tree with a translation, a hardware layer can 3522 * be used to render the view tree only once.</p> 3523 * <p>A hardware layer can also be used to increase the rendering quality when 3524 * rotation transformations are applied on a view. It can also be used to 3525 * prevent potential clipping issues when applying 3D transforms on a view.</p> 3526 * 3527 * @see #getLayerType() 3528 * @see #setLayerType(int, android.graphics.Paint) 3529 * @see #LAYER_TYPE_NONE 3530 * @see #LAYER_TYPE_SOFTWARE 3531 */ 3532 public static final int LAYER_TYPE_HARDWARE = 2; 3533 3534 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 3535 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 3536 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 3537 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 3538 }) 3539 int mLayerType = LAYER_TYPE_NONE; 3540 Paint mLayerPaint; 3541 Rect mLocalDirtyRect; 3542 private HardwareLayer mHardwareLayer; 3543 3544 /** 3545 * Set to true when drawing cache is enabled and cannot be created. 3546 * 3547 * @hide 3548 */ 3549 public boolean mCachingFailed; 3550 private Bitmap mDrawingCache; 3551 private Bitmap mUnscaledDrawingCache; 3552 3553 /** 3554 * RenderNode holding View properties, potentially holding a DisplayList of View content. 3555 * <p> 3556 * When non-null and valid, this is expected to contain an up-to-date copy 3557 * of the View content. Its DisplayList content is cleared on temporary detach and reset on 3558 * cleanup. 3559 */ 3560 RenderNode mRenderNode; 3561 3562 /** 3563 * Set to true when the view is sending hover accessibility events because it 3564 * is the innermost hovered view. 3565 */ 3566 private boolean mSendingHoverAccessibilityEvents; 3567 3568 /** 3569 * Delegate for injecting accessibility functionality. 3570 */ 3571 AccessibilityDelegate mAccessibilityDelegate; 3572 3573 /** 3574 * The view's overlay layer. Developers get a reference to the overlay via getOverlay() 3575 * and add/remove objects to/from the overlay directly through the Overlay methods. 3576 */ 3577 ViewOverlay mOverlay; 3578 3579 /** 3580 * Consistency verifier for debugging purposes. 3581 * @hide 3582 */ 3583 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 3584 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 3585 new InputEventConsistencyVerifier(this, 0) : null; 3586 3587 private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); 3588 3589 /** 3590 * Simple constructor to use when creating a view from code. 3591 * 3592 * @param context The Context the view is running in, through which it can 3593 * access the current theme, resources, etc. 3594 */ 3595 public View(Context context) { 3596 mContext = context; 3597 mResources = context != null ? context.getResources() : null; 3598 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED; 3599 // Set some flags defaults 3600 mPrivateFlags2 = 3601 (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) | 3602 (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) | 3603 (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) | 3604 (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) | 3605 (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) | 3606 (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT); 3607 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 3608 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 3609 mUserPaddingStart = UNDEFINED_PADDING; 3610 mUserPaddingEnd = UNDEFINED_PADDING; 3611 3612 if (!sCompatibilityDone && context != null) { 3613 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3614 3615 // Older apps may need this compatibility hack for measurement. 3616 sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1; 3617 3618 // Older apps expect onMeasure() to always be called on a layout pass, regardless 3619 // of whether a layout was requested on that View. 3620 sIgnoreMeasureCache = targetSdkVersion < KITKAT; 3621 3622 sCompatibilityDone = true; 3623 } 3624 } 3625 3626 /** 3627 * Constructor that is called when inflating a view from XML. This is called 3628 * when a view is being constructed from an XML file, supplying attributes 3629 * that were specified in the XML file. This version uses a default style of 3630 * 0, so the only attribute values applied are those in the Context's Theme 3631 * and the given AttributeSet. 3632 * 3633 * <p> 3634 * The method onFinishInflate() will be called after all children have been 3635 * added. 3636 * 3637 * @param context The Context the view is running in, through which it can 3638 * access the current theme, resources, etc. 3639 * @param attrs The attributes of the XML tag that is inflating the view. 3640 * @see #View(Context, AttributeSet, int) 3641 */ 3642 public View(Context context, AttributeSet attrs) { 3643 this(context, attrs, 0); 3644 } 3645 3646 /** 3647 * Perform inflation from XML and apply a class-specific base style from a 3648 * theme attribute. This constructor of View allows subclasses to use their 3649 * own base style when they are inflating. For example, a Button class's 3650 * constructor would call this version of the super class constructor and 3651 * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this 3652 * allows the theme's button style to modify all of the base view attributes 3653 * (in particular its background) as well as the Button class's attributes. 3654 * 3655 * @param context The Context the view is running in, through which it can 3656 * access the current theme, resources, etc. 3657 * @param attrs The attributes of the XML tag that is inflating the view. 3658 * @param defStyleAttr An attribute in the current theme that contains a 3659 * reference to a style resource that supplies default values for 3660 * the view. Can be 0 to not look for defaults. 3661 * @see #View(Context, AttributeSet) 3662 */ 3663 public View(Context context, AttributeSet attrs, int defStyleAttr) { 3664 this(context, attrs, defStyleAttr, 0); 3665 } 3666 3667 /** 3668 * Perform inflation from XML and apply a class-specific base style from a 3669 * theme attribute or style resource. This constructor of View allows 3670 * subclasses to use their own base style when they are inflating. 3671 * <p> 3672 * When determining the final value of a particular attribute, there are 3673 * four inputs that come into play: 3674 * <ol> 3675 * <li>Any attribute values in the given AttributeSet. 3676 * <li>The style resource specified in the AttributeSet (named "style"). 3677 * <li>The default style specified by <var>defStyleAttr</var>. 3678 * <li>The default style specified by <var>defStyleRes</var>. 3679 * <li>The base values in this theme. 3680 * </ol> 3681 * <p> 3682 * Each of these inputs is considered in-order, with the first listed taking 3683 * precedence over the following ones. In other words, if in the 3684 * AttributeSet you have supplied <code><Button * textColor="#ff000000"></code> 3685 * , then the button's text will <em>always</em> be black, regardless of 3686 * what is specified in any of the styles. 3687 * 3688 * @param context The Context the view is running in, through which it can 3689 * access the current theme, resources, etc. 3690 * @param attrs The attributes of the XML tag that is inflating the view. 3691 * @param defStyleAttr An attribute in the current theme that contains a 3692 * reference to a style resource that supplies default values for 3693 * the view. Can be 0 to not look for defaults. 3694 * @param defStyleRes A resource identifier of a style resource that 3695 * supplies default values for the view, used only if 3696 * defStyleAttr is 0 or can not be found in the theme. Can be 0 3697 * to not look for defaults. 3698 * @see #View(Context, AttributeSet, int) 3699 */ 3700 public View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { 3701 this(context); 3702 3703 final TypedArray a = context.obtainStyledAttributes( 3704 attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes); 3705 3706 Drawable background = null; 3707 3708 int leftPadding = -1; 3709 int topPadding = -1; 3710 int rightPadding = -1; 3711 int bottomPadding = -1; 3712 int startPadding = UNDEFINED_PADDING; 3713 int endPadding = UNDEFINED_PADDING; 3714 3715 int padding = -1; 3716 3717 int viewFlagValues = 0; 3718 int viewFlagMasks = 0; 3719 3720 boolean setScrollContainer = false; 3721 3722 int x = 0; 3723 int y = 0; 3724 3725 float tx = 0; 3726 float ty = 0; 3727 float tz = 0; 3728 float rotation = 0; 3729 float rotationX = 0; 3730 float rotationY = 0; 3731 float sx = 1f; 3732 float sy = 1f; 3733 boolean transformSet = false; 3734 3735 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 3736 int overScrollMode = mOverScrollMode; 3737 boolean initializeScrollbars = false; 3738 3739 boolean startPaddingDefined = false; 3740 boolean endPaddingDefined = false; 3741 boolean leftPaddingDefined = false; 3742 boolean rightPaddingDefined = false; 3743 3744 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3745 3746 final int N = a.getIndexCount(); 3747 for (int i = 0; i < N; i++) { 3748 int attr = a.getIndex(i); 3749 switch (attr) { 3750 case com.android.internal.R.styleable.View_background: 3751 background = a.getDrawable(attr); 3752 break; 3753 case com.android.internal.R.styleable.View_padding: 3754 padding = a.getDimensionPixelSize(attr, -1); 3755 mUserPaddingLeftInitial = padding; 3756 mUserPaddingRightInitial = padding; 3757 leftPaddingDefined = true; 3758 rightPaddingDefined = true; 3759 break; 3760 case com.android.internal.R.styleable.View_paddingLeft: 3761 leftPadding = a.getDimensionPixelSize(attr, -1); 3762 mUserPaddingLeftInitial = leftPadding; 3763 leftPaddingDefined = true; 3764 break; 3765 case com.android.internal.R.styleable.View_paddingTop: 3766 topPadding = a.getDimensionPixelSize(attr, -1); 3767 break; 3768 case com.android.internal.R.styleable.View_paddingRight: 3769 rightPadding = a.getDimensionPixelSize(attr, -1); 3770 mUserPaddingRightInitial = rightPadding; 3771 rightPaddingDefined = true; 3772 break; 3773 case com.android.internal.R.styleable.View_paddingBottom: 3774 bottomPadding = a.getDimensionPixelSize(attr, -1); 3775 break; 3776 case com.android.internal.R.styleable.View_paddingStart: 3777 startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3778 startPaddingDefined = (startPadding != UNDEFINED_PADDING); 3779 break; 3780 case com.android.internal.R.styleable.View_paddingEnd: 3781 endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3782 endPaddingDefined = (endPadding != UNDEFINED_PADDING); 3783 break; 3784 case com.android.internal.R.styleable.View_scrollX: 3785 x = a.getDimensionPixelOffset(attr, 0); 3786 break; 3787 case com.android.internal.R.styleable.View_scrollY: 3788 y = a.getDimensionPixelOffset(attr, 0); 3789 break; 3790 case com.android.internal.R.styleable.View_alpha: 3791 setAlpha(a.getFloat(attr, 1f)); 3792 break; 3793 case com.android.internal.R.styleable.View_transformPivotX: 3794 setPivotX(a.getDimensionPixelOffset(attr, 0)); 3795 break; 3796 case com.android.internal.R.styleable.View_transformPivotY: 3797 setPivotY(a.getDimensionPixelOffset(attr, 0)); 3798 break; 3799 case com.android.internal.R.styleable.View_translationX: 3800 tx = a.getDimensionPixelOffset(attr, 0); 3801 transformSet = true; 3802 break; 3803 case com.android.internal.R.styleable.View_translationY: 3804 ty = a.getDimensionPixelOffset(attr, 0); 3805 transformSet = true; 3806 break; 3807 case com.android.internal.R.styleable.View_translationZ: 3808 tz = a.getDimensionPixelOffset(attr, 0); 3809 transformSet = true; 3810 break; 3811 case com.android.internal.R.styleable.View_rotation: 3812 rotation = a.getFloat(attr, 0); 3813 transformSet = true; 3814 break; 3815 case com.android.internal.R.styleable.View_rotationX: 3816 rotationX = a.getFloat(attr, 0); 3817 transformSet = true; 3818 break; 3819 case com.android.internal.R.styleable.View_rotationY: 3820 rotationY = a.getFloat(attr, 0); 3821 transformSet = true; 3822 break; 3823 case com.android.internal.R.styleable.View_scaleX: 3824 sx = a.getFloat(attr, 1f); 3825 transformSet = true; 3826 break; 3827 case com.android.internal.R.styleable.View_scaleY: 3828 sy = a.getFloat(attr, 1f); 3829 transformSet = true; 3830 break; 3831 case com.android.internal.R.styleable.View_id: 3832 mID = a.getResourceId(attr, NO_ID); 3833 break; 3834 case com.android.internal.R.styleable.View_tag: 3835 mTag = a.getText(attr); 3836 break; 3837 case com.android.internal.R.styleable.View_fitsSystemWindows: 3838 if (a.getBoolean(attr, false)) { 3839 viewFlagValues |= FITS_SYSTEM_WINDOWS; 3840 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 3841 } 3842 break; 3843 case com.android.internal.R.styleable.View_focusable: 3844 if (a.getBoolean(attr, false)) { 3845 viewFlagValues |= FOCUSABLE; 3846 viewFlagMasks |= FOCUSABLE_MASK; 3847 } 3848 break; 3849 case com.android.internal.R.styleable.View_focusableInTouchMode: 3850 if (a.getBoolean(attr, false)) { 3851 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 3852 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 3853 } 3854 break; 3855 case com.android.internal.R.styleable.View_clickable: 3856 if (a.getBoolean(attr, false)) { 3857 viewFlagValues |= CLICKABLE; 3858 viewFlagMasks |= CLICKABLE; 3859 } 3860 break; 3861 case com.android.internal.R.styleable.View_longClickable: 3862 if (a.getBoolean(attr, false)) { 3863 viewFlagValues |= LONG_CLICKABLE; 3864 viewFlagMasks |= LONG_CLICKABLE; 3865 } 3866 break; 3867 case com.android.internal.R.styleable.View_saveEnabled: 3868 if (!a.getBoolean(attr, true)) { 3869 viewFlagValues |= SAVE_DISABLED; 3870 viewFlagMasks |= SAVE_DISABLED_MASK; 3871 } 3872 break; 3873 case com.android.internal.R.styleable.View_duplicateParentState: 3874 if (a.getBoolean(attr, false)) { 3875 viewFlagValues |= DUPLICATE_PARENT_STATE; 3876 viewFlagMasks |= DUPLICATE_PARENT_STATE; 3877 } 3878 break; 3879 case com.android.internal.R.styleable.View_visibility: 3880 final int visibility = a.getInt(attr, 0); 3881 if (visibility != 0) { 3882 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 3883 viewFlagMasks |= VISIBILITY_MASK; 3884 } 3885 break; 3886 case com.android.internal.R.styleable.View_layoutDirection: 3887 // Clear any layout direction flags (included resolved bits) already set 3888 mPrivateFlags2 &= 3889 ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK); 3890 // Set the layout direction flags depending on the value of the attribute 3891 final int layoutDirection = a.getInt(attr, -1); 3892 final int value = (layoutDirection != -1) ? 3893 LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT; 3894 mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT); 3895 break; 3896 case com.android.internal.R.styleable.View_drawingCacheQuality: 3897 final int cacheQuality = a.getInt(attr, 0); 3898 if (cacheQuality != 0) { 3899 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 3900 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 3901 } 3902 break; 3903 case com.android.internal.R.styleable.View_contentDescription: 3904 setContentDescription(a.getString(attr)); 3905 break; 3906 case com.android.internal.R.styleable.View_labelFor: 3907 setLabelFor(a.getResourceId(attr, NO_ID)); 3908 break; 3909 case com.android.internal.R.styleable.View_soundEffectsEnabled: 3910 if (!a.getBoolean(attr, true)) { 3911 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 3912 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 3913 } 3914 break; 3915 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 3916 if (!a.getBoolean(attr, true)) { 3917 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 3918 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 3919 } 3920 break; 3921 case R.styleable.View_scrollbars: 3922 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 3923 if (scrollbars != SCROLLBARS_NONE) { 3924 viewFlagValues |= scrollbars; 3925 viewFlagMasks |= SCROLLBARS_MASK; 3926 initializeScrollbars = true; 3927 } 3928 break; 3929 //noinspection deprecation 3930 case R.styleable.View_fadingEdge: 3931 if (targetSdkVersion >= ICE_CREAM_SANDWICH) { 3932 // Ignore the attribute starting with ICS 3933 break; 3934 } 3935 // With builds < ICS, fall through and apply fading edges 3936 case R.styleable.View_requiresFadingEdge: 3937 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 3938 if (fadingEdge != FADING_EDGE_NONE) { 3939 viewFlagValues |= fadingEdge; 3940 viewFlagMasks |= FADING_EDGE_MASK; 3941 initializeFadingEdge(a); 3942 } 3943 break; 3944 case R.styleable.View_scrollbarStyle: 3945 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 3946 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3947 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 3948 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 3949 } 3950 break; 3951 case R.styleable.View_isScrollContainer: 3952 setScrollContainer = true; 3953 if (a.getBoolean(attr, false)) { 3954 setScrollContainer(true); 3955 } 3956 break; 3957 case com.android.internal.R.styleable.View_keepScreenOn: 3958 if (a.getBoolean(attr, false)) { 3959 viewFlagValues |= KEEP_SCREEN_ON; 3960 viewFlagMasks |= KEEP_SCREEN_ON; 3961 } 3962 break; 3963 case R.styleable.View_filterTouchesWhenObscured: 3964 if (a.getBoolean(attr, false)) { 3965 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 3966 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 3967 } 3968 break; 3969 case R.styleable.View_nextFocusLeft: 3970 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 3971 break; 3972 case R.styleable.View_nextFocusRight: 3973 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 3974 break; 3975 case R.styleable.View_nextFocusUp: 3976 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 3977 break; 3978 case R.styleable.View_nextFocusDown: 3979 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 3980 break; 3981 case R.styleable.View_nextFocusForward: 3982 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 3983 break; 3984 case R.styleable.View_minWidth: 3985 mMinWidth = a.getDimensionPixelSize(attr, 0); 3986 break; 3987 case R.styleable.View_minHeight: 3988 mMinHeight = a.getDimensionPixelSize(attr, 0); 3989 break; 3990 case R.styleable.View_onClick: 3991 if (context.isRestricted()) { 3992 throw new IllegalStateException("The android:onClick attribute cannot " 3993 + "be used within a restricted context"); 3994 } 3995 3996 final String handlerName = a.getString(attr); 3997 if (handlerName != null) { 3998 setOnClickListener(new OnClickListener() { 3999 private Method mHandler; 4000 4001 public void onClick(View v) { 4002 if (mHandler == null) { 4003 try { 4004 mHandler = getContext().getClass().getMethod(handlerName, 4005 View.class); 4006 } catch (NoSuchMethodException e) { 4007 int id = getId(); 4008 String idText = id == NO_ID ? "" : " with id '" 4009 + getContext().getResources().getResourceEntryName( 4010 id) + "'"; 4011 throw new IllegalStateException("Could not find a method " + 4012 handlerName + "(View) in the activity " 4013 + getContext().getClass() + " for onClick handler" 4014 + " on view " + View.this.getClass() + idText, e); 4015 } 4016 } 4017 4018 try { 4019 mHandler.invoke(getContext(), View.this); 4020 } catch (IllegalAccessException e) { 4021 throw new IllegalStateException("Could not execute non " 4022 + "public method of the activity", e); 4023 } catch (InvocationTargetException e) { 4024 throw new IllegalStateException("Could not execute " 4025 + "method of the activity", e); 4026 } 4027 } 4028 }); 4029 } 4030 break; 4031 case R.styleable.View_overScrollMode: 4032 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 4033 break; 4034 case R.styleable.View_verticalScrollbarPosition: 4035 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 4036 break; 4037 case R.styleable.View_layerType: 4038 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 4039 break; 4040 case R.styleable.View_textDirection: 4041 // Clear any text direction flag already set 4042 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 4043 // Set the text direction flags depending on the value of the attribute 4044 final int textDirection = a.getInt(attr, -1); 4045 if (textDirection != -1) { 4046 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection]; 4047 } 4048 break; 4049 case R.styleable.View_textAlignment: 4050 // Clear any text alignment flag already set 4051 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 4052 // Set the text alignment flag depending on the value of the attribute 4053 final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT); 4054 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment]; 4055 break; 4056 case R.styleable.View_importantForAccessibility: 4057 setImportantForAccessibility(a.getInt(attr, 4058 IMPORTANT_FOR_ACCESSIBILITY_DEFAULT)); 4059 break; 4060 case R.styleable.View_accessibilityLiveRegion: 4061 setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT)); 4062 break; 4063 case R.styleable.View_sharedElementName: 4064 setSharedElementName(a.getString(attr)); 4065 break; 4066 } 4067 } 4068 4069 setOverScrollMode(overScrollMode); 4070 4071 // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet 4072 // the resolved layout direction). Those cached values will be used later during padding 4073 // resolution. 4074 mUserPaddingStart = startPadding; 4075 mUserPaddingEnd = endPadding; 4076 4077 if (background != null) { 4078 setBackground(background); 4079 } 4080 4081 // setBackground above will record that padding is currently provided by the background. 4082 // If we have padding specified via xml, record that here instead and use it. 4083 mLeftPaddingDefined = leftPaddingDefined; 4084 mRightPaddingDefined = rightPaddingDefined; 4085 4086 if (padding >= 0) { 4087 leftPadding = padding; 4088 topPadding = padding; 4089 rightPadding = padding; 4090 bottomPadding = padding; 4091 mUserPaddingLeftInitial = padding; 4092 mUserPaddingRightInitial = padding; 4093 } 4094 4095 if (isRtlCompatibilityMode()) { 4096 // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case. 4097 // left / right padding are used if defined (meaning here nothing to do). If they are not 4098 // defined and start / end padding are defined (e.g. in Frameworks resources), then we use 4099 // start / end and resolve them as left / right (layout direction is not taken into account). 4100 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4101 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4102 // defined. 4103 if (!mLeftPaddingDefined && startPaddingDefined) { 4104 leftPadding = startPadding; 4105 } 4106 mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial; 4107 if (!mRightPaddingDefined && endPaddingDefined) { 4108 rightPadding = endPadding; 4109 } 4110 mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial; 4111 } else { 4112 // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right 4113 // values defined. Otherwise, left /right values are used. 4114 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4115 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4116 // defined. 4117 final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined; 4118 4119 if (mLeftPaddingDefined && !hasRelativePadding) { 4120 mUserPaddingLeftInitial = leftPadding; 4121 } 4122 if (mRightPaddingDefined && !hasRelativePadding) { 4123 mUserPaddingRightInitial = rightPadding; 4124 } 4125 } 4126 4127 internalSetPadding( 4128 mUserPaddingLeftInitial, 4129 topPadding >= 0 ? topPadding : mPaddingTop, 4130 mUserPaddingRightInitial, 4131 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 4132 4133 if (viewFlagMasks != 0) { 4134 setFlags(viewFlagValues, viewFlagMasks); 4135 } 4136 4137 if (initializeScrollbars) { 4138 initializeScrollbars(a); 4139 } 4140 4141 a.recycle(); 4142 4143 // Needs to be called after mViewFlags is set 4144 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 4145 recomputePadding(); 4146 } 4147 4148 if (x != 0 || y != 0) { 4149 scrollTo(x, y); 4150 } 4151 4152 if (transformSet) { 4153 setTranslationX(tx); 4154 setTranslationY(ty); 4155 setTranslationZ(tz); 4156 setRotation(rotation); 4157 setRotationX(rotationX); 4158 setRotationY(rotationY); 4159 setScaleX(sx); 4160 setScaleY(sy); 4161 } 4162 4163 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 4164 setScrollContainer(true); 4165 } 4166 4167 computeOpaqueFlags(); 4168 } 4169 4170 /** 4171 * Non-public constructor for use in testing 4172 */ 4173 View() { 4174 mResources = null; 4175 } 4176 4177 public String toString() { 4178 StringBuilder out = new StringBuilder(128); 4179 out.append(getClass().getName()); 4180 out.append('{'); 4181 out.append(Integer.toHexString(System.identityHashCode(this))); 4182 out.append(' '); 4183 switch (mViewFlags&VISIBILITY_MASK) { 4184 case VISIBLE: out.append('V'); break; 4185 case INVISIBLE: out.append('I'); break; 4186 case GONE: out.append('G'); break; 4187 default: out.append('.'); break; 4188 } 4189 out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.'); 4190 out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.'); 4191 out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D'); 4192 out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.'); 4193 out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.'); 4194 out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.'); 4195 out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.'); 4196 out.append(' '); 4197 out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.'); 4198 out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.'); 4199 out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.'); 4200 if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) { 4201 out.append('p'); 4202 } else { 4203 out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.'); 4204 } 4205 out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.'); 4206 out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.'); 4207 out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.'); 4208 out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.'); 4209 out.append(' '); 4210 out.append(mLeft); 4211 out.append(','); 4212 out.append(mTop); 4213 out.append('-'); 4214 out.append(mRight); 4215 out.append(','); 4216 out.append(mBottom); 4217 final int id = getId(); 4218 if (id != NO_ID) { 4219 out.append(" #"); 4220 out.append(Integer.toHexString(id)); 4221 final Resources r = mResources; 4222 if (Resources.resourceHasPackage(id) && r != null) { 4223 try { 4224 String pkgname; 4225 switch (id&0xff000000) { 4226 case 0x7f000000: 4227 pkgname="app"; 4228 break; 4229 case 0x01000000: 4230 pkgname="android"; 4231 break; 4232 default: 4233 pkgname = r.getResourcePackageName(id); 4234 break; 4235 } 4236 String typename = r.getResourceTypeName(id); 4237 String entryname = r.getResourceEntryName(id); 4238 out.append(" "); 4239 out.append(pkgname); 4240 out.append(":"); 4241 out.append(typename); 4242 out.append("/"); 4243 out.append(entryname); 4244 } catch (Resources.NotFoundException e) { 4245 } 4246 } 4247 } 4248 out.append("}"); 4249 return out.toString(); 4250 } 4251 4252 /** 4253 * <p> 4254 * Initializes the fading edges from a given set of styled attributes. This 4255 * method should be called by subclasses that need fading edges and when an 4256 * instance of these subclasses is created programmatically rather than 4257 * being inflated from XML. This method is automatically called when the XML 4258 * is inflated. 4259 * </p> 4260 * 4261 * @param a the styled attributes set to initialize the fading edges from 4262 */ 4263 protected void initializeFadingEdge(TypedArray a) { 4264 initScrollCache(); 4265 4266 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 4267 R.styleable.View_fadingEdgeLength, 4268 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 4269 } 4270 4271 /** 4272 * Returns the size of the vertical faded edges used to indicate that more 4273 * content in this view is visible. 4274 * 4275 * @return The size in pixels of the vertical faded edge or 0 if vertical 4276 * faded edges are not enabled for this view. 4277 * @attr ref android.R.styleable#View_fadingEdgeLength 4278 */ 4279 public int getVerticalFadingEdgeLength() { 4280 if (isVerticalFadingEdgeEnabled()) { 4281 ScrollabilityCache cache = mScrollCache; 4282 if (cache != null) { 4283 return cache.fadingEdgeLength; 4284 } 4285 } 4286 return 0; 4287 } 4288 4289 /** 4290 * Set the size of the faded edge used to indicate that more content in this 4291 * view is available. Will not change whether the fading edge is enabled; use 4292 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 4293 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 4294 * for the vertical or horizontal fading edges. 4295 * 4296 * @param length The size in pixels of the faded edge used to indicate that more 4297 * content in this view is visible. 4298 */ 4299 public void setFadingEdgeLength(int length) { 4300 initScrollCache(); 4301 mScrollCache.fadingEdgeLength = length; 4302 } 4303 4304 /** 4305 * Returns the size of the horizontal faded edges used to indicate that more 4306 * content in this view is visible. 4307 * 4308 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 4309 * faded edges are not enabled for this view. 4310 * @attr ref android.R.styleable#View_fadingEdgeLength 4311 */ 4312 public int getHorizontalFadingEdgeLength() { 4313 if (isHorizontalFadingEdgeEnabled()) { 4314 ScrollabilityCache cache = mScrollCache; 4315 if (cache != null) { 4316 return cache.fadingEdgeLength; 4317 } 4318 } 4319 return 0; 4320 } 4321 4322 /** 4323 * Returns the width of the vertical scrollbar. 4324 * 4325 * @return The width in pixels of the vertical scrollbar or 0 if there 4326 * is no vertical scrollbar. 4327 */ 4328 public int getVerticalScrollbarWidth() { 4329 ScrollabilityCache cache = mScrollCache; 4330 if (cache != null) { 4331 ScrollBarDrawable scrollBar = cache.scrollBar; 4332 if (scrollBar != null) { 4333 int size = scrollBar.getSize(true); 4334 if (size <= 0) { 4335 size = cache.scrollBarSize; 4336 } 4337 return size; 4338 } 4339 return 0; 4340 } 4341 return 0; 4342 } 4343 4344 /** 4345 * Returns the height of the horizontal scrollbar. 4346 * 4347 * @return The height in pixels of the horizontal scrollbar or 0 if 4348 * there is no horizontal scrollbar. 4349 */ 4350 protected int getHorizontalScrollbarHeight() { 4351 ScrollabilityCache cache = mScrollCache; 4352 if (cache != null) { 4353 ScrollBarDrawable scrollBar = cache.scrollBar; 4354 if (scrollBar != null) { 4355 int size = scrollBar.getSize(false); 4356 if (size <= 0) { 4357 size = cache.scrollBarSize; 4358 } 4359 return size; 4360 } 4361 return 0; 4362 } 4363 return 0; 4364 } 4365 4366 /** 4367 * <p> 4368 * Initializes the scrollbars from a given set of styled attributes. This 4369 * method should be called by subclasses that need scrollbars and when an 4370 * instance of these subclasses is created programmatically rather than 4371 * being inflated from XML. This method is automatically called when the XML 4372 * is inflated. 4373 * </p> 4374 * 4375 * @param a the styled attributes set to initialize the scrollbars from 4376 */ 4377 protected void initializeScrollbars(TypedArray a) { 4378 initScrollCache(); 4379 4380 final ScrollabilityCache scrollabilityCache = mScrollCache; 4381 4382 if (scrollabilityCache.scrollBar == null) { 4383 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 4384 } 4385 4386 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 4387 4388 if (!fadeScrollbars) { 4389 scrollabilityCache.state = ScrollabilityCache.ON; 4390 } 4391 scrollabilityCache.fadeScrollBars = fadeScrollbars; 4392 4393 4394 scrollabilityCache.scrollBarFadeDuration = a.getInt( 4395 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 4396 .getScrollBarFadeDuration()); 4397 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 4398 R.styleable.View_scrollbarDefaultDelayBeforeFade, 4399 ViewConfiguration.getScrollDefaultDelay()); 4400 4401 4402 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 4403 com.android.internal.R.styleable.View_scrollbarSize, 4404 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 4405 4406 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 4407 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 4408 4409 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 4410 if (thumb != null) { 4411 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 4412 } 4413 4414 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 4415 false); 4416 if (alwaysDraw) { 4417 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 4418 } 4419 4420 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 4421 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 4422 4423 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 4424 if (thumb != null) { 4425 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 4426 } 4427 4428 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 4429 false); 4430 if (alwaysDraw) { 4431 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 4432 } 4433 4434 // Apply layout direction to the new Drawables if needed 4435 final int layoutDirection = getLayoutDirection(); 4436 if (track != null) { 4437 track.setLayoutDirection(layoutDirection); 4438 } 4439 if (thumb != null) { 4440 thumb.setLayoutDirection(layoutDirection); 4441 } 4442 4443 // Re-apply user/background padding so that scrollbar(s) get added 4444 resolvePadding(); 4445 } 4446 4447 /** 4448 * <p> 4449 * Initalizes the scrollability cache if necessary. 4450 * </p> 4451 */ 4452 private void initScrollCache() { 4453 if (mScrollCache == null) { 4454 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 4455 } 4456 } 4457 4458 private ScrollabilityCache getScrollCache() { 4459 initScrollCache(); 4460 return mScrollCache; 4461 } 4462 4463 /** 4464 * Set the position of the vertical scroll bar. Should be one of 4465 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 4466 * {@link #SCROLLBAR_POSITION_RIGHT}. 4467 * 4468 * @param position Where the vertical scroll bar should be positioned. 4469 */ 4470 public void setVerticalScrollbarPosition(int position) { 4471 if (mVerticalScrollbarPosition != position) { 4472 mVerticalScrollbarPosition = position; 4473 computeOpaqueFlags(); 4474 resolvePadding(); 4475 } 4476 } 4477 4478 /** 4479 * @return The position where the vertical scroll bar will show, if applicable. 4480 * @see #setVerticalScrollbarPosition(int) 4481 */ 4482 public int getVerticalScrollbarPosition() { 4483 return mVerticalScrollbarPosition; 4484 } 4485 4486 ListenerInfo getListenerInfo() { 4487 if (mListenerInfo != null) { 4488 return mListenerInfo; 4489 } 4490 mListenerInfo = new ListenerInfo(); 4491 return mListenerInfo; 4492 } 4493 4494 /** 4495 * Register a callback to be invoked when focus of this view changed. 4496 * 4497 * @param l The callback that will run. 4498 */ 4499 public void setOnFocusChangeListener(OnFocusChangeListener l) { 4500 getListenerInfo().mOnFocusChangeListener = l; 4501 } 4502 4503 /** 4504 * Add a listener that will be called when the bounds of the view change due to 4505 * layout processing. 4506 * 4507 * @param listener The listener that will be called when layout bounds change. 4508 */ 4509 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 4510 ListenerInfo li = getListenerInfo(); 4511 if (li.mOnLayoutChangeListeners == null) { 4512 li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 4513 } 4514 if (!li.mOnLayoutChangeListeners.contains(listener)) { 4515 li.mOnLayoutChangeListeners.add(listener); 4516 } 4517 } 4518 4519 /** 4520 * Remove a listener for layout changes. 4521 * 4522 * @param listener The listener for layout bounds change. 4523 */ 4524 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 4525 ListenerInfo li = mListenerInfo; 4526 if (li == null || li.mOnLayoutChangeListeners == null) { 4527 return; 4528 } 4529 li.mOnLayoutChangeListeners.remove(listener); 4530 } 4531 4532 /** 4533 * Add a listener for attach state changes. 4534 * 4535 * This listener will be called whenever this view is attached or detached 4536 * from a window. Remove the listener using 4537 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 4538 * 4539 * @param listener Listener to attach 4540 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 4541 */ 4542 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4543 ListenerInfo li = getListenerInfo(); 4544 if (li.mOnAttachStateChangeListeners == null) { 4545 li.mOnAttachStateChangeListeners 4546 = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 4547 } 4548 li.mOnAttachStateChangeListeners.add(listener); 4549 } 4550 4551 /** 4552 * Remove a listener for attach state changes. The listener will receive no further 4553 * notification of window attach/detach events. 4554 * 4555 * @param listener Listener to remove 4556 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 4557 */ 4558 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4559 ListenerInfo li = mListenerInfo; 4560 if (li == null || li.mOnAttachStateChangeListeners == null) { 4561 return; 4562 } 4563 li.mOnAttachStateChangeListeners.remove(listener); 4564 } 4565 4566 /** 4567 * Returns the focus-change callback registered for this view. 4568 * 4569 * @return The callback, or null if one is not registered. 4570 */ 4571 public OnFocusChangeListener getOnFocusChangeListener() { 4572 ListenerInfo li = mListenerInfo; 4573 return li != null ? li.mOnFocusChangeListener : null; 4574 } 4575 4576 /** 4577 * Register a callback to be invoked when this view is clicked. If this view is not 4578 * clickable, it becomes clickable. 4579 * 4580 * @param l The callback that will run 4581 * 4582 * @see #setClickable(boolean) 4583 */ 4584 public void setOnClickListener(OnClickListener l) { 4585 if (!isClickable()) { 4586 setClickable(true); 4587 } 4588 getListenerInfo().mOnClickListener = l; 4589 } 4590 4591 /** 4592 * Return whether this view has an attached OnClickListener. Returns 4593 * true if there is a listener, false if there is none. 4594 */ 4595 public boolean hasOnClickListeners() { 4596 ListenerInfo li = mListenerInfo; 4597 return (li != null && li.mOnClickListener != null); 4598 } 4599 4600 /** 4601 * Register a callback to be invoked when this view is clicked and held. If this view is not 4602 * long clickable, it becomes long clickable. 4603 * 4604 * @param l The callback that will run 4605 * 4606 * @see #setLongClickable(boolean) 4607 */ 4608 public void setOnLongClickListener(OnLongClickListener l) { 4609 if (!isLongClickable()) { 4610 setLongClickable(true); 4611 } 4612 getListenerInfo().mOnLongClickListener = l; 4613 } 4614 4615 /** 4616 * Register a callback to be invoked when the context menu for this view is 4617 * being built. If this view is not long clickable, it becomes long clickable. 4618 * 4619 * @param l The callback that will run 4620 * 4621 */ 4622 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 4623 if (!isLongClickable()) { 4624 setLongClickable(true); 4625 } 4626 getListenerInfo().mOnCreateContextMenuListener = l; 4627 } 4628 4629 /** 4630 * Call this view's OnClickListener, if it is defined. Performs all normal 4631 * actions associated with clicking: reporting accessibility event, playing 4632 * a sound, etc. 4633 * 4634 * @return True there was an assigned OnClickListener that was called, false 4635 * otherwise is returned. 4636 */ 4637 public boolean performClick() { 4638 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 4639 4640 ListenerInfo li = mListenerInfo; 4641 if (li != null && li.mOnClickListener != null) { 4642 playSoundEffect(SoundEffectConstants.CLICK); 4643 li.mOnClickListener.onClick(this); 4644 return true; 4645 } 4646 4647 return false; 4648 } 4649 4650 /** 4651 * Directly call any attached OnClickListener. Unlike {@link #performClick()}, 4652 * this only calls the listener, and does not do any associated clicking 4653 * actions like reporting an accessibility event. 4654 * 4655 * @return True there was an assigned OnClickListener that was called, false 4656 * otherwise is returned. 4657 */ 4658 public boolean callOnClick() { 4659 ListenerInfo li = mListenerInfo; 4660 if (li != null && li.mOnClickListener != null) { 4661 li.mOnClickListener.onClick(this); 4662 return true; 4663 } 4664 return false; 4665 } 4666 4667 /** 4668 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the 4669 * OnLongClickListener did not consume the event. 4670 * 4671 * @return True if one of the above receivers consumed the event, false otherwise. 4672 */ 4673 public boolean performLongClick() { 4674 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 4675 4676 boolean handled = false; 4677 ListenerInfo li = mListenerInfo; 4678 if (li != null && li.mOnLongClickListener != null) { 4679 handled = li.mOnLongClickListener.onLongClick(View.this); 4680 } 4681 if (!handled) { 4682 handled = showContextMenu(); 4683 } 4684 if (handled) { 4685 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 4686 } 4687 return handled; 4688 } 4689 4690 /** 4691 * Performs button-related actions during a touch down event. 4692 * 4693 * @param event The event. 4694 * @return True if the down was consumed. 4695 * 4696 * @hide 4697 */ 4698 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 4699 if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 4700 if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) { 4701 return true; 4702 } 4703 } 4704 return false; 4705 } 4706 4707 /** 4708 * Bring up the context menu for this view. 4709 * 4710 * @return Whether a context menu was displayed. 4711 */ 4712 public boolean showContextMenu() { 4713 return getParent().showContextMenuForChild(this); 4714 } 4715 4716 /** 4717 * Bring up the context menu for this view, referring to the item under the specified point. 4718 * 4719 * @param x The referenced x coordinate. 4720 * @param y The referenced y coordinate. 4721 * @param metaState The keyboard modifiers that were pressed. 4722 * @return Whether a context menu was displayed. 4723 * 4724 * @hide 4725 */ 4726 public boolean showContextMenu(float x, float y, int metaState) { 4727 return showContextMenu(); 4728 } 4729 4730 /** 4731 * Start an action mode. 4732 * 4733 * @param callback Callback that will control the lifecycle of the action mode 4734 * @return The new action mode if it is started, null otherwise 4735 * 4736 * @see ActionMode 4737 */ 4738 public ActionMode startActionMode(ActionMode.Callback callback) { 4739 ViewParent parent = getParent(); 4740 if (parent == null) return null; 4741 return parent.startActionModeForChild(this, callback); 4742 } 4743 4744 /** 4745 * Register a callback to be invoked when a hardware key is pressed in this view. 4746 * Key presses in software input methods will generally not trigger the methods of 4747 * this listener. 4748 * @param l the key listener to attach to this view 4749 */ 4750 public void setOnKeyListener(OnKeyListener l) { 4751 getListenerInfo().mOnKeyListener = l; 4752 } 4753 4754 /** 4755 * Register a callback to be invoked when a touch event is sent to this view. 4756 * @param l the touch listener to attach to this view 4757 */ 4758 public void setOnTouchListener(OnTouchListener l) { 4759 getListenerInfo().mOnTouchListener = l; 4760 } 4761 4762 /** 4763 * Register a callback to be invoked when a generic motion event is sent to this view. 4764 * @param l the generic motion listener to attach to this view 4765 */ 4766 public void setOnGenericMotionListener(OnGenericMotionListener l) { 4767 getListenerInfo().mOnGenericMotionListener = l; 4768 } 4769 4770 /** 4771 * Register a callback to be invoked when a hover event is sent to this view. 4772 * @param l the hover listener to attach to this view 4773 */ 4774 public void setOnHoverListener(OnHoverListener l) { 4775 getListenerInfo().mOnHoverListener = l; 4776 } 4777 4778 /** 4779 * Register a drag event listener callback object for this View. The parameter is 4780 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 4781 * View, the system calls the 4782 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 4783 * @param l An implementation of {@link android.view.View.OnDragListener}. 4784 */ 4785 public void setOnDragListener(OnDragListener l) { 4786 getListenerInfo().mOnDragListener = l; 4787 } 4788 4789 /** 4790 * Give this view focus. This will cause 4791 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 4792 * 4793 * Note: this does not check whether this {@link View} should get focus, it just 4794 * gives it focus no matter what. It should only be called internally by framework 4795 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 4796 * 4797 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 4798 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 4799 * focus moved when requestFocus() is called. It may not always 4800 * apply, in which case use the default View.FOCUS_DOWN. 4801 * @param previouslyFocusedRect The rectangle of the view that had focus 4802 * prior in this View's coordinate system. 4803 */ 4804 void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) { 4805 if (DBG) { 4806 System.out.println(this + " requestFocus()"); 4807 } 4808 4809 if ((mPrivateFlags & PFLAG_FOCUSED) == 0) { 4810 mPrivateFlags |= PFLAG_FOCUSED; 4811 4812 View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null; 4813 4814 if (mParent != null) { 4815 mParent.requestChildFocus(this, this); 4816 } 4817 4818 if (mAttachInfo != null) { 4819 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this); 4820 } 4821 4822 manageFocusHotspot(true, oldFocus); 4823 onFocusChanged(true, direction, previouslyFocusedRect); 4824 refreshDrawableState(); 4825 } 4826 } 4827 4828 /** 4829 * Forwards focus information to the background drawable, if necessary. When 4830 * the view is gaining focus, <code>v</code> is the previous focus holder. 4831 * When the view is losing focus, <code>v</code> is the next focus holder. 4832 * 4833 * @param focused whether this view is focused 4834 * @param v previous or the next focus holder, or null if none 4835 */ 4836 private void manageFocusHotspot(boolean focused, View v) { 4837 if (mBackground != null && mBackground.supportsHotspots()) { 4838 final Rect r = new Rect(); 4839 if (v != null) { 4840 v.getBoundsOnScreen(r); 4841 final int[] location = new int[2]; 4842 getLocationOnScreen(location); 4843 r.offset(-location[0], -location[1]); 4844 } else { 4845 r.set(mLeft, mTop, mRight, mBottom); 4846 } 4847 4848 final float x = r.exactCenterX(); 4849 final float y = r.exactCenterY(); 4850 mBackground.setHotspot(Drawable.HOTSPOT_FOCUS, x, y); 4851 4852 if (!focused) { 4853 mBackground.removeHotspot(Drawable.HOTSPOT_FOCUS); 4854 } 4855 } 4856 } 4857 4858 /** 4859 * Request that a rectangle of this view be visible on the screen, 4860 * scrolling if necessary just enough. 4861 * 4862 * <p>A View should call this if it maintains some notion of which part 4863 * of its content is interesting. For example, a text editing view 4864 * should call this when its cursor moves. 4865 * 4866 * @param rectangle The rectangle. 4867 * @return Whether any parent scrolled. 4868 */ 4869 public boolean requestRectangleOnScreen(Rect rectangle) { 4870 return requestRectangleOnScreen(rectangle, false); 4871 } 4872 4873 /** 4874 * Request that a rectangle of this view be visible on the screen, 4875 * scrolling if necessary just enough. 4876 * 4877 * <p>A View should call this if it maintains some notion of which part 4878 * of its content is interesting. For example, a text editing view 4879 * should call this when its cursor moves. 4880 * 4881 * <p>When <code>immediate</code> is set to true, scrolling will not be 4882 * animated. 4883 * 4884 * @param rectangle The rectangle. 4885 * @param immediate True to forbid animated scrolling, false otherwise 4886 * @return Whether any parent scrolled. 4887 */ 4888 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 4889 if (mParent == null) { 4890 return false; 4891 } 4892 4893 View child = this; 4894 4895 RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF(); 4896 position.set(rectangle); 4897 4898 ViewParent parent = mParent; 4899 boolean scrolled = false; 4900 while (parent != null) { 4901 rectangle.set((int) position.left, (int) position.top, 4902 (int) position.right, (int) position.bottom); 4903 4904 scrolled |= parent.requestChildRectangleOnScreen(child, 4905 rectangle, immediate); 4906 4907 if (!child.hasIdentityMatrix()) { 4908 child.getMatrix().mapRect(position); 4909 } 4910 4911 position.offset(child.mLeft, child.mTop); 4912 4913 if (!(parent instanceof View)) { 4914 break; 4915 } 4916 4917 View parentView = (View) parent; 4918 4919 position.offset(-parentView.getScrollX(), -parentView.getScrollY()); 4920 4921 child = parentView; 4922 parent = child.getParent(); 4923 } 4924 4925 return scrolled; 4926 } 4927 4928 /** 4929 * Called when this view wants to give up focus. If focus is cleared 4930 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called. 4931 * <p> 4932 * <strong>Note:</strong> When a View clears focus the framework is trying 4933 * to give focus to the first focusable View from the top. Hence, if this 4934 * View is the first from the top that can take focus, then all callbacks 4935 * related to clearing focus will be invoked after wich the framework will 4936 * give focus to this view. 4937 * </p> 4938 */ 4939 public void clearFocus() { 4940 if (DBG) { 4941 System.out.println(this + " clearFocus()"); 4942 } 4943 4944 clearFocusInternal(null, true, true); 4945 } 4946 4947 /** 4948 * Clears focus from the view, optionally propagating the change up through 4949 * the parent hierarchy and requesting that the root view place new focus. 4950 * 4951 * @param propagate whether to propagate the change up through the parent 4952 * hierarchy 4953 * @param refocus when propagate is true, specifies whether to request the 4954 * root view place new focus 4955 */ 4956 void clearFocusInternal(View focused, boolean propagate, boolean refocus) { 4957 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 4958 mPrivateFlags &= ~PFLAG_FOCUSED; 4959 4960 if (hasFocus()) { 4961 manageFocusHotspot(false, focused); 4962 } 4963 4964 if (propagate && mParent != null) { 4965 mParent.clearChildFocus(this); 4966 } 4967 4968 onFocusChanged(false, 0, null); 4969 4970 refreshDrawableState(); 4971 4972 if (propagate && (!refocus || !rootViewRequestFocus())) { 4973 notifyGlobalFocusCleared(this); 4974 } 4975 } 4976 } 4977 4978 void notifyGlobalFocusCleared(View oldFocus) { 4979 if (oldFocus != null && mAttachInfo != null) { 4980 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null); 4981 } 4982 } 4983 4984 boolean rootViewRequestFocus() { 4985 final View root = getRootView(); 4986 return root != null && root.requestFocus(); 4987 } 4988 4989 /** 4990 * Called internally by the view system when a new view is getting focus. 4991 * This is what clears the old focus. 4992 * <p> 4993 * <b>NOTE:</b> The parent view's focused child must be updated manually 4994 * after calling this method. Otherwise, the view hierarchy may be left in 4995 * an inconstent state. 4996 */ 4997 void unFocus(View focused) { 4998 if (DBG) { 4999 System.out.println(this + " unFocus()"); 5000 } 5001 5002 clearFocusInternal(focused, false, false); 5003 } 5004 5005 /** 5006 * Returns true if this view has focus iteself, or is the ancestor of the 5007 * view that has focus. 5008 * 5009 * @return True if this view has or contains focus, false otherwise. 5010 */ 5011 @ViewDebug.ExportedProperty(category = "focus") 5012 public boolean hasFocus() { 5013 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 5014 } 5015 5016 /** 5017 * Returns true if this view is focusable or if it contains a reachable View 5018 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 5019 * is a View whose parents do not block descendants focus. 5020 * 5021 * Only {@link #VISIBLE} views are considered focusable. 5022 * 5023 * @return True if the view is focusable or if the view contains a focusable 5024 * View, false otherwise. 5025 * 5026 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 5027 */ 5028 public boolean hasFocusable() { 5029 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 5030 } 5031 5032 /** 5033 * Called by the view system when the focus state of this view changes. 5034 * When the focus change event is caused by directional navigation, direction 5035 * and previouslyFocusedRect provide insight into where the focus is coming from. 5036 * When overriding, be sure to call up through to the super class so that 5037 * the standard focus handling will occur. 5038 * 5039 * @param gainFocus True if the View has focus; false otherwise. 5040 * @param direction The direction focus has moved when requestFocus() 5041 * is called to give this view focus. Values are 5042 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 5043 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 5044 * It may not always apply, in which case use the default. 5045 * @param previouslyFocusedRect The rectangle, in this view's coordinate 5046 * system, of the previously focused view. If applicable, this will be 5047 * passed in as finer grained information about where the focus is coming 5048 * from (in addition to direction). Will be <code>null</code> otherwise. 5049 */ 5050 protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction, 5051 @Nullable Rect previouslyFocusedRect) { 5052 if (gainFocus) { 5053 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 5054 } else { 5055 notifyViewAccessibilityStateChangedIfNeeded( 5056 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 5057 } 5058 5059 InputMethodManager imm = InputMethodManager.peekInstance(); 5060 if (!gainFocus) { 5061 if (isPressed()) { 5062 setPressed(false); 5063 } 5064 if (imm != null && mAttachInfo != null 5065 && mAttachInfo.mHasWindowFocus) { 5066 imm.focusOut(this); 5067 } 5068 onFocusLost(); 5069 } else if (imm != null && mAttachInfo != null 5070 && mAttachInfo.mHasWindowFocus) { 5071 imm.focusIn(this); 5072 } 5073 5074 invalidate(true); 5075 ListenerInfo li = mListenerInfo; 5076 if (li != null && li.mOnFocusChangeListener != null) { 5077 li.mOnFocusChangeListener.onFocusChange(this, gainFocus); 5078 } 5079 5080 if (mAttachInfo != null) { 5081 mAttachInfo.mKeyDispatchState.reset(this); 5082 } 5083 } 5084 5085 /** 5086 * Sends an accessibility event of the given type. If accessibility is 5087 * not enabled this method has no effect. The default implementation calls 5088 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 5089 * to populate information about the event source (this View), then calls 5090 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 5091 * populate the text content of the event source including its descendants, 5092 * and last calls 5093 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 5094 * on its parent to resuest sending of the event to interested parties. 5095 * <p> 5096 * If an {@link AccessibilityDelegate} has been specified via calling 5097 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5098 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 5099 * responsible for handling this call. 5100 * </p> 5101 * 5102 * @param eventType The type of the event to send, as defined by several types from 5103 * {@link android.view.accessibility.AccessibilityEvent}, such as 5104 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or 5105 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}. 5106 * 5107 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 5108 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5109 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 5110 * @see AccessibilityDelegate 5111 */ 5112 public void sendAccessibilityEvent(int eventType) { 5113 if (mAccessibilityDelegate != null) { 5114 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 5115 } else { 5116 sendAccessibilityEventInternal(eventType); 5117 } 5118 } 5119 5120 /** 5121 * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT} 5122 * {@link AccessibilityEvent} to make an announcement which is related to some 5123 * sort of a context change for which none of the events representing UI transitions 5124 * is a good fit. For example, announcing a new page in a book. If accessibility 5125 * is not enabled this method does nothing. 5126 * 5127 * @param text The announcement text. 5128 */ 5129 public void announceForAccessibility(CharSequence text) { 5130 if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) { 5131 AccessibilityEvent event = AccessibilityEvent.obtain( 5132 AccessibilityEvent.TYPE_ANNOUNCEMENT); 5133 onInitializeAccessibilityEvent(event); 5134 event.getText().add(text); 5135 event.setContentDescription(null); 5136 mParent.requestSendAccessibilityEvent(this, event); 5137 } 5138 } 5139 5140 /** 5141 * @see #sendAccessibilityEvent(int) 5142 * 5143 * Note: Called from the default {@link AccessibilityDelegate}. 5144 */ 5145 void sendAccessibilityEventInternal(int eventType) { 5146 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 5147 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 5148 } 5149 } 5150 5151 /** 5152 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 5153 * takes as an argument an empty {@link AccessibilityEvent} and does not 5154 * perform a check whether accessibility is enabled. 5155 * <p> 5156 * If an {@link AccessibilityDelegate} has been specified via calling 5157 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5158 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 5159 * is responsible for handling this call. 5160 * </p> 5161 * 5162 * @param event The event to send. 5163 * 5164 * @see #sendAccessibilityEvent(int) 5165 */ 5166 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 5167 if (mAccessibilityDelegate != null) { 5168 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 5169 } else { 5170 sendAccessibilityEventUncheckedInternal(event); 5171 } 5172 } 5173 5174 /** 5175 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 5176 * 5177 * Note: Called from the default {@link AccessibilityDelegate}. 5178 */ 5179 void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 5180 if (!isShown()) { 5181 return; 5182 } 5183 onInitializeAccessibilityEvent(event); 5184 // Only a subset of accessibility events populates text content. 5185 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) { 5186 dispatchPopulateAccessibilityEvent(event); 5187 } 5188 // In the beginning we called #isShown(), so we know that getParent() is not null. 5189 getParent().requestSendAccessibilityEvent(this, event); 5190 } 5191 5192 /** 5193 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 5194 * to its children for adding their text content to the event. Note that the 5195 * event text is populated in a separate dispatch path since we add to the 5196 * event not only the text of the source but also the text of all its descendants. 5197 * A typical implementation will call 5198 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 5199 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 5200 * on each child. Override this method if custom population of the event text 5201 * content is required. 5202 * <p> 5203 * If an {@link AccessibilityDelegate} has been specified via calling 5204 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5205 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 5206 * is responsible for handling this call. 5207 * </p> 5208 * <p> 5209 * <em>Note:</em> Accessibility events of certain types are not dispatched for 5210 * populating the event text via this method. For details refer to {@link AccessibilityEvent}. 5211 * </p> 5212 * 5213 * @param event The event. 5214 * 5215 * @return True if the event population was completed. 5216 */ 5217 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 5218 if (mAccessibilityDelegate != null) { 5219 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 5220 } else { 5221 return dispatchPopulateAccessibilityEventInternal(event); 5222 } 5223 } 5224 5225 /** 5226 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5227 * 5228 * Note: Called from the default {@link AccessibilityDelegate}. 5229 */ 5230 boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5231 onPopulateAccessibilityEvent(event); 5232 return false; 5233 } 5234 5235 /** 5236 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 5237 * giving a chance to this View to populate the accessibility event with its 5238 * text content. While this method is free to modify event 5239 * attributes other than text content, doing so should normally be performed in 5240 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 5241 * <p> 5242 * Example: Adding formatted date string to an accessibility event in addition 5243 * to the text added by the super implementation: 5244 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5245 * super.onPopulateAccessibilityEvent(event); 5246 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 5247 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 5248 * mCurrentDate.getTimeInMillis(), flags); 5249 * event.getText().add(selectedDateUtterance); 5250 * }</pre> 5251 * <p> 5252 * If an {@link AccessibilityDelegate} has been specified via calling 5253 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5254 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 5255 * is responsible for handling this call. 5256 * </p> 5257 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5258 * information to the event, in case the default implementation has basic information to add. 5259 * </p> 5260 * 5261 * @param event The accessibility event which to populate. 5262 * 5263 * @see #sendAccessibilityEvent(int) 5264 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5265 */ 5266 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5267 if (mAccessibilityDelegate != null) { 5268 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 5269 } else { 5270 onPopulateAccessibilityEventInternal(event); 5271 } 5272 } 5273 5274 /** 5275 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 5276 * 5277 * Note: Called from the default {@link AccessibilityDelegate}. 5278 */ 5279 void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5280 } 5281 5282 /** 5283 * Initializes an {@link AccessibilityEvent} with information about 5284 * this View which is the event source. In other words, the source of 5285 * an accessibility event is the view whose state change triggered firing 5286 * the event. 5287 * <p> 5288 * Example: Setting the password property of an event in addition 5289 * to properties set by the super implementation: 5290 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5291 * super.onInitializeAccessibilityEvent(event); 5292 * event.setPassword(true); 5293 * }</pre> 5294 * <p> 5295 * If an {@link AccessibilityDelegate} has been specified via calling 5296 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5297 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 5298 * is responsible for handling this call. 5299 * </p> 5300 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5301 * information to the event, in case the default implementation has basic information to add. 5302 * </p> 5303 * @param event The event to initialize. 5304 * 5305 * @see #sendAccessibilityEvent(int) 5306 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5307 */ 5308 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5309 if (mAccessibilityDelegate != null) { 5310 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 5311 } else { 5312 onInitializeAccessibilityEventInternal(event); 5313 } 5314 } 5315 5316 /** 5317 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 5318 * 5319 * Note: Called from the default {@link AccessibilityDelegate}. 5320 */ 5321 void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 5322 event.setSource(this); 5323 event.setClassName(View.class.getName()); 5324 event.setPackageName(getContext().getPackageName()); 5325 event.setEnabled(isEnabled()); 5326 event.setContentDescription(mContentDescription); 5327 5328 switch (event.getEventType()) { 5329 case AccessibilityEvent.TYPE_VIEW_FOCUSED: { 5330 ArrayList<View> focusablesTempList = (mAttachInfo != null) 5331 ? mAttachInfo.mTempArrayList : new ArrayList<View>(); 5332 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL); 5333 event.setItemCount(focusablesTempList.size()); 5334 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 5335 if (mAttachInfo != null) { 5336 focusablesTempList.clear(); 5337 } 5338 } break; 5339 case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: { 5340 CharSequence text = getIterableTextForAccessibility(); 5341 if (text != null && text.length() > 0) { 5342 event.setFromIndex(getAccessibilitySelectionStart()); 5343 event.setToIndex(getAccessibilitySelectionEnd()); 5344 event.setItemCount(text.length()); 5345 } 5346 } break; 5347 } 5348 } 5349 5350 /** 5351 * Returns an {@link AccessibilityNodeInfo} representing this view from the 5352 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 5353 * This method is responsible for obtaining an accessibility node info from a 5354 * pool of reusable instances and calling 5355 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 5356 * initialize the former. 5357 * <p> 5358 * Note: The client is responsible for recycling the obtained instance by calling 5359 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 5360 * </p> 5361 * 5362 * @return A populated {@link AccessibilityNodeInfo}. 5363 * 5364 * @see AccessibilityNodeInfo 5365 */ 5366 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 5367 if (mAccessibilityDelegate != null) { 5368 return mAccessibilityDelegate.createAccessibilityNodeInfo(this); 5369 } else { 5370 return createAccessibilityNodeInfoInternal(); 5371 } 5372 } 5373 5374 /** 5375 * @see #createAccessibilityNodeInfo() 5376 */ 5377 AccessibilityNodeInfo createAccessibilityNodeInfoInternal() { 5378 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 5379 if (provider != null) { 5380 return provider.createAccessibilityNodeInfo(View.NO_ID); 5381 } else { 5382 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 5383 onInitializeAccessibilityNodeInfo(info); 5384 return info; 5385 } 5386 } 5387 5388 /** 5389 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 5390 * The base implementation sets: 5391 * <ul> 5392 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 5393 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 5394 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 5395 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 5396 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 5397 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 5398 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 5399 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 5400 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 5401 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 5402 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 5403 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 5404 * </ul> 5405 * <p> 5406 * Subclasses should override this method, call the super implementation, 5407 * and set additional attributes. 5408 * </p> 5409 * <p> 5410 * If an {@link AccessibilityDelegate} has been specified via calling 5411 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5412 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 5413 * is responsible for handling this call. 5414 * </p> 5415 * 5416 * @param info The instance to initialize. 5417 */ 5418 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 5419 if (mAccessibilityDelegate != null) { 5420 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 5421 } else { 5422 onInitializeAccessibilityNodeInfoInternal(info); 5423 } 5424 } 5425 5426 /** 5427 * Gets the location of this view in screen coordintates. 5428 * 5429 * @param outRect The output location 5430 */ 5431 void getBoundsOnScreen(Rect outRect) { 5432 if (mAttachInfo == null) { 5433 return; 5434 } 5435 5436 RectF position = mAttachInfo.mTmpTransformRect; 5437 position.set(0, 0, mRight - mLeft, mBottom - mTop); 5438 5439 if (!hasIdentityMatrix()) { 5440 getMatrix().mapRect(position); 5441 } 5442 5443 position.offset(mLeft, mTop); 5444 5445 ViewParent parent = mParent; 5446 while (parent instanceof View) { 5447 View parentView = (View) parent; 5448 5449 position.offset(-parentView.mScrollX, -parentView.mScrollY); 5450 5451 if (!parentView.hasIdentityMatrix()) { 5452 parentView.getMatrix().mapRect(position); 5453 } 5454 5455 position.offset(parentView.mLeft, parentView.mTop); 5456 5457 parent = parentView.mParent; 5458 } 5459 5460 if (parent instanceof ViewRootImpl) { 5461 ViewRootImpl viewRootImpl = (ViewRootImpl) parent; 5462 position.offset(0, -viewRootImpl.mCurScrollY); 5463 } 5464 5465 position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 5466 5467 outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f), 5468 (int) (position.right + 0.5f), (int) (position.bottom + 0.5f)); 5469 } 5470 5471 /** 5472 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 5473 * 5474 * Note: Called from the default {@link AccessibilityDelegate}. 5475 */ 5476 void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 5477 Rect bounds = mAttachInfo.mTmpInvalRect; 5478 5479 getDrawingRect(bounds); 5480 info.setBoundsInParent(bounds); 5481 5482 getBoundsOnScreen(bounds); 5483 info.setBoundsInScreen(bounds); 5484 5485 ViewParent parent = getParentForAccessibility(); 5486 if (parent instanceof View) { 5487 info.setParent((View) parent); 5488 } 5489 5490 if (mID != View.NO_ID) { 5491 View rootView = getRootView(); 5492 if (rootView == null) { 5493 rootView = this; 5494 } 5495 View label = rootView.findLabelForView(this, mID); 5496 if (label != null) { 5497 info.setLabeledBy(label); 5498 } 5499 5500 if ((mAttachInfo.mAccessibilityFetchFlags 5501 & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0 5502 && Resources.resourceHasPackage(mID)) { 5503 try { 5504 String viewId = getResources().getResourceName(mID); 5505 info.setViewIdResourceName(viewId); 5506 } catch (Resources.NotFoundException nfe) { 5507 /* ignore */ 5508 } 5509 } 5510 } 5511 5512 if (mLabelForId != View.NO_ID) { 5513 View rootView = getRootView(); 5514 if (rootView == null) { 5515 rootView = this; 5516 } 5517 View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId); 5518 if (labeled != null) { 5519 info.setLabelFor(labeled); 5520 } 5521 } 5522 5523 info.setVisibleToUser(isVisibleToUser()); 5524 5525 info.setPackageName(mContext.getPackageName()); 5526 info.setClassName(View.class.getName()); 5527 info.setContentDescription(getContentDescription()); 5528 5529 info.setEnabled(isEnabled()); 5530 info.setClickable(isClickable()); 5531 info.setFocusable(isFocusable()); 5532 info.setFocused(isFocused()); 5533 info.setAccessibilityFocused(isAccessibilityFocused()); 5534 info.setSelected(isSelected()); 5535 info.setLongClickable(isLongClickable()); 5536 info.setLiveRegion(getAccessibilityLiveRegion()); 5537 5538 // TODO: These make sense only if we are in an AdapterView but all 5539 // views can be selected. Maybe from accessibility perspective 5540 // we should report as selectable view in an AdapterView. 5541 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 5542 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 5543 5544 if (isFocusable()) { 5545 if (isFocused()) { 5546 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 5547 } else { 5548 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 5549 } 5550 } 5551 5552 if (!isAccessibilityFocused()) { 5553 info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); 5554 } else { 5555 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); 5556 } 5557 5558 if (isClickable() && isEnabled()) { 5559 info.addAction(AccessibilityNodeInfo.ACTION_CLICK); 5560 } 5561 5562 if (isLongClickable() && isEnabled()) { 5563 info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); 5564 } 5565 5566 CharSequence text = getIterableTextForAccessibility(); 5567 if (text != null && text.length() > 0) { 5568 info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd()); 5569 5570 info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION); 5571 info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); 5572 info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); 5573 info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER 5574 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD 5575 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH); 5576 } 5577 } 5578 5579 private View findLabelForView(View view, int labeledId) { 5580 if (mMatchLabelForPredicate == null) { 5581 mMatchLabelForPredicate = new MatchLabelForPredicate(); 5582 } 5583 mMatchLabelForPredicate.mLabeledId = labeledId; 5584 return findViewByPredicateInsideOut(view, mMatchLabelForPredicate); 5585 } 5586 5587 /** 5588 * Computes whether this view is visible to the user. Such a view is 5589 * attached, visible, all its predecessors are visible, it is not clipped 5590 * entirely by its predecessors, and has an alpha greater than zero. 5591 * 5592 * @return Whether the view is visible on the screen. 5593 * 5594 * @hide 5595 */ 5596 protected boolean isVisibleToUser() { 5597 return isVisibleToUser(null); 5598 } 5599 5600 /** 5601 * Computes whether the given portion of this view is visible to the user. 5602 * Such a view is attached, visible, all its predecessors are visible, 5603 * has an alpha greater than zero, and the specified portion is not 5604 * clipped entirely by its predecessors. 5605 * 5606 * @param boundInView the portion of the view to test; coordinates should be relative; may be 5607 * <code>null</code>, and the entire view will be tested in this case. 5608 * When <code>true</code> is returned by the function, the actual visible 5609 * region will be stored in this parameter; that is, if boundInView is fully 5610 * contained within the view, no modification will be made, otherwise regions 5611 * outside of the visible area of the view will be clipped. 5612 * 5613 * @return Whether the specified portion of the view is visible on the screen. 5614 * 5615 * @hide 5616 */ 5617 protected boolean isVisibleToUser(Rect boundInView) { 5618 if (mAttachInfo != null) { 5619 // Attached to invisible window means this view is not visible. 5620 if (mAttachInfo.mWindowVisibility != View.VISIBLE) { 5621 return false; 5622 } 5623 // An invisible predecessor or one with alpha zero means 5624 // that this view is not visible to the user. 5625 Object current = this; 5626 while (current instanceof View) { 5627 View view = (View) current; 5628 // We have attach info so this view is attached and there is no 5629 // need to check whether we reach to ViewRootImpl on the way up. 5630 if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 || 5631 view.getVisibility() != VISIBLE) { 5632 return false; 5633 } 5634 current = view.mParent; 5635 } 5636 // Check if the view is entirely covered by its predecessors. 5637 Rect visibleRect = mAttachInfo.mTmpInvalRect; 5638 Point offset = mAttachInfo.mPoint; 5639 if (!getGlobalVisibleRect(visibleRect, offset)) { 5640 return false; 5641 } 5642 // Check if the visible portion intersects the rectangle of interest. 5643 if (boundInView != null) { 5644 visibleRect.offset(-offset.x, -offset.y); 5645 return boundInView.intersect(visibleRect); 5646 } 5647 return true; 5648 } 5649 return false; 5650 } 5651 5652 /** 5653 * Returns the delegate for implementing accessibility support via 5654 * composition. For more details see {@link AccessibilityDelegate}. 5655 * 5656 * @return The delegate, or null if none set. 5657 * 5658 * @hide 5659 */ 5660 public AccessibilityDelegate getAccessibilityDelegate() { 5661 return mAccessibilityDelegate; 5662 } 5663 5664 /** 5665 * Sets a delegate for implementing accessibility support via composition as 5666 * opposed to inheritance. The delegate's primary use is for implementing 5667 * backwards compatible widgets. For more details see {@link AccessibilityDelegate}. 5668 * 5669 * @param delegate The delegate instance. 5670 * 5671 * @see AccessibilityDelegate 5672 */ 5673 public void setAccessibilityDelegate(AccessibilityDelegate delegate) { 5674 mAccessibilityDelegate = delegate; 5675 } 5676 5677 /** 5678 * Gets the provider for managing a virtual view hierarchy rooted at this View 5679 * and reported to {@link android.accessibilityservice.AccessibilityService}s 5680 * that explore the window content. 5681 * <p> 5682 * If this method returns an instance, this instance is responsible for managing 5683 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this 5684 * View including the one representing the View itself. Similarly the returned 5685 * instance is responsible for performing accessibility actions on any virtual 5686 * view or the root view itself. 5687 * </p> 5688 * <p> 5689 * If an {@link AccessibilityDelegate} has been specified via calling 5690 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5691 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)} 5692 * is responsible for handling this call. 5693 * </p> 5694 * 5695 * @return The provider. 5696 * 5697 * @see AccessibilityNodeProvider 5698 */ 5699 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 5700 if (mAccessibilityDelegate != null) { 5701 return mAccessibilityDelegate.getAccessibilityNodeProvider(this); 5702 } else { 5703 return null; 5704 } 5705 } 5706 5707 /** 5708 * Gets the unique identifier of this view on the screen for accessibility purposes. 5709 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 5710 * 5711 * @return The view accessibility id. 5712 * 5713 * @hide 5714 */ 5715 public int getAccessibilityViewId() { 5716 if (mAccessibilityViewId == NO_ID) { 5717 mAccessibilityViewId = sNextAccessibilityViewId++; 5718 } 5719 return mAccessibilityViewId; 5720 } 5721 5722 /** 5723 * Gets the unique identifier of the window in which this View reseides. 5724 * 5725 * @return The window accessibility id. 5726 * 5727 * @hide 5728 */ 5729 public int getAccessibilityWindowId() { 5730 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId 5731 : AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 5732 } 5733 5734 /** 5735 * Gets the {@link View} description. It briefly describes the view and is 5736 * primarily used for accessibility support. Set this property to enable 5737 * better accessibility support for your application. This is especially 5738 * true for views that do not have textual representation (For example, 5739 * ImageButton). 5740 * 5741 * @return The content description. 5742 * 5743 * @attr ref android.R.styleable#View_contentDescription 5744 */ 5745 @ViewDebug.ExportedProperty(category = "accessibility") 5746 public CharSequence getContentDescription() { 5747 return mContentDescription; 5748 } 5749 5750 /** 5751 * Sets the {@link View} description. It briefly describes the view and is 5752 * primarily used for accessibility support. Set this property to enable 5753 * better accessibility support for your application. This is especially 5754 * true for views that do not have textual representation (For example, 5755 * ImageButton). 5756 * 5757 * @param contentDescription The content description. 5758 * 5759 * @attr ref android.R.styleable#View_contentDescription 5760 */ 5761 @RemotableViewMethod 5762 public void setContentDescription(CharSequence contentDescription) { 5763 if (mContentDescription == null) { 5764 if (contentDescription == null) { 5765 return; 5766 } 5767 } else if (mContentDescription.equals(contentDescription)) { 5768 return; 5769 } 5770 mContentDescription = contentDescription; 5771 final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0; 5772 if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 5773 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); 5774 notifySubtreeAccessibilityStateChangedIfNeeded(); 5775 } else { 5776 notifyViewAccessibilityStateChangedIfNeeded( 5777 AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION); 5778 } 5779 } 5780 5781 /** 5782 * Gets the id of a view for which this view serves as a label for 5783 * accessibility purposes. 5784 * 5785 * @return The labeled view id. 5786 */ 5787 @ViewDebug.ExportedProperty(category = "accessibility") 5788 public int getLabelFor() { 5789 return mLabelForId; 5790 } 5791 5792 /** 5793 * Sets the id of a view for which this view serves as a label for 5794 * accessibility purposes. 5795 * 5796 * @param id The labeled view id. 5797 */ 5798 @RemotableViewMethod 5799 public void setLabelFor(int id) { 5800 mLabelForId = id; 5801 if (mLabelForId != View.NO_ID 5802 && mID == View.NO_ID) { 5803 mID = generateViewId(); 5804 } 5805 } 5806 5807 /** 5808 * Invoked whenever this view loses focus, either by losing window focus or by losing 5809 * focus within its window. This method can be used to clear any state tied to the 5810 * focus. For instance, if a button is held pressed with the trackball and the window 5811 * loses focus, this method can be used to cancel the press. 5812 * 5813 * Subclasses of View overriding this method should always call super.onFocusLost(). 5814 * 5815 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 5816 * @see #onWindowFocusChanged(boolean) 5817 * 5818 * @hide pending API council approval 5819 */ 5820 protected void onFocusLost() { 5821 resetPressedState(); 5822 } 5823 5824 private void resetPressedState() { 5825 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 5826 return; 5827 } 5828 5829 if (isPressed()) { 5830 setPressed(false); 5831 5832 if (!mHasPerformedLongPress) { 5833 removeLongPressCallback(); 5834 } 5835 } 5836 } 5837 5838 /** 5839 * Returns true if this view has focus 5840 * 5841 * @return True if this view has focus, false otherwise. 5842 */ 5843 @ViewDebug.ExportedProperty(category = "focus") 5844 public boolean isFocused() { 5845 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 5846 } 5847 5848 /** 5849 * Find the view in the hierarchy rooted at this view that currently has 5850 * focus. 5851 * 5852 * @return The view that currently has focus, or null if no focused view can 5853 * be found. 5854 */ 5855 public View findFocus() { 5856 return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null; 5857 } 5858 5859 /** 5860 * Indicates whether this view is one of the set of scrollable containers in 5861 * its window. 5862 * 5863 * @return whether this view is one of the set of scrollable containers in 5864 * its window 5865 * 5866 * @attr ref android.R.styleable#View_isScrollContainer 5867 */ 5868 public boolean isScrollContainer() { 5869 return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0; 5870 } 5871 5872 /** 5873 * Change whether this view is one of the set of scrollable containers in 5874 * its window. This will be used to determine whether the window can 5875 * resize or must pan when a soft input area is open -- scrollable 5876 * containers allow the window to use resize mode since the container 5877 * will appropriately shrink. 5878 * 5879 * @attr ref android.R.styleable#View_isScrollContainer 5880 */ 5881 public void setScrollContainer(boolean isScrollContainer) { 5882 if (isScrollContainer) { 5883 if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) { 5884 mAttachInfo.mScrollContainers.add(this); 5885 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 5886 } 5887 mPrivateFlags |= PFLAG_SCROLL_CONTAINER; 5888 } else { 5889 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 5890 mAttachInfo.mScrollContainers.remove(this); 5891 } 5892 mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED); 5893 } 5894 } 5895 5896 /** 5897 * Returns the quality of the drawing cache. 5898 * 5899 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5900 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5901 * 5902 * @see #setDrawingCacheQuality(int) 5903 * @see #setDrawingCacheEnabled(boolean) 5904 * @see #isDrawingCacheEnabled() 5905 * 5906 * @attr ref android.R.styleable#View_drawingCacheQuality 5907 */ 5908 @DrawingCacheQuality 5909 public int getDrawingCacheQuality() { 5910 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 5911 } 5912 5913 /** 5914 * Set the drawing cache quality of this view. This value is used only when the 5915 * drawing cache is enabled 5916 * 5917 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5918 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5919 * 5920 * @see #getDrawingCacheQuality() 5921 * @see #setDrawingCacheEnabled(boolean) 5922 * @see #isDrawingCacheEnabled() 5923 * 5924 * @attr ref android.R.styleable#View_drawingCacheQuality 5925 */ 5926 public void setDrawingCacheQuality(@DrawingCacheQuality int quality) { 5927 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 5928 } 5929 5930 /** 5931 * Returns whether the screen should remain on, corresponding to the current 5932 * value of {@link #KEEP_SCREEN_ON}. 5933 * 5934 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 5935 * 5936 * @see #setKeepScreenOn(boolean) 5937 * 5938 * @attr ref android.R.styleable#View_keepScreenOn 5939 */ 5940 public boolean getKeepScreenOn() { 5941 return (mViewFlags & KEEP_SCREEN_ON) != 0; 5942 } 5943 5944 /** 5945 * Controls whether the screen should remain on, modifying the 5946 * value of {@link #KEEP_SCREEN_ON}. 5947 * 5948 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 5949 * 5950 * @see #getKeepScreenOn() 5951 * 5952 * @attr ref android.R.styleable#View_keepScreenOn 5953 */ 5954 public void setKeepScreenOn(boolean keepScreenOn) { 5955 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 5956 } 5957 5958 /** 5959 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5960 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5961 * 5962 * @attr ref android.R.styleable#View_nextFocusLeft 5963 */ 5964 public int getNextFocusLeftId() { 5965 return mNextFocusLeftId; 5966 } 5967 5968 /** 5969 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5970 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 5971 * decide automatically. 5972 * 5973 * @attr ref android.R.styleable#View_nextFocusLeft 5974 */ 5975 public void setNextFocusLeftId(int nextFocusLeftId) { 5976 mNextFocusLeftId = nextFocusLeftId; 5977 } 5978 5979 /** 5980 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 5981 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5982 * 5983 * @attr ref android.R.styleable#View_nextFocusRight 5984 */ 5985 public int getNextFocusRightId() { 5986 return mNextFocusRightId; 5987 } 5988 5989 /** 5990 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 5991 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 5992 * decide automatically. 5993 * 5994 * @attr ref android.R.styleable#View_nextFocusRight 5995 */ 5996 public void setNextFocusRightId(int nextFocusRightId) { 5997 mNextFocusRightId = nextFocusRightId; 5998 } 5999 6000 /** 6001 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 6002 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6003 * 6004 * @attr ref android.R.styleable#View_nextFocusUp 6005 */ 6006 public int getNextFocusUpId() { 6007 return mNextFocusUpId; 6008 } 6009 6010 /** 6011 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 6012 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 6013 * decide automatically. 6014 * 6015 * @attr ref android.R.styleable#View_nextFocusUp 6016 */ 6017 public void setNextFocusUpId(int nextFocusUpId) { 6018 mNextFocusUpId = nextFocusUpId; 6019 } 6020 6021 /** 6022 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 6023 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6024 * 6025 * @attr ref android.R.styleable#View_nextFocusDown 6026 */ 6027 public int getNextFocusDownId() { 6028 return mNextFocusDownId; 6029 } 6030 6031 /** 6032 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 6033 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 6034 * decide automatically. 6035 * 6036 * @attr ref android.R.styleable#View_nextFocusDown 6037 */ 6038 public void setNextFocusDownId(int nextFocusDownId) { 6039 mNextFocusDownId = nextFocusDownId; 6040 } 6041 6042 /** 6043 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 6044 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6045 * 6046 * @attr ref android.R.styleable#View_nextFocusForward 6047 */ 6048 public int getNextFocusForwardId() { 6049 return mNextFocusForwardId; 6050 } 6051 6052 /** 6053 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 6054 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 6055 * decide automatically. 6056 * 6057 * @attr ref android.R.styleable#View_nextFocusForward 6058 */ 6059 public void setNextFocusForwardId(int nextFocusForwardId) { 6060 mNextFocusForwardId = nextFocusForwardId; 6061 } 6062 6063 /** 6064 * Returns the visibility of this view and all of its ancestors 6065 * 6066 * @return True if this view and all of its ancestors are {@link #VISIBLE} 6067 */ 6068 public boolean isShown() { 6069 View current = this; 6070 //noinspection ConstantConditions 6071 do { 6072 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 6073 return false; 6074 } 6075 ViewParent parent = current.mParent; 6076 if (parent == null) { 6077 return false; // We are not attached to the view root 6078 } 6079 if (!(parent instanceof View)) { 6080 return true; 6081 } 6082 current = (View) parent; 6083 } while (current != null); 6084 6085 return false; 6086 } 6087 6088 /** 6089 * Called by the view hierarchy when the content insets for a window have 6090 * changed, to allow it to adjust its content to fit within those windows. 6091 * The content insets tell you the space that the status bar, input method, 6092 * and other system windows infringe on the application's window. 6093 * 6094 * <p>You do not normally need to deal with this function, since the default 6095 * window decoration given to applications takes care of applying it to the 6096 * content of the window. If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 6097 * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case, 6098 * and your content can be placed under those system elements. You can then 6099 * use this method within your view hierarchy if you have parts of your UI 6100 * which you would like to ensure are not being covered. 6101 * 6102 * <p>The default implementation of this method simply applies the content 6103 * insets to the view's padding, consuming that content (modifying the 6104 * insets to be 0), and returning true. This behavior is off by default, but can 6105 * be enabled through {@link #setFitsSystemWindows(boolean)}. 6106 * 6107 * <p>This function's traversal down the hierarchy is depth-first. The same content 6108 * insets object is propagated down the hierarchy, so any changes made to it will 6109 * be seen by all following views (including potentially ones above in 6110 * the hierarchy since this is a depth-first traversal). The first view 6111 * that returns true will abort the entire traversal. 6112 * 6113 * <p>The default implementation works well for a situation where it is 6114 * used with a container that covers the entire window, allowing it to 6115 * apply the appropriate insets to its content on all edges. If you need 6116 * a more complicated layout (such as two different views fitting system 6117 * windows, one on the top of the window, and one on the bottom), 6118 * you can override the method and handle the insets however you would like. 6119 * Note that the insets provided by the framework are always relative to the 6120 * far edges of the window, not accounting for the location of the called view 6121 * within that window. (In fact when this method is called you do not yet know 6122 * where the layout will place the view, as it is done before layout happens.) 6123 * 6124 * <p>Note: unlike many View methods, there is no dispatch phase to this 6125 * call. If you are overriding it in a ViewGroup and want to allow the 6126 * call to continue to your children, you must be sure to call the super 6127 * implementation. 6128 * 6129 * <p>Here is a sample layout that makes use of fitting system windows 6130 * to have controls for a video view placed inside of the window decorations 6131 * that it hides and shows. This can be used with code like the second 6132 * sample (video player) shown in {@link #setSystemUiVisibility(int)}. 6133 * 6134 * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete} 6135 * 6136 * @param insets Current content insets of the window. Prior to 6137 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify 6138 * the insets or else you and Android will be unhappy. 6139 * 6140 * @return {@code true} if this view applied the insets and it should not 6141 * continue propagating further down the hierarchy, {@code false} otherwise. 6142 * @see #getFitsSystemWindows() 6143 * @see #setFitsSystemWindows(boolean) 6144 * @see #setSystemUiVisibility(int) 6145 * 6146 * @deprecated As of API XX use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply 6147 * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use 6148 * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)} 6149 * to implement handling their own insets. 6150 */ 6151 protected boolean fitSystemWindows(Rect insets) { 6152 if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) { 6153 // If we're not in the process of dispatching the newer apply insets call, 6154 // that means we're not in the compatibility path. Dispatch into the newer 6155 // apply insets path and take things from there. 6156 try { 6157 mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS; 6158 return !dispatchApplyWindowInsets(new WindowInsets(insets)).hasInsets(); 6159 } finally { 6160 mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS; 6161 } 6162 } else { 6163 // We're being called from the newer apply insets path. 6164 // Perform the standard fallback behavior. 6165 return fitSystemWindowsInt(insets); 6166 } 6167 } 6168 6169 private boolean fitSystemWindowsInt(Rect insets) { 6170 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 6171 mUserPaddingStart = UNDEFINED_PADDING; 6172 mUserPaddingEnd = UNDEFINED_PADDING; 6173 Rect localInsets = sThreadLocal.get(); 6174 if (localInsets == null) { 6175 localInsets = new Rect(); 6176 sThreadLocal.set(localInsets); 6177 } 6178 boolean res = computeFitSystemWindows(insets, localInsets); 6179 mUserPaddingLeftInitial = localInsets.left; 6180 mUserPaddingRightInitial = localInsets.right; 6181 internalSetPadding(localInsets.left, localInsets.top, 6182 localInsets.right, localInsets.bottom); 6183 return res; 6184 } 6185 return false; 6186 } 6187 6188 /** 6189 * Called when the view should apply {@link WindowInsets} according to its internal policy. 6190 * 6191 * <p>This method should be overridden by views that wish to apply a policy different from or 6192 * in addition to the default behavior. Clients that wish to force a view subtree 6193 * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p> 6194 * 6195 * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set 6196 * it will be called during dispatch instead of this method. The listener may optionally 6197 * call this method from its own implementation if it wishes to apply the view's default 6198 * insets policy in addition to its own.</p> 6199 * 6200 * <p>Implementations of this method should either return the insets parameter unchanged 6201 * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed 6202 * that this view applied itself. This allows new inset types added in future platform 6203 * versions to pass through existing implementations unchanged without being erroneously 6204 * consumed.</p> 6205 * 6206 * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows} 6207 * property is set then the view will consume the system window insets and apply them 6208 * as padding for the view.</p> 6209 * 6210 * @param insets Insets to apply 6211 * @return The supplied insets with any applied insets consumed 6212 */ 6213 public WindowInsets onApplyWindowInsets(WindowInsets insets) { 6214 if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) { 6215 // We weren't called from within a direct call to fitSystemWindows, 6216 // call into it as a fallback in case we're in a class that overrides it 6217 // and has logic to perform. 6218 if (fitSystemWindows(insets.getSystemWindowInsets())) { 6219 return insets.cloneWithSystemWindowInsetsConsumed(); 6220 } 6221 } else { 6222 // We were called from within a direct call to fitSystemWindows. 6223 if (fitSystemWindowsInt(insets.getSystemWindowInsets())) { 6224 return insets.cloneWithSystemWindowInsetsConsumed(); 6225 } 6226 } 6227 return insets; 6228 } 6229 6230 /** 6231 * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying 6232 * window insets to this view. The listener's 6233 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 6234 * method will be called instead of the view's 6235 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 6236 * 6237 * @param listener Listener to set 6238 * 6239 * @see #onApplyWindowInsets(WindowInsets) 6240 */ 6241 public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) { 6242 getListenerInfo().mOnApplyWindowInsetsListener = listener; 6243 } 6244 6245 /** 6246 * Request to apply the given window insets to this view or another view in its subtree. 6247 * 6248 * <p>This method should be called by clients wishing to apply insets corresponding to areas 6249 * obscured by window decorations or overlays. This can include the status and navigation bars, 6250 * action bars, input methods and more. New inset categories may be added in the future. 6251 * The method returns the insets provided minus any that were applied by this view or its 6252 * children.</p> 6253 * 6254 * <p>Clients wishing to provide custom behavior should override the 6255 * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a 6256 * {@link OnApplyWindowInsetsListener} via the 6257 * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener} 6258 * method.</p> 6259 * 6260 * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method. 6261 * </p> 6262 * 6263 * @param insets Insets to apply 6264 * @return The provided insets minus the insets that were consumed 6265 */ 6266 public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) { 6267 try { 6268 mPrivateFlags3 |= PFLAG3_APPLYING_INSETS; 6269 if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) { 6270 return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets); 6271 } else { 6272 return onApplyWindowInsets(insets); 6273 } 6274 } finally { 6275 mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS; 6276 } 6277 } 6278 6279 /** 6280 * @hide Compute the insets that should be consumed by this view and the ones 6281 * that should propagate to those under it. 6282 */ 6283 protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) { 6284 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 6285 || mAttachInfo == null 6286 || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0 6287 && !mAttachInfo.mOverscanRequested)) { 6288 outLocalInsets.set(inoutInsets); 6289 inoutInsets.set(0, 0, 0, 0); 6290 return true; 6291 } else { 6292 // The application wants to take care of fitting system window for 6293 // the content... however we still need to take care of any overscan here. 6294 final Rect overscan = mAttachInfo.mOverscanInsets; 6295 outLocalInsets.set(overscan); 6296 inoutInsets.left -= overscan.left; 6297 inoutInsets.top -= overscan.top; 6298 inoutInsets.right -= overscan.right; 6299 inoutInsets.bottom -= overscan.bottom; 6300 return false; 6301 } 6302 } 6303 6304 /** 6305 * Sets whether or not this view should account for system screen decorations 6306 * such as the status bar and inset its content; that is, controlling whether 6307 * the default implementation of {@link #fitSystemWindows(Rect)} will be 6308 * executed. See that method for more details. 6309 * 6310 * <p>Note that if you are providing your own implementation of 6311 * {@link #fitSystemWindows(Rect)}, then there is no need to set this 6312 * flag to true -- your implementation will be overriding the default 6313 * implementation that checks this flag. 6314 * 6315 * @param fitSystemWindows If true, then the default implementation of 6316 * {@link #fitSystemWindows(Rect)} will be executed. 6317 * 6318 * @attr ref android.R.styleable#View_fitsSystemWindows 6319 * @see #getFitsSystemWindows() 6320 * @see #fitSystemWindows(Rect) 6321 * @see #setSystemUiVisibility(int) 6322 */ 6323 public void setFitsSystemWindows(boolean fitSystemWindows) { 6324 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 6325 } 6326 6327 /** 6328 * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method 6329 * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)} 6330 * will be executed. 6331 * 6332 * @return {@code true} if the default implementation of 6333 * {@link #fitSystemWindows(Rect)} will be executed. 6334 * 6335 * @attr ref android.R.styleable#View_fitsSystemWindows 6336 * @see #setFitsSystemWindows(boolean) 6337 * @see #fitSystemWindows(Rect) 6338 * @see #setSystemUiVisibility(int) 6339 */ 6340 public boolean getFitsSystemWindows() { 6341 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 6342 } 6343 6344 /** @hide */ 6345 public boolean fitsSystemWindows() { 6346 return getFitsSystemWindows(); 6347 } 6348 6349 /** 6350 * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed. 6351 * @deprecated Use {@link #requestApplyInsets()} for newer platform versions. 6352 */ 6353 public void requestFitSystemWindows() { 6354 if (mParent != null) { 6355 mParent.requestFitSystemWindows(); 6356 } 6357 } 6358 6359 /** 6360 * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed. 6361 */ 6362 public void requestApplyInsets() { 6363 requestFitSystemWindows(); 6364 } 6365 6366 /** 6367 * For use by PhoneWindow to make its own system window fitting optional. 6368 * @hide 6369 */ 6370 public void makeOptionalFitsSystemWindows() { 6371 setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS); 6372 } 6373 6374 /** 6375 * Returns the visibility status for this view. 6376 * 6377 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 6378 * @attr ref android.R.styleable#View_visibility 6379 */ 6380 @ViewDebug.ExportedProperty(mapping = { 6381 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 6382 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 6383 @ViewDebug.IntToString(from = GONE, to = "GONE") 6384 }) 6385 @Visibility 6386 public int getVisibility() { 6387 return mViewFlags & VISIBILITY_MASK; 6388 } 6389 6390 /** 6391 * Set the enabled state of this view. 6392 * 6393 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 6394 * @attr ref android.R.styleable#View_visibility 6395 */ 6396 @RemotableViewMethod 6397 public void setVisibility(@Visibility int visibility) { 6398 setFlags(visibility, VISIBILITY_MASK); 6399 if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false); 6400 } 6401 6402 /** 6403 * Returns the enabled status for this view. The interpretation of the 6404 * enabled state varies by subclass. 6405 * 6406 * @return True if this view is enabled, false otherwise. 6407 */ 6408 @ViewDebug.ExportedProperty 6409 public boolean isEnabled() { 6410 return (mViewFlags & ENABLED_MASK) == ENABLED; 6411 } 6412 6413 /** 6414 * Set the enabled state of this view. The interpretation of the enabled 6415 * state varies by subclass. 6416 * 6417 * @param enabled True if this view is enabled, false otherwise. 6418 */ 6419 @RemotableViewMethod 6420 public void setEnabled(boolean enabled) { 6421 if (enabled == isEnabled()) return; 6422 6423 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 6424 6425 /* 6426 * The View most likely has to change its appearance, so refresh 6427 * the drawable state. 6428 */ 6429 refreshDrawableState(); 6430 6431 // Invalidate too, since the default behavior for views is to be 6432 // be drawn at 50% alpha rather than to change the drawable. 6433 invalidate(true); 6434 6435 if (!enabled) { 6436 cancelPendingInputEvents(); 6437 } 6438 } 6439 6440 /** 6441 * Set whether this view can receive the focus. 6442 * 6443 * Setting this to false will also ensure that this view is not focusable 6444 * in touch mode. 6445 * 6446 * @param focusable If true, this view can receive the focus. 6447 * 6448 * @see #setFocusableInTouchMode(boolean) 6449 * @attr ref android.R.styleable#View_focusable 6450 */ 6451 public void setFocusable(boolean focusable) { 6452 if (!focusable) { 6453 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 6454 } 6455 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 6456 } 6457 6458 /** 6459 * Set whether this view can receive focus while in touch mode. 6460 * 6461 * Setting this to true will also ensure that this view is focusable. 6462 * 6463 * @param focusableInTouchMode If true, this view can receive the focus while 6464 * in touch mode. 6465 * 6466 * @see #setFocusable(boolean) 6467 * @attr ref android.R.styleable#View_focusableInTouchMode 6468 */ 6469 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 6470 // Focusable in touch mode should always be set before the focusable flag 6471 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 6472 // which, in touch mode, will not successfully request focus on this view 6473 // because the focusable in touch mode flag is not set 6474 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 6475 if (focusableInTouchMode) { 6476 setFlags(FOCUSABLE, FOCUSABLE_MASK); 6477 } 6478 } 6479 6480 /** 6481 * Set whether this view should have sound effects enabled for events such as 6482 * clicking and touching. 6483 * 6484 * <p>You may wish to disable sound effects for a view if you already play sounds, 6485 * for instance, a dial key that plays dtmf tones. 6486 * 6487 * @param soundEffectsEnabled whether sound effects are enabled for this view. 6488 * @see #isSoundEffectsEnabled() 6489 * @see #playSoundEffect(int) 6490 * @attr ref android.R.styleable#View_soundEffectsEnabled 6491 */ 6492 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 6493 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 6494 } 6495 6496 /** 6497 * @return whether this view should have sound effects enabled for events such as 6498 * clicking and touching. 6499 * 6500 * @see #setSoundEffectsEnabled(boolean) 6501 * @see #playSoundEffect(int) 6502 * @attr ref android.R.styleable#View_soundEffectsEnabled 6503 */ 6504 @ViewDebug.ExportedProperty 6505 public boolean isSoundEffectsEnabled() { 6506 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 6507 } 6508 6509 /** 6510 * Set whether this view should have haptic feedback for events such as 6511 * long presses. 6512 * 6513 * <p>You may wish to disable haptic feedback if your view already controls 6514 * its own haptic feedback. 6515 * 6516 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 6517 * @see #isHapticFeedbackEnabled() 6518 * @see #performHapticFeedback(int) 6519 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6520 */ 6521 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 6522 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 6523 } 6524 6525 /** 6526 * @return whether this view should have haptic feedback enabled for events 6527 * long presses. 6528 * 6529 * @see #setHapticFeedbackEnabled(boolean) 6530 * @see #performHapticFeedback(int) 6531 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6532 */ 6533 @ViewDebug.ExportedProperty 6534 public boolean isHapticFeedbackEnabled() { 6535 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 6536 } 6537 6538 /** 6539 * Returns the layout direction for this view. 6540 * 6541 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 6542 * {@link #LAYOUT_DIRECTION_RTL}, 6543 * {@link #LAYOUT_DIRECTION_INHERIT} or 6544 * {@link #LAYOUT_DIRECTION_LOCALE}. 6545 * 6546 * @attr ref android.R.styleable#View_layoutDirection 6547 * 6548 * @hide 6549 */ 6550 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6551 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 6552 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 6553 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 6554 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 6555 }) 6556 @LayoutDir 6557 public int getRawLayoutDirection() { 6558 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 6559 } 6560 6561 /** 6562 * Set the layout direction for this view. This will propagate a reset of layout direction 6563 * resolution to the view's children and resolve layout direction for this view. 6564 * 6565 * @param layoutDirection the layout direction to set. Should be one of: 6566 * 6567 * {@link #LAYOUT_DIRECTION_LTR}, 6568 * {@link #LAYOUT_DIRECTION_RTL}, 6569 * {@link #LAYOUT_DIRECTION_INHERIT}, 6570 * {@link #LAYOUT_DIRECTION_LOCALE}. 6571 * 6572 * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution 6573 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 6574 * will return the default {@link #LAYOUT_DIRECTION_LTR}. 6575 * 6576 * @attr ref android.R.styleable#View_layoutDirection 6577 */ 6578 @RemotableViewMethod 6579 public void setLayoutDirection(@LayoutDir int layoutDirection) { 6580 if (getRawLayoutDirection() != layoutDirection) { 6581 // Reset the current layout direction and the resolved one 6582 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK; 6583 resetRtlProperties(); 6584 // Set the new layout direction (filtered) 6585 mPrivateFlags2 |= 6586 ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK); 6587 // We need to resolve all RTL properties as they all depend on layout direction 6588 resolveRtlPropertiesIfNeeded(); 6589 requestLayout(); 6590 invalidate(true); 6591 } 6592 } 6593 6594 /** 6595 * Returns the resolved layout direction for this view. 6596 * 6597 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 6598 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL. 6599 * 6600 * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version 6601 * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}. 6602 * 6603 * @attr ref android.R.styleable#View_layoutDirection 6604 */ 6605 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6606 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 6607 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 6608 }) 6609 @ResolvedLayoutDir 6610 public int getLayoutDirection() { 6611 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 6612 if (targetSdkVersion < JELLY_BEAN_MR1) { 6613 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 6614 return LAYOUT_DIRECTION_RESOLVED_DEFAULT; 6615 } 6616 return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) == 6617 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 6618 } 6619 6620 /** 6621 * Indicates whether or not this view's layout is right-to-left. This is resolved from 6622 * layout attribute and/or the inherited value from the parent 6623 * 6624 * @return true if the layout is right-to-left. 6625 * 6626 * @hide 6627 */ 6628 @ViewDebug.ExportedProperty(category = "layout") 6629 public boolean isLayoutRtl() { 6630 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL); 6631 } 6632 6633 /** 6634 * Indicates whether the view is currently tracking transient state that the 6635 * app should not need to concern itself with saving and restoring, but that 6636 * the framework should take special note to preserve when possible. 6637 * 6638 * <p>A view with transient state cannot be trivially rebound from an external 6639 * data source, such as an adapter binding item views in a list. This may be 6640 * because the view is performing an animation, tracking user selection 6641 * of content, or similar.</p> 6642 * 6643 * @return true if the view has transient state 6644 */ 6645 @ViewDebug.ExportedProperty(category = "layout") 6646 public boolean hasTransientState() { 6647 return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE; 6648 } 6649 6650 /** 6651 * Set whether this view is currently tracking transient state that the 6652 * framework should attempt to preserve when possible. This flag is reference counted, 6653 * so every call to setHasTransientState(true) should be paired with a later call 6654 * to setHasTransientState(false). 6655 * 6656 * <p>A view with transient state cannot be trivially rebound from an external 6657 * data source, such as an adapter binding item views in a list. This may be 6658 * because the view is performing an animation, tracking user selection 6659 * of content, or similar.</p> 6660 * 6661 * @param hasTransientState true if this view has transient state 6662 */ 6663 public void setHasTransientState(boolean hasTransientState) { 6664 mTransientStateCount = hasTransientState ? mTransientStateCount + 1 : 6665 mTransientStateCount - 1; 6666 if (mTransientStateCount < 0) { 6667 mTransientStateCount = 0; 6668 Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " + 6669 "unmatched pair of setHasTransientState calls"); 6670 } else if ((hasTransientState && mTransientStateCount == 1) || 6671 (!hasTransientState && mTransientStateCount == 0)) { 6672 // update flag if we've just incremented up from 0 or decremented down to 0 6673 mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) | 6674 (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0); 6675 if (mParent != null) { 6676 try { 6677 mParent.childHasTransientStateChanged(this, hasTransientState); 6678 } catch (AbstractMethodError e) { 6679 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 6680 " does not fully implement ViewParent", e); 6681 } 6682 } 6683 } 6684 } 6685 6686 /** 6687 * Returns true if this view is currently attached to a window. 6688 */ 6689 public boolean isAttachedToWindow() { 6690 return mAttachInfo != null; 6691 } 6692 6693 /** 6694 * Returns true if this view has been through at least one layout since it 6695 * was last attached to or detached from a window. 6696 */ 6697 public boolean isLaidOut() { 6698 return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT; 6699 } 6700 6701 /** 6702 * If this view doesn't do any drawing on its own, set this flag to 6703 * allow further optimizations. By default, this flag is not set on 6704 * View, but could be set on some View subclasses such as ViewGroup. 6705 * 6706 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 6707 * you should clear this flag. 6708 * 6709 * @param willNotDraw whether or not this View draw on its own 6710 */ 6711 public void setWillNotDraw(boolean willNotDraw) { 6712 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 6713 } 6714 6715 /** 6716 * Returns whether or not this View draws on its own. 6717 * 6718 * @return true if this view has nothing to draw, false otherwise 6719 */ 6720 @ViewDebug.ExportedProperty(category = "drawing") 6721 public boolean willNotDraw() { 6722 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 6723 } 6724 6725 /** 6726 * When a View's drawing cache is enabled, drawing is redirected to an 6727 * offscreen bitmap. Some views, like an ImageView, must be able to 6728 * bypass this mechanism if they already draw a single bitmap, to avoid 6729 * unnecessary usage of the memory. 6730 * 6731 * @param willNotCacheDrawing true if this view does not cache its 6732 * drawing, false otherwise 6733 */ 6734 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 6735 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 6736 } 6737 6738 /** 6739 * Returns whether or not this View can cache its drawing or not. 6740 * 6741 * @return true if this view does not cache its drawing, false otherwise 6742 */ 6743 @ViewDebug.ExportedProperty(category = "drawing") 6744 public boolean willNotCacheDrawing() { 6745 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 6746 } 6747 6748 /** 6749 * Indicates whether this view reacts to click events or not. 6750 * 6751 * @return true if the view is clickable, false otherwise 6752 * 6753 * @see #setClickable(boolean) 6754 * @attr ref android.R.styleable#View_clickable 6755 */ 6756 @ViewDebug.ExportedProperty 6757 public boolean isClickable() { 6758 return (mViewFlags & CLICKABLE) == CLICKABLE; 6759 } 6760 6761 /** 6762 * Enables or disables click events for this view. When a view 6763 * is clickable it will change its state to "pressed" on every click. 6764 * Subclasses should set the view clickable to visually react to 6765 * user's clicks. 6766 * 6767 * @param clickable true to make the view clickable, false otherwise 6768 * 6769 * @see #isClickable() 6770 * @attr ref android.R.styleable#View_clickable 6771 */ 6772 public void setClickable(boolean clickable) { 6773 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 6774 } 6775 6776 /** 6777 * Indicates whether this view reacts to long click events or not. 6778 * 6779 * @return true if the view is long clickable, false otherwise 6780 * 6781 * @see #setLongClickable(boolean) 6782 * @attr ref android.R.styleable#View_longClickable 6783 */ 6784 public boolean isLongClickable() { 6785 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 6786 } 6787 6788 /** 6789 * Enables or disables long click events for this view. When a view is long 6790 * clickable it reacts to the user holding down the button for a longer 6791 * duration than a tap. This event can either launch the listener or a 6792 * context menu. 6793 * 6794 * @param longClickable true to make the view long clickable, false otherwise 6795 * @see #isLongClickable() 6796 * @attr ref android.R.styleable#View_longClickable 6797 */ 6798 public void setLongClickable(boolean longClickable) { 6799 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 6800 } 6801 6802 /** 6803 * Sets the pressed state for this view. 6804 * 6805 * @see #isClickable() 6806 * @see #setClickable(boolean) 6807 * 6808 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 6809 * the View's internal state from a previously set "pressed" state. 6810 */ 6811 public void setPressed(boolean pressed) { 6812 final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED); 6813 6814 if (pressed) { 6815 mPrivateFlags |= PFLAG_PRESSED; 6816 } else { 6817 mPrivateFlags &= ~PFLAG_PRESSED; 6818 } 6819 6820 if (needsRefresh) { 6821 refreshDrawableState(); 6822 } 6823 dispatchSetPressed(pressed); 6824 } 6825 6826 /** 6827 * Dispatch setPressed to all of this View's children. 6828 * 6829 * @see #setPressed(boolean) 6830 * 6831 * @param pressed The new pressed state 6832 */ 6833 protected void dispatchSetPressed(boolean pressed) { 6834 } 6835 6836 /** 6837 * Indicates whether the view is currently in pressed state. Unless 6838 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 6839 * the pressed state. 6840 * 6841 * @see #setPressed(boolean) 6842 * @see #isClickable() 6843 * @see #setClickable(boolean) 6844 * 6845 * @return true if the view is currently pressed, false otherwise 6846 */ 6847 public boolean isPressed() { 6848 return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED; 6849 } 6850 6851 /** 6852 * Indicates whether this view will save its state (that is, 6853 * whether its {@link #onSaveInstanceState} method will be called). 6854 * 6855 * @return Returns true if the view state saving is enabled, else false. 6856 * 6857 * @see #setSaveEnabled(boolean) 6858 * @attr ref android.R.styleable#View_saveEnabled 6859 */ 6860 public boolean isSaveEnabled() { 6861 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 6862 } 6863 6864 /** 6865 * Controls whether the saving of this view's state is 6866 * enabled (that is, whether its {@link #onSaveInstanceState} method 6867 * will be called). Note that even if freezing is enabled, the 6868 * view still must have an id assigned to it (via {@link #setId(int)}) 6869 * for its state to be saved. This flag can only disable the 6870 * saving of this view; any child views may still have their state saved. 6871 * 6872 * @param enabled Set to false to <em>disable</em> state saving, or true 6873 * (the default) to allow it. 6874 * 6875 * @see #isSaveEnabled() 6876 * @see #setId(int) 6877 * @see #onSaveInstanceState() 6878 * @attr ref android.R.styleable#View_saveEnabled 6879 */ 6880 public void setSaveEnabled(boolean enabled) { 6881 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 6882 } 6883 6884 /** 6885 * Gets whether the framework should discard touches when the view's 6886 * window is obscured by another visible window. 6887 * Refer to the {@link View} security documentation for more details. 6888 * 6889 * @return True if touch filtering is enabled. 6890 * 6891 * @see #setFilterTouchesWhenObscured(boolean) 6892 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 6893 */ 6894 @ViewDebug.ExportedProperty 6895 public boolean getFilterTouchesWhenObscured() { 6896 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 6897 } 6898 6899 /** 6900 * Sets whether the framework should discard touches when the view's 6901 * window is obscured by another visible window. 6902 * Refer to the {@link View} security documentation for more details. 6903 * 6904 * @param enabled True if touch filtering should be enabled. 6905 * 6906 * @see #getFilterTouchesWhenObscured 6907 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 6908 */ 6909 public void setFilterTouchesWhenObscured(boolean enabled) { 6910 setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0, 6911 FILTER_TOUCHES_WHEN_OBSCURED); 6912 } 6913 6914 /** 6915 * Indicates whether the entire hierarchy under this view will save its 6916 * state when a state saving traversal occurs from its parent. The default 6917 * is true; if false, these views will not be saved unless 6918 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 6919 * 6920 * @return Returns true if the view state saving from parent is enabled, else false. 6921 * 6922 * @see #setSaveFromParentEnabled(boolean) 6923 */ 6924 public boolean isSaveFromParentEnabled() { 6925 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 6926 } 6927 6928 /** 6929 * Controls whether the entire hierarchy under this view will save its 6930 * state when a state saving traversal occurs from its parent. The default 6931 * is true; if false, these views will not be saved unless 6932 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 6933 * 6934 * @param enabled Set to false to <em>disable</em> state saving, or true 6935 * (the default) to allow it. 6936 * 6937 * @see #isSaveFromParentEnabled() 6938 * @see #setId(int) 6939 * @see #onSaveInstanceState() 6940 */ 6941 public void setSaveFromParentEnabled(boolean enabled) { 6942 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 6943 } 6944 6945 6946 /** 6947 * Returns whether this View is able to take focus. 6948 * 6949 * @return True if this view can take focus, or false otherwise. 6950 * @attr ref android.R.styleable#View_focusable 6951 */ 6952 @ViewDebug.ExportedProperty(category = "focus") 6953 public final boolean isFocusable() { 6954 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 6955 } 6956 6957 /** 6958 * When a view is focusable, it may not want to take focus when in touch mode. 6959 * For example, a button would like focus when the user is navigating via a D-pad 6960 * so that the user can click on it, but once the user starts touching the screen, 6961 * the button shouldn't take focus 6962 * @return Whether the view is focusable in touch mode. 6963 * @attr ref android.R.styleable#View_focusableInTouchMode 6964 */ 6965 @ViewDebug.ExportedProperty 6966 public final boolean isFocusableInTouchMode() { 6967 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 6968 } 6969 6970 /** 6971 * Find the nearest view in the specified direction that can take focus. 6972 * This does not actually give focus to that view. 6973 * 6974 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 6975 * 6976 * @return The nearest focusable in the specified direction, or null if none 6977 * can be found. 6978 */ 6979 public View focusSearch(@FocusRealDirection int direction) { 6980 if (mParent != null) { 6981 return mParent.focusSearch(this, direction); 6982 } else { 6983 return null; 6984 } 6985 } 6986 6987 /** 6988 * This method is the last chance for the focused view and its ancestors to 6989 * respond to an arrow key. This is called when the focused view did not 6990 * consume the key internally, nor could the view system find a new view in 6991 * the requested direction to give focus to. 6992 * 6993 * @param focused The currently focused view. 6994 * @param direction The direction focus wants to move. One of FOCUS_UP, 6995 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 6996 * @return True if the this view consumed this unhandled move. 6997 */ 6998 public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) { 6999 return false; 7000 } 7001 7002 /** 7003 * If a user manually specified the next view id for a particular direction, 7004 * use the root to look up the view. 7005 * @param root The root view of the hierarchy containing this view. 7006 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 7007 * or FOCUS_BACKWARD. 7008 * @return The user specified next view, or null if there is none. 7009 */ 7010 View findUserSetNextFocus(View root, @FocusDirection int direction) { 7011 switch (direction) { 7012 case FOCUS_LEFT: 7013 if (mNextFocusLeftId == View.NO_ID) return null; 7014 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 7015 case FOCUS_RIGHT: 7016 if (mNextFocusRightId == View.NO_ID) return null; 7017 return findViewInsideOutShouldExist(root, mNextFocusRightId); 7018 case FOCUS_UP: 7019 if (mNextFocusUpId == View.NO_ID) return null; 7020 return findViewInsideOutShouldExist(root, mNextFocusUpId); 7021 case FOCUS_DOWN: 7022 if (mNextFocusDownId == View.NO_ID) return null; 7023 return findViewInsideOutShouldExist(root, mNextFocusDownId); 7024 case FOCUS_FORWARD: 7025 if (mNextFocusForwardId == View.NO_ID) return null; 7026 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 7027 case FOCUS_BACKWARD: { 7028 if (mID == View.NO_ID) return null; 7029 final int id = mID; 7030 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 7031 @Override 7032 public boolean apply(View t) { 7033 return t.mNextFocusForwardId == id; 7034 } 7035 }); 7036 } 7037 } 7038 return null; 7039 } 7040 7041 private View findViewInsideOutShouldExist(View root, int id) { 7042 if (mMatchIdPredicate == null) { 7043 mMatchIdPredicate = new MatchIdPredicate(); 7044 } 7045 mMatchIdPredicate.mId = id; 7046 View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate); 7047 if (result == null) { 7048 Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id); 7049 } 7050 return result; 7051 } 7052 7053 /** 7054 * Find and return all focusable views that are descendants of this view, 7055 * possibly including this view if it is focusable itself. 7056 * 7057 * @param direction The direction of the focus 7058 * @return A list of focusable views 7059 */ 7060 public ArrayList<View> getFocusables(@FocusDirection int direction) { 7061 ArrayList<View> result = new ArrayList<View>(24); 7062 addFocusables(result, direction); 7063 return result; 7064 } 7065 7066 /** 7067 * Add any focusable views that are descendants of this view (possibly 7068 * including this view if it is focusable itself) to views. If we are in touch mode, 7069 * only add views that are also focusable in touch mode. 7070 * 7071 * @param views Focusable views found so far 7072 * @param direction The direction of the focus 7073 */ 7074 public void addFocusables(ArrayList<View> views, @FocusDirection int direction) { 7075 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 7076 } 7077 7078 /** 7079 * Adds any focusable views that are descendants of this view (possibly 7080 * including this view if it is focusable itself) to views. This method 7081 * adds all focusable views regardless if we are in touch mode or 7082 * only views focusable in touch mode if we are in touch mode or 7083 * only views that can take accessibility focus if accessibility is enabeld 7084 * depending on the focusable mode paramater. 7085 * 7086 * @param views Focusable views found so far or null if all we are interested is 7087 * the number of focusables. 7088 * @param direction The direction of the focus. 7089 * @param focusableMode The type of focusables to be added. 7090 * 7091 * @see #FOCUSABLES_ALL 7092 * @see #FOCUSABLES_TOUCH_MODE 7093 */ 7094 public void addFocusables(ArrayList<View> views, @FocusDirection int direction, 7095 @FocusableMode int focusableMode) { 7096 if (views == null) { 7097 return; 7098 } 7099 if (!isFocusable()) { 7100 return; 7101 } 7102 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE 7103 && isInTouchMode() && !isFocusableInTouchMode()) { 7104 return; 7105 } 7106 views.add(this); 7107 } 7108 7109 /** 7110 * Finds the Views that contain given text. The containment is case insensitive. 7111 * The search is performed by either the text that the View renders or the content 7112 * description that describes the view for accessibility purposes and the view does 7113 * not render or both. Clients can specify how the search is to be performed via 7114 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 7115 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 7116 * 7117 * @param outViews The output list of matching Views. 7118 * @param searched The text to match against. 7119 * 7120 * @see #FIND_VIEWS_WITH_TEXT 7121 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 7122 * @see #setContentDescription(CharSequence) 7123 */ 7124 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, 7125 @FindViewFlags int flags) { 7126 if (getAccessibilityNodeProvider() != null) { 7127 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 7128 outViews.add(this); 7129 } 7130 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 7131 && (searched != null && searched.length() > 0) 7132 && (mContentDescription != null && mContentDescription.length() > 0)) { 7133 String searchedLowerCase = searched.toString().toLowerCase(); 7134 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 7135 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 7136 outViews.add(this); 7137 } 7138 } 7139 } 7140 7141 /** 7142 * Find and return all touchable views that are descendants of this view, 7143 * possibly including this view if it is touchable itself. 7144 * 7145 * @return A list of touchable views 7146 */ 7147 public ArrayList<View> getTouchables() { 7148 ArrayList<View> result = new ArrayList<View>(); 7149 addTouchables(result); 7150 return result; 7151 } 7152 7153 /** 7154 * Add any touchable views that are descendants of this view (possibly 7155 * including this view if it is touchable itself) to views. 7156 * 7157 * @param views Touchable views found so far 7158 */ 7159 public void addTouchables(ArrayList<View> views) { 7160 final int viewFlags = mViewFlags; 7161 7162 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 7163 && (viewFlags & ENABLED_MASK) == ENABLED) { 7164 views.add(this); 7165 } 7166 } 7167 7168 /** 7169 * Returns whether this View is accessibility focused. 7170 * 7171 * @return True if this View is accessibility focused. 7172 */ 7173 public boolean isAccessibilityFocused() { 7174 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0; 7175 } 7176 7177 /** 7178 * Call this to try to give accessibility focus to this view. 7179 * 7180 * A view will not actually take focus if {@link AccessibilityManager#isEnabled()} 7181 * returns false or the view is no visible or the view already has accessibility 7182 * focus. 7183 * 7184 * See also {@link #focusSearch(int)}, which is what you call to say that you 7185 * have focus, and you want your parent to look for the next one. 7186 * 7187 * @return Whether this view actually took accessibility focus. 7188 * 7189 * @hide 7190 */ 7191 public boolean requestAccessibilityFocus() { 7192 AccessibilityManager manager = AccessibilityManager.getInstance(mContext); 7193 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 7194 return false; 7195 } 7196 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7197 return false; 7198 } 7199 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) { 7200 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED; 7201 ViewRootImpl viewRootImpl = getViewRootImpl(); 7202 if (viewRootImpl != null) { 7203 viewRootImpl.setAccessibilityFocus(this, null); 7204 } 7205 invalidate(); 7206 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); 7207 return true; 7208 } 7209 return false; 7210 } 7211 7212 /** 7213 * Call this to try to clear accessibility focus of this view. 7214 * 7215 * See also {@link #focusSearch(int)}, which is what you call to say that you 7216 * have focus, and you want your parent to look for the next one. 7217 * 7218 * @hide 7219 */ 7220 public void clearAccessibilityFocus() { 7221 clearAccessibilityFocusNoCallbacks(); 7222 // Clear the global reference of accessibility focus if this 7223 // view or any of its descendants had accessibility focus. 7224 ViewRootImpl viewRootImpl = getViewRootImpl(); 7225 if (viewRootImpl != null) { 7226 View focusHost = viewRootImpl.getAccessibilityFocusedHost(); 7227 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 7228 viewRootImpl.setAccessibilityFocus(null, null); 7229 } 7230 } 7231 } 7232 7233 private void sendAccessibilityHoverEvent(int eventType) { 7234 // Since we are not delivering to a client accessibility events from not 7235 // important views (unless the clinet request that) we need to fire the 7236 // event from the deepest view exposed to the client. As a consequence if 7237 // the user crosses a not exposed view the client will see enter and exit 7238 // of the exposed predecessor followed by and enter and exit of that same 7239 // predecessor when entering and exiting the not exposed descendant. This 7240 // is fine since the client has a clear idea which view is hovered at the 7241 // price of a couple more events being sent. This is a simple and 7242 // working solution. 7243 View source = this; 7244 while (true) { 7245 if (source.includeForAccessibility()) { 7246 source.sendAccessibilityEvent(eventType); 7247 return; 7248 } 7249 ViewParent parent = source.getParent(); 7250 if (parent instanceof View) { 7251 source = (View) parent; 7252 } else { 7253 return; 7254 } 7255 } 7256 } 7257 7258 /** 7259 * Clears accessibility focus without calling any callback methods 7260 * normally invoked in {@link #clearAccessibilityFocus()}. This method 7261 * is used for clearing accessibility focus when giving this focus to 7262 * another view. 7263 */ 7264 void clearAccessibilityFocusNoCallbacks() { 7265 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 7266 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 7267 invalidate(); 7268 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); 7269 } 7270 } 7271 7272 /** 7273 * Call this to try to give focus to a specific view or to one of its 7274 * descendants. 7275 * 7276 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7277 * false), or if it is focusable and it is not focusable in touch mode 7278 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7279 * 7280 * See also {@link #focusSearch(int)}, which is what you call to say that you 7281 * have focus, and you want your parent to look for the next one. 7282 * 7283 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 7284 * {@link #FOCUS_DOWN} and <code>null</code>. 7285 * 7286 * @return Whether this view or one of its descendants actually took focus. 7287 */ 7288 public final boolean requestFocus() { 7289 return requestFocus(View.FOCUS_DOWN); 7290 } 7291 7292 /** 7293 * Call this to try to give focus to a specific view or to one of its 7294 * descendants and give it a hint about what direction focus is heading. 7295 * 7296 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7297 * false), or if it is focusable and it is not focusable in touch mode 7298 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7299 * 7300 * See also {@link #focusSearch(int)}, which is what you call to say that you 7301 * have focus, and you want your parent to look for the next one. 7302 * 7303 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 7304 * <code>null</code> set for the previously focused rectangle. 7305 * 7306 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7307 * @return Whether this view or one of its descendants actually took focus. 7308 */ 7309 public final boolean requestFocus(int direction) { 7310 return requestFocus(direction, null); 7311 } 7312 7313 /** 7314 * Call this to try to give focus to a specific view or to one of its descendants 7315 * and give it hints about the direction and a specific rectangle that the focus 7316 * is coming from. The rectangle can help give larger views a finer grained hint 7317 * about where focus is coming from, and therefore, where to show selection, or 7318 * forward focus change internally. 7319 * 7320 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7321 * false), or if it is focusable and it is not focusable in touch mode 7322 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7323 * 7324 * A View will not take focus if it is not visible. 7325 * 7326 * A View will not take focus if one of its parents has 7327 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 7328 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 7329 * 7330 * See also {@link #focusSearch(int)}, which is what you call to say that you 7331 * have focus, and you want your parent to look for the next one. 7332 * 7333 * You may wish to override this method if your custom {@link View} has an internal 7334 * {@link View} that it wishes to forward the request to. 7335 * 7336 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7337 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 7338 * to give a finer grained hint about where focus is coming from. May be null 7339 * if there is no hint. 7340 * @return Whether this view or one of its descendants actually took focus. 7341 */ 7342 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 7343 return requestFocusNoSearch(direction, previouslyFocusedRect); 7344 } 7345 7346 private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) { 7347 // need to be focusable 7348 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 7349 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7350 return false; 7351 } 7352 7353 // need to be focusable in touch mode if in touch mode 7354 if (isInTouchMode() && 7355 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 7356 return false; 7357 } 7358 7359 // need to not have any parents blocking us 7360 if (hasAncestorThatBlocksDescendantFocus()) { 7361 return false; 7362 } 7363 7364 handleFocusGainInternal(direction, previouslyFocusedRect); 7365 return true; 7366 } 7367 7368 /** 7369 * Call this to try to give focus to a specific view or to one of its descendants. This is a 7370 * special variant of {@link #requestFocus() } that will allow views that are not focuable in 7371 * touch mode to request focus when they are touched. 7372 * 7373 * @return Whether this view or one of its descendants actually took focus. 7374 * 7375 * @see #isInTouchMode() 7376 * 7377 */ 7378 public final boolean requestFocusFromTouch() { 7379 // Leave touch mode if we need to 7380 if (isInTouchMode()) { 7381 ViewRootImpl viewRoot = getViewRootImpl(); 7382 if (viewRoot != null) { 7383 viewRoot.ensureTouchMode(false); 7384 } 7385 } 7386 return requestFocus(View.FOCUS_DOWN); 7387 } 7388 7389 /** 7390 * @return Whether any ancestor of this view blocks descendant focus. 7391 */ 7392 private boolean hasAncestorThatBlocksDescendantFocus() { 7393 ViewParent ancestor = mParent; 7394 while (ancestor instanceof ViewGroup) { 7395 final ViewGroup vgAncestor = (ViewGroup) ancestor; 7396 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) { 7397 return true; 7398 } else { 7399 ancestor = vgAncestor.getParent(); 7400 } 7401 } 7402 return false; 7403 } 7404 7405 /** 7406 * Gets the mode for determining whether this View is important for accessibility 7407 * which is if it fires accessibility events and if it is reported to 7408 * accessibility services that query the screen. 7409 * 7410 * @return The mode for determining whether a View is important for accessibility. 7411 * 7412 * @attr ref android.R.styleable#View_importantForAccessibility 7413 * 7414 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 7415 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 7416 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 7417 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 7418 */ 7419 @ViewDebug.ExportedProperty(category = "accessibility", mapping = { 7420 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"), 7421 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"), 7422 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"), 7423 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS, 7424 to = "noHideDescendants") 7425 }) 7426 public int getImportantForAccessibility() { 7427 return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 7428 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 7429 } 7430 7431 /** 7432 * Sets the live region mode for this view. This indicates to accessibility 7433 * services whether they should automatically notify the user about changes 7434 * to the view's content description or text, or to the content descriptions 7435 * or text of the view's children (where applicable). 7436 * <p> 7437 * For example, in a login screen with a TextView that displays an "incorrect 7438 * password" notification, that view should be marked as a live region with 7439 * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 7440 * <p> 7441 * To disable change notifications for this view, use 7442 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region 7443 * mode for most views. 7444 * <p> 7445 * To indicate that the user should be notified of changes, use 7446 * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 7447 * <p> 7448 * If the view's changes should interrupt ongoing speech and notify the user 7449 * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}. 7450 * 7451 * @param mode The live region mode for this view, one of: 7452 * <ul> 7453 * <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE} 7454 * <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE} 7455 * <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE} 7456 * </ul> 7457 * @attr ref android.R.styleable#View_accessibilityLiveRegion 7458 */ 7459 public void setAccessibilityLiveRegion(int mode) { 7460 if (mode != getAccessibilityLiveRegion()) { 7461 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 7462 mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT) 7463 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 7464 notifyViewAccessibilityStateChangedIfNeeded( 7465 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7466 } 7467 } 7468 7469 /** 7470 * Gets the live region mode for this View. 7471 * 7472 * @return The live region mode for the view. 7473 * 7474 * @attr ref android.R.styleable#View_accessibilityLiveRegion 7475 * 7476 * @see #setAccessibilityLiveRegion(int) 7477 */ 7478 public int getAccessibilityLiveRegion() { 7479 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK) 7480 >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 7481 } 7482 7483 /** 7484 * Sets how to determine whether this view is important for accessibility 7485 * which is if it fires accessibility events and if it is reported to 7486 * accessibility services that query the screen. 7487 * 7488 * @param mode How to determine whether this view is important for accessibility. 7489 * 7490 * @attr ref android.R.styleable#View_importantForAccessibility 7491 * 7492 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 7493 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 7494 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 7495 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 7496 */ 7497 public void setImportantForAccessibility(int mode) { 7498 final int oldMode = getImportantForAccessibility(); 7499 if (mode != oldMode) { 7500 // If we're moving between AUTO and another state, we might not need 7501 // to send a subtree changed notification. We'll store the computed 7502 // importance, since we'll need to check it later to make sure. 7503 final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO 7504 || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO; 7505 final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility(); 7506 mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 7507 mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT) 7508 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 7509 if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) { 7510 notifySubtreeAccessibilityStateChangedIfNeeded(); 7511 } else { 7512 notifyViewAccessibilityStateChangedIfNeeded( 7513 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7514 } 7515 } 7516 } 7517 7518 /** 7519 * Computes whether this view should be exposed for accessibility. In 7520 * general, views that are interactive or provide information are exposed 7521 * while views that serve only as containers are hidden. 7522 * <p> 7523 * If an ancestor of this view has importance 7524 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method 7525 * returns <code>false</code>. 7526 * <p> 7527 * Otherwise, the value is computed according to the view's 7528 * {@link #getImportantForAccessibility()} value: 7529 * <ol> 7530 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or 7531 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false 7532 * </code> 7533 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code> 7534 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if 7535 * view satisfies any of the following: 7536 * <ul> 7537 * <li>Is actionable, e.g. {@link #isClickable()}, 7538 * {@link #isLongClickable()}, or {@link #isFocusable()} 7539 * <li>Has an {@link AccessibilityDelegate} 7540 * <li>Has an interaction listener, e.g. {@link OnTouchListener}, 7541 * {@link OnKeyListener}, etc. 7542 * <li>Is an accessibility live region, e.g. 7543 * {@link #getAccessibilityLiveRegion()} is not 7544 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. 7545 * </ul> 7546 * </ol> 7547 * 7548 * @return Whether the view is exposed for accessibility. 7549 * @see #setImportantForAccessibility(int) 7550 * @see #getImportantForAccessibility() 7551 */ 7552 public boolean isImportantForAccessibility() { 7553 final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 7554 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 7555 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO 7556 || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 7557 return false; 7558 } 7559 7560 // Check parent mode to ensure we're not hidden. 7561 ViewParent parent = mParent; 7562 while (parent instanceof View) { 7563 if (((View) parent).getImportantForAccessibility() 7564 == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 7565 return false; 7566 } 7567 parent = parent.getParent(); 7568 } 7569 7570 return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility() 7571 || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null 7572 || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE; 7573 } 7574 7575 /** 7576 * Gets the parent for accessibility purposes. Note that the parent for 7577 * accessibility is not necessary the immediate parent. It is the first 7578 * predecessor that is important for accessibility. 7579 * 7580 * @return The parent for accessibility purposes. 7581 */ 7582 public ViewParent getParentForAccessibility() { 7583 if (mParent instanceof View) { 7584 View parentView = (View) mParent; 7585 if (parentView.includeForAccessibility()) { 7586 return mParent; 7587 } else { 7588 return mParent.getParentForAccessibility(); 7589 } 7590 } 7591 return null; 7592 } 7593 7594 /** 7595 * Adds the children of a given View for accessibility. Since some Views are 7596 * not important for accessibility the children for accessibility are not 7597 * necessarily direct children of the view, rather they are the first level of 7598 * descendants important for accessibility. 7599 * 7600 * @param children The list of children for accessibility. 7601 */ 7602 public void addChildrenForAccessibility(ArrayList<View> children) { 7603 7604 } 7605 7606 /** 7607 * Whether to regard this view for accessibility. A view is regarded for 7608 * accessibility if it is important for accessibility or the querying 7609 * accessibility service has explicitly requested that view not 7610 * important for accessibility are regarded. 7611 * 7612 * @return Whether to regard the view for accessibility. 7613 * 7614 * @hide 7615 */ 7616 public boolean includeForAccessibility() { 7617 if (mAttachInfo != null) { 7618 return (mAttachInfo.mAccessibilityFetchFlags 7619 & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0 7620 || isImportantForAccessibility(); 7621 } 7622 return false; 7623 } 7624 7625 /** 7626 * Returns whether the View is considered actionable from 7627 * accessibility perspective. Such view are important for 7628 * accessibility. 7629 * 7630 * @return True if the view is actionable for accessibility. 7631 * 7632 * @hide 7633 */ 7634 public boolean isActionableForAccessibility() { 7635 return (isClickable() || isLongClickable() || isFocusable()); 7636 } 7637 7638 /** 7639 * Returns whether the View has registered callbacks which makes it 7640 * important for accessibility. 7641 * 7642 * @return True if the view is actionable for accessibility. 7643 */ 7644 private boolean hasListenersForAccessibility() { 7645 ListenerInfo info = getListenerInfo(); 7646 return mTouchDelegate != null || info.mOnKeyListener != null 7647 || info.mOnTouchListener != null || info.mOnGenericMotionListener != null 7648 || info.mOnHoverListener != null || info.mOnDragListener != null; 7649 } 7650 7651 /** 7652 * Notifies that the accessibility state of this view changed. The change 7653 * is local to this view and does not represent structural changes such 7654 * as children and parent. For example, the view became focusable. The 7655 * notification is at at most once every 7656 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 7657 * to avoid unnecessary load to the system. Also once a view has a pending 7658 * notification this method is a NOP until the notification has been sent. 7659 * 7660 * @hide 7661 */ 7662 public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) { 7663 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 7664 return; 7665 } 7666 if (mSendViewStateChangedAccessibilityEvent == null) { 7667 mSendViewStateChangedAccessibilityEvent = 7668 new SendViewStateChangedAccessibilityEvent(); 7669 } 7670 mSendViewStateChangedAccessibilityEvent.runOrPost(changeType); 7671 } 7672 7673 /** 7674 * Notifies that the accessibility state of this view changed. The change 7675 * is *not* local to this view and does represent structural changes such 7676 * as children and parent. For example, the view size changed. The 7677 * notification is at at most once every 7678 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 7679 * to avoid unnecessary load to the system. Also once a view has a pending 7680 * notifucation this method is a NOP until the notification has been sent. 7681 * 7682 * @hide 7683 */ 7684 public void notifySubtreeAccessibilityStateChangedIfNeeded() { 7685 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 7686 return; 7687 } 7688 if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) { 7689 mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 7690 if (mParent != null) { 7691 try { 7692 mParent.notifySubtreeAccessibilityStateChanged( 7693 this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE); 7694 } catch (AbstractMethodError e) { 7695 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 7696 " does not fully implement ViewParent", e); 7697 } 7698 } 7699 } 7700 } 7701 7702 /** 7703 * Reset the flag indicating the accessibility state of the subtree rooted 7704 * at this view changed. 7705 */ 7706 void resetSubtreeAccessibilityStateChanged() { 7707 mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 7708 } 7709 7710 /** 7711 * Performs the specified accessibility action on the view. For 7712 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 7713 * <p> 7714 * If an {@link AccessibilityDelegate} has been specified via calling 7715 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 7716 * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)} 7717 * is responsible for handling this call. 7718 * </p> 7719 * 7720 * @param action The action to perform. 7721 * @param arguments Optional action arguments. 7722 * @return Whether the action was performed. 7723 */ 7724 public boolean performAccessibilityAction(int action, Bundle arguments) { 7725 if (mAccessibilityDelegate != null) { 7726 return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments); 7727 } else { 7728 return performAccessibilityActionInternal(action, arguments); 7729 } 7730 } 7731 7732 /** 7733 * @see #performAccessibilityAction(int, Bundle) 7734 * 7735 * Note: Called from the default {@link AccessibilityDelegate}. 7736 */ 7737 boolean performAccessibilityActionInternal(int action, Bundle arguments) { 7738 switch (action) { 7739 case AccessibilityNodeInfo.ACTION_CLICK: { 7740 if (isClickable()) { 7741 performClick(); 7742 return true; 7743 } 7744 } break; 7745 case AccessibilityNodeInfo.ACTION_LONG_CLICK: { 7746 if (isLongClickable()) { 7747 performLongClick(); 7748 return true; 7749 } 7750 } break; 7751 case AccessibilityNodeInfo.ACTION_FOCUS: { 7752 if (!hasFocus()) { 7753 // Get out of touch mode since accessibility 7754 // wants to move focus around. 7755 getViewRootImpl().ensureTouchMode(false); 7756 return requestFocus(); 7757 } 7758 } break; 7759 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 7760 if (hasFocus()) { 7761 clearFocus(); 7762 return !isFocused(); 7763 } 7764 } break; 7765 case AccessibilityNodeInfo.ACTION_SELECT: { 7766 if (!isSelected()) { 7767 setSelected(true); 7768 return isSelected(); 7769 } 7770 } break; 7771 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: { 7772 if (isSelected()) { 7773 setSelected(false); 7774 return !isSelected(); 7775 } 7776 } break; 7777 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 7778 if (!isAccessibilityFocused()) { 7779 return requestAccessibilityFocus(); 7780 } 7781 } break; 7782 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 7783 if (isAccessibilityFocused()) { 7784 clearAccessibilityFocus(); 7785 return true; 7786 } 7787 } break; 7788 case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { 7789 if (arguments != null) { 7790 final int granularity = arguments.getInt( 7791 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 7792 final boolean extendSelection = arguments.getBoolean( 7793 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 7794 return traverseAtGranularity(granularity, true, extendSelection); 7795 } 7796 } break; 7797 case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { 7798 if (arguments != null) { 7799 final int granularity = arguments.getInt( 7800 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 7801 final boolean extendSelection = arguments.getBoolean( 7802 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 7803 return traverseAtGranularity(granularity, false, extendSelection); 7804 } 7805 } break; 7806 case AccessibilityNodeInfo.ACTION_SET_SELECTION: { 7807 CharSequence text = getIterableTextForAccessibility(); 7808 if (text == null) { 7809 return false; 7810 } 7811 final int start = (arguments != null) ? arguments.getInt( 7812 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1; 7813 final int end = (arguments != null) ? arguments.getInt( 7814 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1; 7815 // Only cursor position can be specified (selection length == 0) 7816 if ((getAccessibilitySelectionStart() != start 7817 || getAccessibilitySelectionEnd() != end) 7818 && (start == end)) { 7819 setAccessibilitySelection(start, end); 7820 notifyViewAccessibilityStateChangedIfNeeded( 7821 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7822 return true; 7823 } 7824 } break; 7825 } 7826 return false; 7827 } 7828 7829 private boolean traverseAtGranularity(int granularity, boolean forward, 7830 boolean extendSelection) { 7831 CharSequence text = getIterableTextForAccessibility(); 7832 if (text == null || text.length() == 0) { 7833 return false; 7834 } 7835 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 7836 if (iterator == null) { 7837 return false; 7838 } 7839 int current = getAccessibilitySelectionEnd(); 7840 if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 7841 current = forward ? 0 : text.length(); 7842 } 7843 final int[] range = forward ? iterator.following(current) : iterator.preceding(current); 7844 if (range == null) { 7845 return false; 7846 } 7847 final int segmentStart = range[0]; 7848 final int segmentEnd = range[1]; 7849 int selectionStart; 7850 int selectionEnd; 7851 if (extendSelection && isAccessibilitySelectionExtendable()) { 7852 selectionStart = getAccessibilitySelectionStart(); 7853 if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 7854 selectionStart = forward ? segmentStart : segmentEnd; 7855 } 7856 selectionEnd = forward ? segmentEnd : segmentStart; 7857 } else { 7858 selectionStart = selectionEnd= forward ? segmentEnd : segmentStart; 7859 } 7860 setAccessibilitySelection(selectionStart, selectionEnd); 7861 final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY 7862 : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY; 7863 sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd); 7864 return true; 7865 } 7866 7867 /** 7868 * Gets the text reported for accessibility purposes. 7869 * 7870 * @return The accessibility text. 7871 * 7872 * @hide 7873 */ 7874 public CharSequence getIterableTextForAccessibility() { 7875 return getContentDescription(); 7876 } 7877 7878 /** 7879 * Gets whether accessibility selection can be extended. 7880 * 7881 * @return If selection is extensible. 7882 * 7883 * @hide 7884 */ 7885 public boolean isAccessibilitySelectionExtendable() { 7886 return false; 7887 } 7888 7889 /** 7890 * @hide 7891 */ 7892 public int getAccessibilitySelectionStart() { 7893 return mAccessibilityCursorPosition; 7894 } 7895 7896 /** 7897 * @hide 7898 */ 7899 public int getAccessibilitySelectionEnd() { 7900 return getAccessibilitySelectionStart(); 7901 } 7902 7903 /** 7904 * @hide 7905 */ 7906 public void setAccessibilitySelection(int start, int end) { 7907 if (start == end && end == mAccessibilityCursorPosition) { 7908 return; 7909 } 7910 if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) { 7911 mAccessibilityCursorPosition = start; 7912 } else { 7913 mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 7914 } 7915 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); 7916 } 7917 7918 private void sendViewTextTraversedAtGranularityEvent(int action, int granularity, 7919 int fromIndex, int toIndex) { 7920 if (mParent == null) { 7921 return; 7922 } 7923 AccessibilityEvent event = AccessibilityEvent.obtain( 7924 AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY); 7925 onInitializeAccessibilityEvent(event); 7926 onPopulateAccessibilityEvent(event); 7927 event.setFromIndex(fromIndex); 7928 event.setToIndex(toIndex); 7929 event.setAction(action); 7930 event.setMovementGranularity(granularity); 7931 mParent.requestSendAccessibilityEvent(this, event); 7932 } 7933 7934 /** 7935 * @hide 7936 */ 7937 public TextSegmentIterator getIteratorForGranularity(int granularity) { 7938 switch (granularity) { 7939 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { 7940 CharSequence text = getIterableTextForAccessibility(); 7941 if (text != null && text.length() > 0) { 7942 CharacterTextSegmentIterator iterator = 7943 CharacterTextSegmentIterator.getInstance( 7944 mContext.getResources().getConfiguration().locale); 7945 iterator.initialize(text.toString()); 7946 return iterator; 7947 } 7948 } break; 7949 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: { 7950 CharSequence text = getIterableTextForAccessibility(); 7951 if (text != null && text.length() > 0) { 7952 WordTextSegmentIterator iterator = 7953 WordTextSegmentIterator.getInstance( 7954 mContext.getResources().getConfiguration().locale); 7955 iterator.initialize(text.toString()); 7956 return iterator; 7957 } 7958 } break; 7959 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: { 7960 CharSequence text = getIterableTextForAccessibility(); 7961 if (text != null && text.length() > 0) { 7962 ParagraphTextSegmentIterator iterator = 7963 ParagraphTextSegmentIterator.getInstance(); 7964 iterator.initialize(text.toString()); 7965 return iterator; 7966 } 7967 } break; 7968 } 7969 return null; 7970 } 7971 7972 /** 7973 * @hide 7974 */ 7975 public void dispatchStartTemporaryDetach() { 7976 onStartTemporaryDetach(); 7977 } 7978 7979 /** 7980 * This is called when a container is going to temporarily detach a child, with 7981 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 7982 * It will either be followed by {@link #onFinishTemporaryDetach()} or 7983 * {@link #onDetachedFromWindow()} when the container is done. 7984 */ 7985 public void onStartTemporaryDetach() { 7986 removeUnsetPressCallback(); 7987 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 7988 } 7989 7990 /** 7991 * @hide 7992 */ 7993 public void dispatchFinishTemporaryDetach() { 7994 onFinishTemporaryDetach(); 7995 } 7996 7997 /** 7998 * Called after {@link #onStartTemporaryDetach} when the container is done 7999 * changing the view. 8000 */ 8001 public void onFinishTemporaryDetach() { 8002 } 8003 8004 /** 8005 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 8006 * for this view's window. Returns null if the view is not currently attached 8007 * to the window. Normally you will not need to use this directly, but 8008 * just use the standard high-level event callbacks like 8009 * {@link #onKeyDown(int, KeyEvent)}. 8010 */ 8011 public KeyEvent.DispatcherState getKeyDispatcherState() { 8012 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 8013 } 8014 8015 /** 8016 * Dispatch a key event before it is processed by any input method 8017 * associated with the view hierarchy. This can be used to intercept 8018 * key events in special situations before the IME consumes them; a 8019 * typical example would be handling the BACK key to update the application's 8020 * UI instead of allowing the IME to see it and close itself. 8021 * 8022 * @param event The key event to be dispatched. 8023 * @return True if the event was handled, false otherwise. 8024 */ 8025 public boolean dispatchKeyEventPreIme(KeyEvent event) { 8026 return onKeyPreIme(event.getKeyCode(), event); 8027 } 8028 8029 /** 8030 * Dispatch a key event to the next view on the focus path. This path runs 8031 * from the top of the view tree down to the currently focused view. If this 8032 * view has focus, it will dispatch to itself. Otherwise it will dispatch 8033 * the next node down the focus path. This method also fires any key 8034 * listeners. 8035 * 8036 * @param event The key event to be dispatched. 8037 * @return True if the event was handled, false otherwise. 8038 */ 8039 public boolean dispatchKeyEvent(KeyEvent event) { 8040 if (mInputEventConsistencyVerifier != null) { 8041 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 8042 } 8043 8044 // Give any attached key listener a first crack at the event. 8045 //noinspection SimplifiableIfStatement 8046 ListenerInfo li = mListenerInfo; 8047 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 8048 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 8049 return true; 8050 } 8051 8052 if (event.dispatch(this, mAttachInfo != null 8053 ? mAttachInfo.mKeyDispatchState : null, this)) { 8054 return true; 8055 } 8056 8057 if (mInputEventConsistencyVerifier != null) { 8058 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8059 } 8060 return false; 8061 } 8062 8063 /** 8064 * Dispatches a key shortcut event. 8065 * 8066 * @param event The key event to be dispatched. 8067 * @return True if the event was handled by the view, false otherwise. 8068 */ 8069 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 8070 return onKeyShortcut(event.getKeyCode(), event); 8071 } 8072 8073 /** 8074 * Pass the touch screen motion event down to the target view, or this 8075 * view if it is the target. 8076 * 8077 * @param event The motion event to be dispatched. 8078 * @return True if the event was handled by the view, false otherwise. 8079 */ 8080 public boolean dispatchTouchEvent(MotionEvent event) { 8081 if (mInputEventConsistencyVerifier != null) { 8082 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 8083 } 8084 8085 if (onFilterTouchEventForSecurity(event)) { 8086 //noinspection SimplifiableIfStatement 8087 ListenerInfo li = mListenerInfo; 8088 if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 8089 && li.mOnTouchListener.onTouch(this, event)) { 8090 return true; 8091 } 8092 8093 if (onTouchEvent(event)) { 8094 return true; 8095 } 8096 } 8097 8098 if (mInputEventConsistencyVerifier != null) { 8099 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8100 } 8101 return false; 8102 } 8103 8104 /** 8105 * Filter the touch event to apply security policies. 8106 * 8107 * @param event The motion event to be filtered. 8108 * @return True if the event should be dispatched, false if the event should be dropped. 8109 * 8110 * @see #getFilterTouchesWhenObscured 8111 */ 8112 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 8113 //noinspection RedundantIfStatement 8114 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 8115 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 8116 // Window is obscured, drop this touch. 8117 return false; 8118 } 8119 return true; 8120 } 8121 8122 /** 8123 * Pass a trackball motion event down to the focused view. 8124 * 8125 * @param event The motion event to be dispatched. 8126 * @return True if the event was handled by the view, false otherwise. 8127 */ 8128 public boolean dispatchTrackballEvent(MotionEvent event) { 8129 if (mInputEventConsistencyVerifier != null) { 8130 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 8131 } 8132 8133 return onTrackballEvent(event); 8134 } 8135 8136 /** 8137 * Dispatch a generic motion event. 8138 * <p> 8139 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 8140 * are delivered to the view under the pointer. All other generic motion events are 8141 * delivered to the focused view. Hover events are handled specially and are delivered 8142 * to {@link #onHoverEvent(MotionEvent)}. 8143 * </p> 8144 * 8145 * @param event The motion event to be dispatched. 8146 * @return True if the event was handled by the view, false otherwise. 8147 */ 8148 public boolean dispatchGenericMotionEvent(MotionEvent event) { 8149 if (mInputEventConsistencyVerifier != null) { 8150 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 8151 } 8152 8153 final int source = event.getSource(); 8154 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 8155 final int action = event.getAction(); 8156 if (action == MotionEvent.ACTION_HOVER_ENTER 8157 || action == MotionEvent.ACTION_HOVER_MOVE 8158 || action == MotionEvent.ACTION_HOVER_EXIT) { 8159 if (dispatchHoverEvent(event)) { 8160 return true; 8161 } 8162 } else if (dispatchGenericPointerEvent(event)) { 8163 return true; 8164 } 8165 } else if (dispatchGenericFocusedEvent(event)) { 8166 return true; 8167 } 8168 8169 if (dispatchGenericMotionEventInternal(event)) { 8170 return true; 8171 } 8172 8173 if (mInputEventConsistencyVerifier != null) { 8174 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8175 } 8176 return false; 8177 } 8178 8179 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 8180 //noinspection SimplifiableIfStatement 8181 ListenerInfo li = mListenerInfo; 8182 if (li != null && li.mOnGenericMotionListener != null 8183 && (mViewFlags & ENABLED_MASK) == ENABLED 8184 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 8185 return true; 8186 } 8187 8188 if (onGenericMotionEvent(event)) { 8189 return true; 8190 } 8191 8192 if (mInputEventConsistencyVerifier != null) { 8193 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8194 } 8195 return false; 8196 } 8197 8198 /** 8199 * Dispatch a hover event. 8200 * <p> 8201 * Do not call this method directly. 8202 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8203 * </p> 8204 * 8205 * @param event The motion event to be dispatched. 8206 * @return True if the event was handled by the view, false otherwise. 8207 */ 8208 protected boolean dispatchHoverEvent(MotionEvent event) { 8209 ListenerInfo li = mListenerInfo; 8210 //noinspection SimplifiableIfStatement 8211 if (li != null && li.mOnHoverListener != null 8212 && (mViewFlags & ENABLED_MASK) == ENABLED 8213 && li.mOnHoverListener.onHover(this, event)) { 8214 return true; 8215 } 8216 8217 return onHoverEvent(event); 8218 } 8219 8220 /** 8221 * Returns true if the view has a child to which it has recently sent 8222 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 8223 * it does not have a hovered child, then it must be the innermost hovered view. 8224 * @hide 8225 */ 8226 protected boolean hasHoveredChild() { 8227 return false; 8228 } 8229 8230 /** 8231 * Dispatch a generic motion event to the view under the first pointer. 8232 * <p> 8233 * Do not call this method directly. 8234 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8235 * </p> 8236 * 8237 * @param event The motion event to be dispatched. 8238 * @return True if the event was handled by the view, false otherwise. 8239 */ 8240 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 8241 return false; 8242 } 8243 8244 /** 8245 * Dispatch a generic motion event to the currently focused view. 8246 * <p> 8247 * Do not call this method directly. 8248 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8249 * </p> 8250 * 8251 * @param event The motion event to be dispatched. 8252 * @return True if the event was handled by the view, false otherwise. 8253 */ 8254 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 8255 return false; 8256 } 8257 8258 /** 8259 * Dispatch a pointer event. 8260 * <p> 8261 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 8262 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 8263 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 8264 * and should not be expected to handle other pointing device features. 8265 * </p> 8266 * 8267 * @param event The motion event to be dispatched. 8268 * @return True if the event was handled by the view, false otherwise. 8269 * @hide 8270 */ 8271 public final boolean dispatchPointerEvent(MotionEvent event) { 8272 if (event.isTouchEvent()) { 8273 return dispatchTouchEvent(event); 8274 } else { 8275 return dispatchGenericMotionEvent(event); 8276 } 8277 } 8278 8279 /** 8280 * Called when the window containing this view gains or loses window focus. 8281 * ViewGroups should override to route to their children. 8282 * 8283 * @param hasFocus True if the window containing this view now has focus, 8284 * false otherwise. 8285 */ 8286 public void dispatchWindowFocusChanged(boolean hasFocus) { 8287 onWindowFocusChanged(hasFocus); 8288 } 8289 8290 /** 8291 * Called when the window containing this view gains or loses focus. Note 8292 * that this is separate from view focus: to receive key events, both 8293 * your view and its window must have focus. If a window is displayed 8294 * on top of yours that takes input focus, then your own window will lose 8295 * focus but the view focus will remain unchanged. 8296 * 8297 * @param hasWindowFocus True if the window containing this view now has 8298 * focus, false otherwise. 8299 */ 8300 public void onWindowFocusChanged(boolean hasWindowFocus) { 8301 InputMethodManager imm = InputMethodManager.peekInstance(); 8302 if (!hasWindowFocus) { 8303 if (isPressed()) { 8304 setPressed(false); 8305 } 8306 if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 8307 imm.focusOut(this); 8308 } 8309 removeLongPressCallback(); 8310 removeTapCallback(); 8311 onFocusLost(); 8312 } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 8313 imm.focusIn(this); 8314 } 8315 refreshDrawableState(); 8316 } 8317 8318 /** 8319 * Returns true if this view is in a window that currently has window focus. 8320 * Note that this is not the same as the view itself having focus. 8321 * 8322 * @return True if this view is in a window that currently has window focus. 8323 */ 8324 public boolean hasWindowFocus() { 8325 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 8326 } 8327 8328 /** 8329 * Dispatch a view visibility change down the view hierarchy. 8330 * ViewGroups should override to route to their children. 8331 * @param changedView The view whose visibility changed. Could be 'this' or 8332 * an ancestor view. 8333 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 8334 * {@link #INVISIBLE} or {@link #GONE}. 8335 */ 8336 protected void dispatchVisibilityChanged(@NonNull View changedView, 8337 @Visibility int visibility) { 8338 onVisibilityChanged(changedView, visibility); 8339 } 8340 8341 /** 8342 * Called when the visibility of the view or an ancestor of the view is changed. 8343 * @param changedView The view whose visibility changed. Could be 'this' or 8344 * an ancestor view. 8345 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 8346 * {@link #INVISIBLE} or {@link #GONE}. 8347 */ 8348 protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) { 8349 if (visibility == VISIBLE) { 8350 if (mAttachInfo != null) { 8351 initialAwakenScrollBars(); 8352 } else { 8353 mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 8354 } 8355 } 8356 } 8357 8358 /** 8359 * Dispatch a hint about whether this view is displayed. For instance, when 8360 * a View moves out of the screen, it might receives a display hint indicating 8361 * the view is not displayed. Applications should not <em>rely</em> on this hint 8362 * as there is no guarantee that they will receive one. 8363 * 8364 * @param hint A hint about whether or not this view is displayed: 8365 * {@link #VISIBLE} or {@link #INVISIBLE}. 8366 */ 8367 public void dispatchDisplayHint(@Visibility int hint) { 8368 onDisplayHint(hint); 8369 } 8370 8371 /** 8372 * Gives this view a hint about whether is displayed or not. For instance, when 8373 * a View moves out of the screen, it might receives a display hint indicating 8374 * the view is not displayed. Applications should not <em>rely</em> on this hint 8375 * as there is no guarantee that they will receive one. 8376 * 8377 * @param hint A hint about whether or not this view is displayed: 8378 * {@link #VISIBLE} or {@link #INVISIBLE}. 8379 */ 8380 protected void onDisplayHint(@Visibility int hint) { 8381 } 8382 8383 /** 8384 * Dispatch a window visibility change down the view hierarchy. 8385 * ViewGroups should override to route to their children. 8386 * 8387 * @param visibility The new visibility of the window. 8388 * 8389 * @see #onWindowVisibilityChanged(int) 8390 */ 8391 public void dispatchWindowVisibilityChanged(@Visibility int visibility) { 8392 onWindowVisibilityChanged(visibility); 8393 } 8394 8395 /** 8396 * Called when the window containing has change its visibility 8397 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 8398 * that this tells you whether or not your window is being made visible 8399 * to the window manager; this does <em>not</em> tell you whether or not 8400 * your window is obscured by other windows on the screen, even if it 8401 * is itself visible. 8402 * 8403 * @param visibility The new visibility of the window. 8404 */ 8405 protected void onWindowVisibilityChanged(@Visibility int visibility) { 8406 if (visibility == VISIBLE) { 8407 initialAwakenScrollBars(); 8408 } 8409 } 8410 8411 /** 8412 * Returns the current visibility of the window this view is attached to 8413 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 8414 * 8415 * @return Returns the current visibility of the view's window. 8416 */ 8417 @Visibility 8418 public int getWindowVisibility() { 8419 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 8420 } 8421 8422 /** 8423 * Retrieve the overall visible display size in which the window this view is 8424 * attached to has been positioned in. This takes into account screen 8425 * decorations above the window, for both cases where the window itself 8426 * is being position inside of them or the window is being placed under 8427 * then and covered insets are used for the window to position its content 8428 * inside. In effect, this tells you the available area where content can 8429 * be placed and remain visible to users. 8430 * 8431 * <p>This function requires an IPC back to the window manager to retrieve 8432 * the requested information, so should not be used in performance critical 8433 * code like drawing. 8434 * 8435 * @param outRect Filled in with the visible display frame. If the view 8436 * is not attached to a window, this is simply the raw display size. 8437 */ 8438 public void getWindowVisibleDisplayFrame(Rect outRect) { 8439 if (mAttachInfo != null) { 8440 try { 8441 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 8442 } catch (RemoteException e) { 8443 return; 8444 } 8445 // XXX This is really broken, and probably all needs to be done 8446 // in the window manager, and we need to know more about whether 8447 // we want the area behind or in front of the IME. 8448 final Rect insets = mAttachInfo.mVisibleInsets; 8449 outRect.left += insets.left; 8450 outRect.top += insets.top; 8451 outRect.right -= insets.right; 8452 outRect.bottom -= insets.bottom; 8453 return; 8454 } 8455 // The view is not attached to a display so we don't have a context. 8456 // Make a best guess about the display size. 8457 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 8458 d.getRectSize(outRect); 8459 } 8460 8461 /** 8462 * Dispatch a notification about a resource configuration change down 8463 * the view hierarchy. 8464 * ViewGroups should override to route to their children. 8465 * 8466 * @param newConfig The new resource configuration. 8467 * 8468 * @see #onConfigurationChanged(android.content.res.Configuration) 8469 */ 8470 public void dispatchConfigurationChanged(Configuration newConfig) { 8471 onConfigurationChanged(newConfig); 8472 } 8473 8474 /** 8475 * Called when the current configuration of the resources being used 8476 * by the application have changed. You can use this to decide when 8477 * to reload resources that can changed based on orientation and other 8478 * configuration characterstics. You only need to use this if you are 8479 * not relying on the normal {@link android.app.Activity} mechanism of 8480 * recreating the activity instance upon a configuration change. 8481 * 8482 * @param newConfig The new resource configuration. 8483 */ 8484 protected void onConfigurationChanged(Configuration newConfig) { 8485 } 8486 8487 /** 8488 * Private function to aggregate all per-view attributes in to the view 8489 * root. 8490 */ 8491 void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) { 8492 performCollectViewAttributes(attachInfo, visibility); 8493 } 8494 8495 void performCollectViewAttributes(AttachInfo attachInfo, int visibility) { 8496 if ((visibility & VISIBILITY_MASK) == VISIBLE) { 8497 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 8498 attachInfo.mKeepScreenOn = true; 8499 } 8500 attachInfo.mSystemUiVisibility |= mSystemUiVisibility; 8501 ListenerInfo li = mListenerInfo; 8502 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 8503 attachInfo.mHasSystemUiListeners = true; 8504 } 8505 } 8506 } 8507 8508 void needGlobalAttributesUpdate(boolean force) { 8509 final AttachInfo ai = mAttachInfo; 8510 if (ai != null && !ai.mRecomputeGlobalAttributes) { 8511 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 8512 || ai.mHasSystemUiListeners) { 8513 ai.mRecomputeGlobalAttributes = true; 8514 } 8515 } 8516 } 8517 8518 /** 8519 * Returns whether the device is currently in touch mode. Touch mode is entered 8520 * once the user begins interacting with the device by touch, and affects various 8521 * things like whether focus is always visible to the user. 8522 * 8523 * @return Whether the device is in touch mode. 8524 */ 8525 @ViewDebug.ExportedProperty 8526 public boolean isInTouchMode() { 8527 if (mAttachInfo != null) { 8528 return mAttachInfo.mInTouchMode; 8529 } else { 8530 return ViewRootImpl.isInTouchMode(); 8531 } 8532 } 8533 8534 /** 8535 * Returns the context the view is running in, through which it can 8536 * access the current theme, resources, etc. 8537 * 8538 * @return The view's Context. 8539 */ 8540 @ViewDebug.CapturedViewProperty 8541 public final Context getContext() { 8542 return mContext; 8543 } 8544 8545 /** 8546 * Handle a key event before it is processed by any input method 8547 * associated with the view hierarchy. This can be used to intercept 8548 * key events in special situations before the IME consumes them; a 8549 * typical example would be handling the BACK key to update the application's 8550 * UI instead of allowing the IME to see it and close itself. 8551 * 8552 * @param keyCode The value in event.getKeyCode(). 8553 * @param event Description of the key event. 8554 * @return If you handled the event, return true. If you want to allow the 8555 * event to be handled by the next receiver, return false. 8556 */ 8557 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 8558 return false; 8559 } 8560 8561 /** 8562 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 8563 * KeyEvent.Callback.onKeyDown()}: perform press of the view 8564 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 8565 * is released, if the view is enabled and clickable. 8566 * 8567 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8568 * although some may elect to do so in some situations. Do not rely on this to 8569 * catch software key presses. 8570 * 8571 * @param keyCode A key code that represents the button pressed, from 8572 * {@link android.view.KeyEvent}. 8573 * @param event The KeyEvent object that defines the button action. 8574 */ 8575 public boolean onKeyDown(int keyCode, KeyEvent event) { 8576 boolean result = false; 8577 8578 if (KeyEvent.isConfirmKey(keyCode)) { 8579 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 8580 return true; 8581 } 8582 // Long clickable items don't necessarily have to be clickable 8583 if (((mViewFlags & CLICKABLE) == CLICKABLE || 8584 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 8585 (event.getRepeatCount() == 0)) { 8586 setPressed(true); 8587 checkForLongClick(0); 8588 return true; 8589 } 8590 } 8591 return result; 8592 } 8593 8594 /** 8595 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 8596 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 8597 * the event). 8598 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8599 * although some may elect to do so in some situations. Do not rely on this to 8600 * catch software key presses. 8601 */ 8602 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 8603 return false; 8604 } 8605 8606 /** 8607 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 8608 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 8609 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 8610 * {@link KeyEvent#KEYCODE_ENTER} is released. 8611 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8612 * although some may elect to do so in some situations. Do not rely on this to 8613 * catch software key presses. 8614 * 8615 * @param keyCode A key code that represents the button pressed, from 8616 * {@link android.view.KeyEvent}. 8617 * @param event The KeyEvent object that defines the button action. 8618 */ 8619 public boolean onKeyUp(int keyCode, KeyEvent event) { 8620 if (KeyEvent.isConfirmKey(keyCode)) { 8621 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 8622 return true; 8623 } 8624 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 8625 setPressed(false); 8626 8627 if (!mHasPerformedLongPress) { 8628 // This is a tap, so remove the longpress check 8629 removeLongPressCallback(); 8630 return performClick(); 8631 } 8632 } 8633 } 8634 return false; 8635 } 8636 8637 /** 8638 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 8639 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 8640 * the event). 8641 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8642 * although some may elect to do so in some situations. Do not rely on this to 8643 * catch software key presses. 8644 * 8645 * @param keyCode A key code that represents the button pressed, from 8646 * {@link android.view.KeyEvent}. 8647 * @param repeatCount The number of times the action was made. 8648 * @param event The KeyEvent object that defines the button action. 8649 */ 8650 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 8651 return false; 8652 } 8653 8654 /** 8655 * Called on the focused view when a key shortcut event is not handled. 8656 * Override this method to implement local key shortcuts for the View. 8657 * Key shortcuts can also be implemented by setting the 8658 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 8659 * 8660 * @param keyCode The value in event.getKeyCode(). 8661 * @param event Description of the key event. 8662 * @return If you handled the event, return true. If you want to allow the 8663 * event to be handled by the next receiver, return false. 8664 */ 8665 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 8666 return false; 8667 } 8668 8669 /** 8670 * Check whether the called view is a text editor, in which case it 8671 * would make sense to automatically display a soft input window for 8672 * it. Subclasses should override this if they implement 8673 * {@link #onCreateInputConnection(EditorInfo)} to return true if 8674 * a call on that method would return a non-null InputConnection, and 8675 * they are really a first-class editor that the user would normally 8676 * start typing on when the go into a window containing your view. 8677 * 8678 * <p>The default implementation always returns false. This does 8679 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 8680 * will not be called or the user can not otherwise perform edits on your 8681 * view; it is just a hint to the system that this is not the primary 8682 * purpose of this view. 8683 * 8684 * @return Returns true if this view is a text editor, else false. 8685 */ 8686 public boolean onCheckIsTextEditor() { 8687 return false; 8688 } 8689 8690 /** 8691 * Create a new InputConnection for an InputMethod to interact 8692 * with the view. The default implementation returns null, since it doesn't 8693 * support input methods. You can override this to implement such support. 8694 * This is only needed for views that take focus and text input. 8695 * 8696 * <p>When implementing this, you probably also want to implement 8697 * {@link #onCheckIsTextEditor()} to indicate you will return a 8698 * non-null InputConnection.</p> 8699 * 8700 * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo} 8701 * object correctly and in its entirety, so that the connected IME can rely 8702 * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart} 8703 * and {@link android.view.inputmethod.EditorInfo#initialSelEnd} members 8704 * must be filled in with the correct cursor position for IMEs to work correctly 8705 * with your application.</p> 8706 * 8707 * @param outAttrs Fill in with attribute information about the connection. 8708 */ 8709 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 8710 return null; 8711 } 8712 8713 /** 8714 * Called by the {@link android.view.inputmethod.InputMethodManager} 8715 * when a view who is not the current 8716 * input connection target is trying to make a call on the manager. The 8717 * default implementation returns false; you can override this to return 8718 * true for certain views if you are performing InputConnection proxying 8719 * to them. 8720 * @param view The View that is making the InputMethodManager call. 8721 * @return Return true to allow the call, false to reject. 8722 */ 8723 public boolean checkInputConnectionProxy(View view) { 8724 return false; 8725 } 8726 8727 /** 8728 * Show the context menu for this view. It is not safe to hold on to the 8729 * menu after returning from this method. 8730 * 8731 * You should normally not overload this method. Overload 8732 * {@link #onCreateContextMenu(ContextMenu)} or define an 8733 * {@link OnCreateContextMenuListener} to add items to the context menu. 8734 * 8735 * @param menu The context menu to populate 8736 */ 8737 public void createContextMenu(ContextMenu menu) { 8738 ContextMenuInfo menuInfo = getContextMenuInfo(); 8739 8740 // Sets the current menu info so all items added to menu will have 8741 // my extra info set. 8742 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 8743 8744 onCreateContextMenu(menu); 8745 ListenerInfo li = mListenerInfo; 8746 if (li != null && li.mOnCreateContextMenuListener != null) { 8747 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 8748 } 8749 8750 // Clear the extra information so subsequent items that aren't mine don't 8751 // have my extra info. 8752 ((MenuBuilder)menu).setCurrentMenuInfo(null); 8753 8754 if (mParent != null) { 8755 mParent.createContextMenu(menu); 8756 } 8757 } 8758 8759 /** 8760 * Views should implement this if they have extra information to associate 8761 * with the context menu. The return result is supplied as a parameter to 8762 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 8763 * callback. 8764 * 8765 * @return Extra information about the item for which the context menu 8766 * should be shown. This information will vary across different 8767 * subclasses of View. 8768 */ 8769 protected ContextMenuInfo getContextMenuInfo() { 8770 return null; 8771 } 8772 8773 /** 8774 * Views should implement this if the view itself is going to add items to 8775 * the context menu. 8776 * 8777 * @param menu the context menu to populate 8778 */ 8779 protected void onCreateContextMenu(ContextMenu menu) { 8780 } 8781 8782 /** 8783 * Implement this method to handle trackball motion events. The 8784 * <em>relative</em> movement of the trackball since the last event 8785 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 8786 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 8787 * that a movement of 1 corresponds to the user pressing one DPAD key (so 8788 * they will often be fractional values, representing the more fine-grained 8789 * movement information available from a trackball). 8790 * 8791 * @param event The motion event. 8792 * @return True if the event was handled, false otherwise. 8793 */ 8794 public boolean onTrackballEvent(MotionEvent event) { 8795 return false; 8796 } 8797 8798 /** 8799 * Implement this method to handle generic motion events. 8800 * <p> 8801 * Generic motion events describe joystick movements, mouse hovers, track pad 8802 * touches, scroll wheel movements and other input events. The 8803 * {@link MotionEvent#getSource() source} of the motion event specifies 8804 * the class of input that was received. Implementations of this method 8805 * must examine the bits in the source before processing the event. 8806 * The following code example shows how this is done. 8807 * </p><p> 8808 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 8809 * are delivered to the view under the pointer. All other generic motion events are 8810 * delivered to the focused view. 8811 * </p> 8812 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 8813 * if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) { 8814 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 8815 * // process the joystick movement... 8816 * return true; 8817 * } 8818 * } 8819 * if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) { 8820 * switch (event.getAction()) { 8821 * case MotionEvent.ACTION_HOVER_MOVE: 8822 * // process the mouse hover movement... 8823 * return true; 8824 * case MotionEvent.ACTION_SCROLL: 8825 * // process the scroll wheel movement... 8826 * return true; 8827 * } 8828 * } 8829 * return super.onGenericMotionEvent(event); 8830 * }</pre> 8831 * 8832 * @param event The generic motion event being processed. 8833 * @return True if the event was handled, false otherwise. 8834 */ 8835 public boolean onGenericMotionEvent(MotionEvent event) { 8836 return false; 8837 } 8838 8839 /** 8840 * Implement this method to handle hover events. 8841 * <p> 8842 * This method is called whenever a pointer is hovering into, over, or out of the 8843 * bounds of a view and the view is not currently being touched. 8844 * Hover events are represented as pointer events with action 8845 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 8846 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 8847 * </p> 8848 * <ul> 8849 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 8850 * when the pointer enters the bounds of the view.</li> 8851 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 8852 * when the pointer has already entered the bounds of the view and has moved.</li> 8853 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 8854 * when the pointer has exited the bounds of the view or when the pointer is 8855 * about to go down due to a button click, tap, or similar user action that 8856 * causes the view to be touched.</li> 8857 * </ul> 8858 * <p> 8859 * The view should implement this method to return true to indicate that it is 8860 * handling the hover event, such as by changing its drawable state. 8861 * </p><p> 8862 * The default implementation calls {@link #setHovered} to update the hovered state 8863 * of the view when a hover enter or hover exit event is received, if the view 8864 * is enabled and is clickable. The default implementation also sends hover 8865 * accessibility events. 8866 * </p> 8867 * 8868 * @param event The motion event that describes the hover. 8869 * @return True if the view handled the hover event. 8870 * 8871 * @see #isHovered 8872 * @see #setHovered 8873 * @see #onHoverChanged 8874 */ 8875 public boolean onHoverEvent(MotionEvent event) { 8876 // The root view may receive hover (or touch) events that are outside the bounds of 8877 // the window. This code ensures that we only send accessibility events for 8878 // hovers that are actually within the bounds of the root view. 8879 final int action = event.getActionMasked(); 8880 if (!mSendingHoverAccessibilityEvents) { 8881 if ((action == MotionEvent.ACTION_HOVER_ENTER 8882 || action == MotionEvent.ACTION_HOVER_MOVE) 8883 && !hasHoveredChild() 8884 && pointInView(event.getX(), event.getY())) { 8885 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 8886 mSendingHoverAccessibilityEvents = true; 8887 } 8888 } else { 8889 if (action == MotionEvent.ACTION_HOVER_EXIT 8890 || (action == MotionEvent.ACTION_MOVE 8891 && !pointInView(event.getX(), event.getY()))) { 8892 mSendingHoverAccessibilityEvents = false; 8893 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 8894 // If the window does not have input focus we take away accessibility 8895 // focus as soon as the user stop hovering over the view. 8896 if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) { 8897 getViewRootImpl().setAccessibilityFocus(null, null); 8898 } 8899 } 8900 } 8901 8902 if (isHoverable()) { 8903 switch (action) { 8904 case MotionEvent.ACTION_HOVER_ENTER: 8905 setHovered(true); 8906 break; 8907 case MotionEvent.ACTION_HOVER_EXIT: 8908 setHovered(false); 8909 break; 8910 } 8911 8912 // Dispatch the event to onGenericMotionEvent before returning true. 8913 // This is to provide compatibility with existing applications that 8914 // handled HOVER_MOVE events in onGenericMotionEvent and that would 8915 // break because of the new default handling for hoverable views 8916 // in onHoverEvent. 8917 // Note that onGenericMotionEvent will be called by default when 8918 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 8919 dispatchGenericMotionEventInternal(event); 8920 // The event was already handled by calling setHovered(), so always 8921 // return true. 8922 return true; 8923 } 8924 8925 return false; 8926 } 8927 8928 /** 8929 * Returns true if the view should handle {@link #onHoverEvent} 8930 * by calling {@link #setHovered} to change its hovered state. 8931 * 8932 * @return True if the view is hoverable. 8933 */ 8934 private boolean isHoverable() { 8935 final int viewFlags = mViewFlags; 8936 if ((viewFlags & ENABLED_MASK) == DISABLED) { 8937 return false; 8938 } 8939 8940 return (viewFlags & CLICKABLE) == CLICKABLE 8941 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 8942 } 8943 8944 /** 8945 * Returns true if the view is currently hovered. 8946 * 8947 * @return True if the view is currently hovered. 8948 * 8949 * @see #setHovered 8950 * @see #onHoverChanged 8951 */ 8952 @ViewDebug.ExportedProperty 8953 public boolean isHovered() { 8954 return (mPrivateFlags & PFLAG_HOVERED) != 0; 8955 } 8956 8957 /** 8958 * Sets whether the view is currently hovered. 8959 * <p> 8960 * Calling this method also changes the drawable state of the view. This 8961 * enables the view to react to hover by using different drawable resources 8962 * to change its appearance. 8963 * </p><p> 8964 * The {@link #onHoverChanged} method is called when the hovered state changes. 8965 * </p> 8966 * 8967 * @param hovered True if the view is hovered. 8968 * 8969 * @see #isHovered 8970 * @see #onHoverChanged 8971 */ 8972 public void setHovered(boolean hovered) { 8973 if (hovered) { 8974 if ((mPrivateFlags & PFLAG_HOVERED) == 0) { 8975 mPrivateFlags |= PFLAG_HOVERED; 8976 refreshDrawableState(); 8977 onHoverChanged(true); 8978 } 8979 } else { 8980 if ((mPrivateFlags & PFLAG_HOVERED) != 0) { 8981 mPrivateFlags &= ~PFLAG_HOVERED; 8982 refreshDrawableState(); 8983 onHoverChanged(false); 8984 } 8985 } 8986 } 8987 8988 /** 8989 * Implement this method to handle hover state changes. 8990 * <p> 8991 * This method is called whenever the hover state changes as a result of a 8992 * call to {@link #setHovered}. 8993 * </p> 8994 * 8995 * @param hovered The current hover state, as returned by {@link #isHovered}. 8996 * 8997 * @see #isHovered 8998 * @see #setHovered 8999 */ 9000 public void onHoverChanged(boolean hovered) { 9001 } 9002 9003 /** 9004 * Implement this method to handle touch screen motion events. 9005 * <p> 9006 * If this method is used to detect click actions, it is recommended that 9007 * the actions be performed by implementing and calling 9008 * {@link #performClick()}. This will ensure consistent system behavior, 9009 * including: 9010 * <ul> 9011 * <li>obeying click sound preferences 9012 * <li>dispatching OnClickListener calls 9013 * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when 9014 * accessibility features are enabled 9015 * </ul> 9016 * 9017 * @param event The motion event. 9018 * @return True if the event was handled, false otherwise. 9019 */ 9020 public boolean onTouchEvent(MotionEvent event) { 9021 final float x = event.getX(); 9022 final float y = event.getY(); 9023 final int viewFlags = mViewFlags; 9024 9025 if ((viewFlags & ENABLED_MASK) == DISABLED) { 9026 if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { 9027 clearHotspot(R.attr.state_pressed); 9028 setPressed(false); 9029 } 9030 // A disabled view that is clickable still consumes the touch 9031 // events, it just doesn't respond to them. 9032 return (((viewFlags & CLICKABLE) == CLICKABLE || 9033 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); 9034 } 9035 9036 if (mTouchDelegate != null) { 9037 if (mTouchDelegate.onTouchEvent(event)) { 9038 return true; 9039 } 9040 } 9041 9042 if (((viewFlags & CLICKABLE) == CLICKABLE || 9043 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { 9044 switch (event.getAction()) { 9045 case MotionEvent.ACTION_UP: 9046 boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; 9047 if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { 9048 // take focus if we don't have it already and we should in 9049 // touch mode. 9050 boolean focusTaken = false; 9051 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 9052 focusTaken = requestFocus(); 9053 } 9054 9055 if (prepressed) { 9056 // The button is being released before we actually 9057 // showed it as pressed. Make it show the pressed 9058 // state now (before scheduling the click) to ensure 9059 // the user sees it. 9060 setHotspot(R.attr.state_pressed, x, y); 9061 setPressed(true); 9062 } 9063 9064 if (!mHasPerformedLongPress) { 9065 // This is a tap, so remove the longpress check 9066 removeLongPressCallback(); 9067 9068 // Only perform take click actions if we were in the pressed state 9069 if (!focusTaken) { 9070 // Use a Runnable and post this rather than calling 9071 // performClick directly. This lets other visual state 9072 // of the view update before click actions start. 9073 if (mPerformClick == null) { 9074 mPerformClick = new PerformClick(); 9075 } 9076 if (!post(mPerformClick)) { 9077 performClick(); 9078 } 9079 } 9080 } 9081 9082 if (mUnsetPressedState == null) { 9083 mUnsetPressedState = new UnsetPressedState(); 9084 } 9085 9086 if (prepressed) { 9087 postDelayed(mUnsetPressedState, 9088 ViewConfiguration.getPressedStateDuration()); 9089 } else if (!post(mUnsetPressedState)) { 9090 // If the post failed, unpress right now 9091 mUnsetPressedState.run(); 9092 } 9093 9094 removeTapCallback(); 9095 } 9096 break; 9097 9098 case MotionEvent.ACTION_DOWN: 9099 mHasPerformedLongPress = false; 9100 9101 if (performButtonActionOnTouchDown(event)) { 9102 break; 9103 } 9104 9105 // Walk up the hierarchy to determine if we're inside a scrolling container. 9106 boolean isInScrollingContainer = isInScrollingContainer(); 9107 9108 // For views inside a scrolling container, delay the pressed feedback for 9109 // a short period in case this is a scroll. 9110 if (isInScrollingContainer) { 9111 mPrivateFlags |= PFLAG_PREPRESSED; 9112 if (mPendingCheckForTap == null) { 9113 mPendingCheckForTap = new CheckForTap(); 9114 } 9115 mPendingCheckForTap.x = event.getX(); 9116 mPendingCheckForTap.y = event.getY(); 9117 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 9118 } else { 9119 // Not inside a scrolling container, so show the feedback right away 9120 setHotspot(R.attr.state_pressed, x, y); 9121 setPressed(true); 9122 checkForLongClick(0); 9123 } 9124 break; 9125 9126 case MotionEvent.ACTION_CANCEL: 9127 clearHotspot(R.attr.state_pressed); 9128 setPressed(false); 9129 removeTapCallback(); 9130 removeLongPressCallback(); 9131 break; 9132 9133 case MotionEvent.ACTION_MOVE: 9134 setHotspot(R.attr.state_pressed, x, y); 9135 9136 // Be lenient about moving outside of buttons 9137 if (!pointInView(x, y, mTouchSlop)) { 9138 // Outside button 9139 removeTapCallback(); 9140 if ((mPrivateFlags & PFLAG_PRESSED) != 0) { 9141 // Remove any future long press/tap checks 9142 removeLongPressCallback(); 9143 9144 setPressed(false); 9145 } 9146 } 9147 break; 9148 } 9149 9150 return true; 9151 } 9152 9153 return false; 9154 } 9155 9156 private void setHotspot(int id, float x, float y) { 9157 final Drawable bg = mBackground; 9158 if (bg != null && bg.supportsHotspots()) { 9159 bg.setHotspot(id, x, y); 9160 } 9161 } 9162 9163 private void clearHotspot(int id) { 9164 final Drawable bg = mBackground; 9165 if (bg != null && bg.supportsHotspots()) { 9166 bg.removeHotspot(id); 9167 } 9168 } 9169 9170 /** 9171 * @hide 9172 */ 9173 public boolean isInScrollingContainer() { 9174 ViewParent p = getParent(); 9175 while (p != null && p instanceof ViewGroup) { 9176 if (((ViewGroup) p).shouldDelayChildPressedState()) { 9177 return true; 9178 } 9179 p = p.getParent(); 9180 } 9181 return false; 9182 } 9183 9184 /** 9185 * Remove the longpress detection timer. 9186 */ 9187 private void removeLongPressCallback() { 9188 if (mPendingCheckForLongPress != null) { 9189 removeCallbacks(mPendingCheckForLongPress); 9190 } 9191 } 9192 9193 /** 9194 * Remove the pending click action 9195 */ 9196 private void removePerformClickCallback() { 9197 if (mPerformClick != null) { 9198 removeCallbacks(mPerformClick); 9199 } 9200 } 9201 9202 /** 9203 * Remove the prepress detection timer. 9204 */ 9205 private void removeUnsetPressCallback() { 9206 if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) { 9207 setPressed(false); 9208 removeCallbacks(mUnsetPressedState); 9209 } 9210 } 9211 9212 /** 9213 * Remove the tap detection timer. 9214 */ 9215 private void removeTapCallback() { 9216 if (mPendingCheckForTap != null) { 9217 mPrivateFlags &= ~PFLAG_PREPRESSED; 9218 removeCallbacks(mPendingCheckForTap); 9219 } 9220 } 9221 9222 /** 9223 * Cancels a pending long press. Your subclass can use this if you 9224 * want the context menu to come up if the user presses and holds 9225 * at the same place, but you don't want it to come up if they press 9226 * and then move around enough to cause scrolling. 9227 */ 9228 public void cancelLongPress() { 9229 removeLongPressCallback(); 9230 9231 /* 9232 * The prepressed state handled by the tap callback is a display 9233 * construct, but the tap callback will post a long press callback 9234 * less its own timeout. Remove it here. 9235 */ 9236 removeTapCallback(); 9237 } 9238 9239 /** 9240 * Remove the pending callback for sending a 9241 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 9242 */ 9243 private void removeSendViewScrolledAccessibilityEventCallback() { 9244 if (mSendViewScrolledAccessibilityEvent != null) { 9245 removeCallbacks(mSendViewScrolledAccessibilityEvent); 9246 mSendViewScrolledAccessibilityEvent.mIsPending = false; 9247 } 9248 } 9249 9250 /** 9251 * Sets the TouchDelegate for this View. 9252 */ 9253 public void setTouchDelegate(TouchDelegate delegate) { 9254 mTouchDelegate = delegate; 9255 } 9256 9257 /** 9258 * Gets the TouchDelegate for this View. 9259 */ 9260 public TouchDelegate getTouchDelegate() { 9261 return mTouchDelegate; 9262 } 9263 9264 /** 9265 * Set flags controlling behavior of this view. 9266 * 9267 * @param flags Constant indicating the value which should be set 9268 * @param mask Constant indicating the bit range that should be changed 9269 */ 9270 void setFlags(int flags, int mask) { 9271 final boolean accessibilityEnabled = 9272 AccessibilityManager.getInstance(mContext).isEnabled(); 9273 final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility(); 9274 9275 int old = mViewFlags; 9276 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 9277 9278 int changed = mViewFlags ^ old; 9279 if (changed == 0) { 9280 return; 9281 } 9282 int privateFlags = mPrivateFlags; 9283 9284 /* Check if the FOCUSABLE bit has changed */ 9285 if (((changed & FOCUSABLE_MASK) != 0) && 9286 ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) { 9287 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 9288 && ((privateFlags & PFLAG_FOCUSED) != 0)) { 9289 /* Give up focus if we are no longer focusable */ 9290 clearFocus(); 9291 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 9292 && ((privateFlags & PFLAG_FOCUSED) == 0)) { 9293 /* 9294 * Tell the view system that we are now available to take focus 9295 * if no one else already has it. 9296 */ 9297 if (mParent != null) mParent.focusableViewAvailable(this); 9298 } 9299 } 9300 9301 final int newVisibility = flags & VISIBILITY_MASK; 9302 if (newVisibility == VISIBLE) { 9303 if ((changed & VISIBILITY_MASK) != 0) { 9304 /* 9305 * If this view is becoming visible, invalidate it in case it changed while 9306 * it was not visible. Marking it drawn ensures that the invalidation will 9307 * go through. 9308 */ 9309 mPrivateFlags |= PFLAG_DRAWN; 9310 invalidate(true); 9311 9312 needGlobalAttributesUpdate(true); 9313 9314 // a view becoming visible is worth notifying the parent 9315 // about in case nothing has focus. even if this specific view 9316 // isn't focusable, it may contain something that is, so let 9317 // the root view try to give this focus if nothing else does. 9318 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 9319 mParent.focusableViewAvailable(this); 9320 } 9321 } 9322 } 9323 9324 /* Check if the GONE bit has changed */ 9325 if ((changed & GONE) != 0) { 9326 needGlobalAttributesUpdate(false); 9327 requestLayout(); 9328 9329 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 9330 if (hasFocus()) clearFocus(); 9331 clearAccessibilityFocus(); 9332 destroyDrawingCache(); 9333 if (mParent instanceof View) { 9334 // GONE views noop invalidation, so invalidate the parent 9335 ((View) mParent).invalidate(true); 9336 } 9337 // Mark the view drawn to ensure that it gets invalidated properly the next 9338 // time it is visible and gets invalidated 9339 mPrivateFlags |= PFLAG_DRAWN; 9340 } 9341 if (mAttachInfo != null) { 9342 mAttachInfo.mViewVisibilityChanged = true; 9343 } 9344 } 9345 9346 /* Check if the VISIBLE bit has changed */ 9347 if ((changed & INVISIBLE) != 0) { 9348 needGlobalAttributesUpdate(false); 9349 /* 9350 * If this view is becoming invisible, set the DRAWN flag so that 9351 * the next invalidate() will not be skipped. 9352 */ 9353 mPrivateFlags |= PFLAG_DRAWN; 9354 9355 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) { 9356 // root view becoming invisible shouldn't clear focus and accessibility focus 9357 if (getRootView() != this) { 9358 if (hasFocus()) clearFocus(); 9359 clearAccessibilityFocus(); 9360 } 9361 } 9362 if (mAttachInfo != null) { 9363 mAttachInfo.mViewVisibilityChanged = true; 9364 } 9365 } 9366 9367 if ((changed & VISIBILITY_MASK) != 0) { 9368 // If the view is invisible, cleanup its display list to free up resources 9369 if (newVisibility != VISIBLE && mAttachInfo != null) { 9370 cleanupDraw(); 9371 } 9372 9373 if (mParent instanceof ViewGroup) { 9374 ((ViewGroup) mParent).onChildVisibilityChanged(this, 9375 (changed & VISIBILITY_MASK), newVisibility); 9376 ((View) mParent).invalidate(true); 9377 } else if (mParent != null) { 9378 mParent.invalidateChild(this, null); 9379 } 9380 dispatchVisibilityChanged(this, newVisibility); 9381 9382 notifySubtreeAccessibilityStateChangedIfNeeded(); 9383 } 9384 9385 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 9386 destroyDrawingCache(); 9387 } 9388 9389 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 9390 destroyDrawingCache(); 9391 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 9392 invalidateParentCaches(); 9393 } 9394 9395 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 9396 destroyDrawingCache(); 9397 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 9398 } 9399 9400 if ((changed & DRAW_MASK) != 0) { 9401 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 9402 if (mBackground != null) { 9403 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 9404 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 9405 } else { 9406 mPrivateFlags |= PFLAG_SKIP_DRAW; 9407 } 9408 } else { 9409 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 9410 } 9411 requestLayout(); 9412 invalidate(true); 9413 } 9414 9415 if ((changed & KEEP_SCREEN_ON) != 0) { 9416 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 9417 mParent.recomputeViewAttributes(this); 9418 } 9419 } 9420 9421 if (accessibilityEnabled) { 9422 if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0 9423 || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) { 9424 if (oldIncludeForAccessibility != includeForAccessibility()) { 9425 notifySubtreeAccessibilityStateChangedIfNeeded(); 9426 } else { 9427 notifyViewAccessibilityStateChangedIfNeeded( 9428 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9429 } 9430 } else if ((changed & ENABLED_MASK) != 0) { 9431 notifyViewAccessibilityStateChangedIfNeeded( 9432 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9433 } 9434 } 9435 } 9436 9437 /** 9438 * Change the view's z order in the tree, so it's on top of other sibling 9439 * views. This ordering change may affect layout, if the parent container 9440 * uses an order-dependent layout scheme (e.g., LinearLayout). Prior 9441 * to {@link android.os.Build.VERSION_CODES#KITKAT} this 9442 * method should be followed by calls to {@link #requestLayout()} and 9443 * {@link View#invalidate()} on the view's parent to force the parent to redraw 9444 * with the new child ordering. 9445 * 9446 * @see ViewGroup#bringChildToFront(View) 9447 */ 9448 public void bringToFront() { 9449 if (mParent != null) { 9450 mParent.bringChildToFront(this); 9451 } 9452 } 9453 9454 /** 9455 * This is called in response to an internal scroll in this view (i.e., the 9456 * view scrolled its own contents). This is typically as a result of 9457 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 9458 * called. 9459 * 9460 * @param l Current horizontal scroll origin. 9461 * @param t Current vertical scroll origin. 9462 * @param oldl Previous horizontal scroll origin. 9463 * @param oldt Previous vertical scroll origin. 9464 */ 9465 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 9466 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 9467 postSendViewScrolledAccessibilityEventCallback(); 9468 } 9469 9470 mBackgroundSizeChanged = true; 9471 9472 final AttachInfo ai = mAttachInfo; 9473 if (ai != null) { 9474 ai.mViewScrollChanged = true; 9475 } 9476 } 9477 9478 /** 9479 * Interface definition for a callback to be invoked when the layout bounds of a view 9480 * changes due to layout processing. 9481 */ 9482 public interface OnLayoutChangeListener { 9483 /** 9484 * Called when the layout bounds of a view changes due to layout processing. 9485 * 9486 * @param v The view whose bounds have changed. 9487 * @param left The new value of the view's left property. 9488 * @param top The new value of the view's top property. 9489 * @param right The new value of the view's right property. 9490 * @param bottom The new value of the view's bottom property. 9491 * @param oldLeft The previous value of the view's left property. 9492 * @param oldTop The previous value of the view's top property. 9493 * @param oldRight The previous value of the view's right property. 9494 * @param oldBottom The previous value of the view's bottom property. 9495 */ 9496 void onLayoutChange(View v, int left, int top, int right, int bottom, 9497 int oldLeft, int oldTop, int oldRight, int oldBottom); 9498 } 9499 9500 /** 9501 * This is called during layout when the size of this view has changed. If 9502 * you were just added to the view hierarchy, you're called with the old 9503 * values of 0. 9504 * 9505 * @param w Current width of this view. 9506 * @param h Current height of this view. 9507 * @param oldw Old width of this view. 9508 * @param oldh Old height of this view. 9509 */ 9510 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 9511 } 9512 9513 /** 9514 * Called by draw to draw the child views. This may be overridden 9515 * by derived classes to gain control just before its children are drawn 9516 * (but after its own view has been drawn). 9517 * @param canvas the canvas on which to draw the view 9518 */ 9519 protected void dispatchDraw(Canvas canvas) { 9520 9521 } 9522 9523 /** 9524 * Gets the parent of this view. Note that the parent is a 9525 * ViewParent and not necessarily a View. 9526 * 9527 * @return Parent of this view. 9528 */ 9529 public final ViewParent getParent() { 9530 return mParent; 9531 } 9532 9533 /** 9534 * Set the horizontal scrolled position of your view. This will cause a call to 9535 * {@link #onScrollChanged(int, int, int, int)} and the view will be 9536 * invalidated. 9537 * @param value the x position to scroll to 9538 */ 9539 public void setScrollX(int value) { 9540 scrollTo(value, mScrollY); 9541 } 9542 9543 /** 9544 * Set the vertical scrolled position of your view. This will cause a call to 9545 * {@link #onScrollChanged(int, int, int, int)} and the view will be 9546 * invalidated. 9547 * @param value the y position to scroll to 9548 */ 9549 public void setScrollY(int value) { 9550 scrollTo(mScrollX, value); 9551 } 9552 9553 /** 9554 * Return the scrolled left position of this view. This is the left edge of 9555 * the displayed part of your view. You do not need to draw any pixels 9556 * farther left, since those are outside of the frame of your view on 9557 * screen. 9558 * 9559 * @return The left edge of the displayed part of your view, in pixels. 9560 */ 9561 public final int getScrollX() { 9562 return mScrollX; 9563 } 9564 9565 /** 9566 * Return the scrolled top position of this view. This is the top edge of 9567 * the displayed part of your view. You do not need to draw any pixels above 9568 * it, since those are outside of the frame of your view on screen. 9569 * 9570 * @return The top edge of the displayed part of your view, in pixels. 9571 */ 9572 public final int getScrollY() { 9573 return mScrollY; 9574 } 9575 9576 /** 9577 * Return the width of the your view. 9578 * 9579 * @return The width of your view, in pixels. 9580 */ 9581 @ViewDebug.ExportedProperty(category = "layout") 9582 public final int getWidth() { 9583 return mRight - mLeft; 9584 } 9585 9586 /** 9587 * Return the height of your view. 9588 * 9589 * @return The height of your view, in pixels. 9590 */ 9591 @ViewDebug.ExportedProperty(category = "layout") 9592 public final int getHeight() { 9593 return mBottom - mTop; 9594 } 9595 9596 /** 9597 * Return the visible drawing bounds of your view. Fills in the output 9598 * rectangle with the values from getScrollX(), getScrollY(), 9599 * getWidth(), and getHeight(). These bounds do not account for any 9600 * transformation properties currently set on the view, such as 9601 * {@link #setScaleX(float)} or {@link #setRotation(float)}. 9602 * 9603 * @param outRect The (scrolled) drawing bounds of the view. 9604 */ 9605 public void getDrawingRect(Rect outRect) { 9606 outRect.left = mScrollX; 9607 outRect.top = mScrollY; 9608 outRect.right = mScrollX + (mRight - mLeft); 9609 outRect.bottom = mScrollY + (mBottom - mTop); 9610 } 9611 9612 /** 9613 * Like {@link #getMeasuredWidthAndState()}, but only returns the 9614 * raw width component (that is the result is masked by 9615 * {@link #MEASURED_SIZE_MASK}). 9616 * 9617 * @return The raw measured width of this view. 9618 */ 9619 public final int getMeasuredWidth() { 9620 return mMeasuredWidth & MEASURED_SIZE_MASK; 9621 } 9622 9623 /** 9624 * Return the full width measurement information for this view as computed 9625 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 9626 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 9627 * This should be used during measurement and layout calculations only. Use 9628 * {@link #getWidth()} to see how wide a view is after layout. 9629 * 9630 * @return The measured width of this view as a bit mask. 9631 */ 9632 public final int getMeasuredWidthAndState() { 9633 return mMeasuredWidth; 9634 } 9635 9636 /** 9637 * Like {@link #getMeasuredHeightAndState()}, but only returns the 9638 * raw width component (that is the result is masked by 9639 * {@link #MEASURED_SIZE_MASK}). 9640 * 9641 * @return The raw measured height of this view. 9642 */ 9643 public final int getMeasuredHeight() { 9644 return mMeasuredHeight & MEASURED_SIZE_MASK; 9645 } 9646 9647 /** 9648 * Return the full height measurement information for this view as computed 9649 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 9650 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 9651 * This should be used during measurement and layout calculations only. Use 9652 * {@link #getHeight()} to see how wide a view is after layout. 9653 * 9654 * @return The measured width of this view as a bit mask. 9655 */ 9656 public final int getMeasuredHeightAndState() { 9657 return mMeasuredHeight; 9658 } 9659 9660 /** 9661 * Return only the state bits of {@link #getMeasuredWidthAndState()} 9662 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 9663 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 9664 * and the height component is at the shifted bits 9665 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 9666 */ 9667 public final int getMeasuredState() { 9668 return (mMeasuredWidth&MEASURED_STATE_MASK) 9669 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 9670 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 9671 } 9672 9673 /** 9674 * The transform matrix of this view, which is calculated based on the current 9675 * roation, scale, and pivot properties. 9676 * 9677 * @see #getRotation() 9678 * @see #getScaleX() 9679 * @see #getScaleY() 9680 * @see #getPivotX() 9681 * @see #getPivotY() 9682 * @return The current transform matrix for the view 9683 */ 9684 public Matrix getMatrix() { 9685 if (mTransformationInfo != null) { 9686 updateMatrix(); 9687 return mTransformationInfo.mMatrix; 9688 } 9689 return Matrix.IDENTITY_MATRIX; 9690 } 9691 9692 /** 9693 * Utility function to determine if the value is far enough away from zero to be 9694 * considered non-zero. 9695 * @param value A floating point value to check for zero-ness 9696 * @return whether the passed-in value is far enough away from zero to be considered non-zero 9697 */ 9698 private static boolean nonzero(float value) { 9699 return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON); 9700 } 9701 9702 /** 9703 * Returns true if the transform matrix is the identity matrix. 9704 * Recomputes the matrix if necessary. 9705 * 9706 * @return True if the transform matrix is the identity matrix, false otherwise. 9707 */ 9708 final boolean hasIdentityMatrix() { 9709 if (mTransformationInfo != null) { 9710 updateMatrix(); 9711 return mTransformationInfo.mMatrixIsIdentity; 9712 } 9713 return true; 9714 } 9715 9716 void ensureTransformationInfo() { 9717 if (mTransformationInfo == null) { 9718 mTransformationInfo = new TransformationInfo(); 9719 } 9720 } 9721 9722 void ensureRenderNode() { 9723 if (mRenderNode == null) { 9724 mRenderNode = RenderNode.create(getClass().getName()); 9725 } 9726 } 9727 9728 /** 9729 * Recomputes the transform matrix if necessary. 9730 */ 9731 private void updateMatrix() { 9732 final TransformationInfo info = mTransformationInfo; 9733 if (info == null) { 9734 return; 9735 } 9736 if (info.mMatrixDirty) { 9737 // transform-related properties have changed since the last time someone 9738 // asked for the matrix; recalculate it with the current values 9739 9740 // Figure out if we need to update the pivot point 9741 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 9742 if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) { 9743 info.mPrevWidth = mRight - mLeft; 9744 info.mPrevHeight = mBottom - mTop; 9745 info.mPivotX = info.mPrevWidth / 2f; 9746 info.mPivotY = info.mPrevHeight / 2f; 9747 } 9748 } 9749 info.mMatrix.reset(); 9750 if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) { 9751 info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY); 9752 info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY); 9753 info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY); 9754 } else { 9755 if (info.mCamera == null) { 9756 info.mCamera = new Camera(); 9757 info.matrix3D = new Matrix(); 9758 } 9759 info.mCamera.save(); 9760 info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY); 9761 info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation); 9762 info.mCamera.getMatrix(info.matrix3D); 9763 info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY); 9764 info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX, 9765 info.mPivotY + info.mTranslationY); 9766 info.mMatrix.postConcat(info.matrix3D); 9767 info.mCamera.restore(); 9768 } 9769 info.mMatrixDirty = false; 9770 info.mMatrixIsIdentity = info.mMatrix.isIdentity(); 9771 info.mInverseMatrixDirty = true; 9772 } 9773 } 9774 9775 /** 9776 * Utility method to retrieve the inverse of the current mMatrix property. 9777 * We cache the matrix to avoid recalculating it when transform properties 9778 * have not changed. 9779 * 9780 * @return The inverse of the current matrix of this view. 9781 */ 9782 final Matrix getInverseMatrix() { 9783 final TransformationInfo info = mTransformationInfo; 9784 if (info != null) { 9785 updateMatrix(); 9786 if (info.mInverseMatrixDirty) { 9787 if (info.mInverseMatrix == null) { 9788 info.mInverseMatrix = new Matrix(); 9789 } 9790 info.mMatrix.invert(info.mInverseMatrix); 9791 info.mInverseMatrixDirty = false; 9792 } 9793 return info.mInverseMatrix; 9794 } 9795 return Matrix.IDENTITY_MATRIX; 9796 } 9797 9798 /** 9799 * Gets the distance along the Z axis from the camera to this view. 9800 * 9801 * @see #setCameraDistance(float) 9802 * 9803 * @return The distance along the Z axis. 9804 */ 9805 public float getCameraDistance() { 9806 ensureTransformationInfo(); 9807 final float dpi = mResources.getDisplayMetrics().densityDpi; 9808 final TransformationInfo info = mTransformationInfo; 9809 if (info.mCamera == null) { 9810 info.mCamera = new Camera(); 9811 info.matrix3D = new Matrix(); 9812 } 9813 return -(info.mCamera.getLocationZ() * dpi); 9814 } 9815 9816 /** 9817 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 9818 * views are drawn) from the camera to this view. The camera's distance 9819 * affects 3D transformations, for instance rotations around the X and Y 9820 * axis. If the rotationX or rotationY properties are changed and this view is 9821 * large (more than half the size of the screen), it is recommended to always 9822 * use a camera distance that's greater than the height (X axis rotation) or 9823 * the width (Y axis rotation) of this view.</p> 9824 * 9825 * <p>The distance of the camera from the view plane can have an affect on the 9826 * perspective distortion of the view when it is rotated around the x or y axis. 9827 * For example, a large distance will result in a large viewing angle, and there 9828 * will not be much perspective distortion of the view as it rotates. A short 9829 * distance may cause much more perspective distortion upon rotation, and can 9830 * also result in some drawing artifacts if the rotated view ends up partially 9831 * behind the camera (which is why the recommendation is to use a distance at 9832 * least as far as the size of the view, if the view is to be rotated.)</p> 9833 * 9834 * <p>The distance is expressed in "depth pixels." The default distance depends 9835 * on the screen density. For instance, on a medium density display, the 9836 * default distance is 1280. On a high density display, the default distance 9837 * is 1920.</p> 9838 * 9839 * <p>If you want to specify a distance that leads to visually consistent 9840 * results across various densities, use the following formula:</p> 9841 * <pre> 9842 * float scale = context.getResources().getDisplayMetrics().density; 9843 * view.setCameraDistance(distance * scale); 9844 * </pre> 9845 * 9846 * <p>The density scale factor of a high density display is 1.5, 9847 * and 1920 = 1280 * 1.5.</p> 9848 * 9849 * @param distance The distance in "depth pixels", if negative the opposite 9850 * value is used 9851 * 9852 * @see #setRotationX(float) 9853 * @see #setRotationY(float) 9854 */ 9855 public void setCameraDistance(float distance) { 9856 invalidateViewProperty(true, false); 9857 9858 ensureTransformationInfo(); 9859 final float dpi = mResources.getDisplayMetrics().densityDpi; 9860 final TransformationInfo info = mTransformationInfo; 9861 if (info.mCamera == null) { 9862 info.mCamera = new Camera(); 9863 info.matrix3D = new Matrix(); 9864 } 9865 9866 info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi); 9867 info.mMatrixDirty = true; 9868 9869 invalidateViewProperty(false, false); 9870 if (mRenderNode != null) { 9871 mRenderNode.setCameraDistance(-Math.abs(distance) / dpi); 9872 } 9873 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9874 // View was rejected last time it was drawn by its parent; this may have changed 9875 invalidateParentIfNeeded(); 9876 } 9877 } 9878 9879 /** 9880 * The degrees that the view is rotated around the pivot point. 9881 * 9882 * @see #setRotation(float) 9883 * @see #getPivotX() 9884 * @see #getPivotY() 9885 * 9886 * @return The degrees of rotation. 9887 */ 9888 @ViewDebug.ExportedProperty(category = "drawing") 9889 public float getRotation() { 9890 return mTransformationInfo != null ? mTransformationInfo.mRotation : 0; 9891 } 9892 9893 /** 9894 * Sets the degrees that the view is rotated around the pivot point. Increasing values 9895 * result in clockwise rotation. 9896 * 9897 * @param rotation The degrees of rotation. 9898 * 9899 * @see #getRotation() 9900 * @see #getPivotX() 9901 * @see #getPivotY() 9902 * @see #setRotationX(float) 9903 * @see #setRotationY(float) 9904 * 9905 * @attr ref android.R.styleable#View_rotation 9906 */ 9907 public void setRotation(float rotation) { 9908 ensureTransformationInfo(); 9909 final TransformationInfo info = mTransformationInfo; 9910 if (info.mRotation != rotation) { 9911 // Double-invalidation is necessary to capture view's old and new areas 9912 invalidateViewProperty(true, false); 9913 info.mRotation = rotation; 9914 info.mMatrixDirty = true; 9915 invalidateViewProperty(false, true); 9916 if (mRenderNode != null) { 9917 mRenderNode.setRotation(rotation); 9918 } 9919 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9920 // View was rejected last time it was drawn by its parent; this may have changed 9921 invalidateParentIfNeeded(); 9922 } 9923 } 9924 } 9925 9926 /** 9927 * The degrees that the view is rotated around the vertical axis through the pivot point. 9928 * 9929 * @see #getPivotX() 9930 * @see #getPivotY() 9931 * @see #setRotationY(float) 9932 * 9933 * @return The degrees of Y rotation. 9934 */ 9935 @ViewDebug.ExportedProperty(category = "drawing") 9936 public float getRotationY() { 9937 return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0; 9938 } 9939 9940 /** 9941 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 9942 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 9943 * down the y axis. 9944 * 9945 * When rotating large views, it is recommended to adjust the camera distance 9946 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 9947 * 9948 * @param rotationY The degrees of Y rotation. 9949 * 9950 * @see #getRotationY() 9951 * @see #getPivotX() 9952 * @see #getPivotY() 9953 * @see #setRotation(float) 9954 * @see #setRotationX(float) 9955 * @see #setCameraDistance(float) 9956 * 9957 * @attr ref android.R.styleable#View_rotationY 9958 */ 9959 public void setRotationY(float rotationY) { 9960 ensureTransformationInfo(); 9961 final TransformationInfo info = mTransformationInfo; 9962 if (info.mRotationY != rotationY) { 9963 invalidateViewProperty(true, false); 9964 info.mRotationY = rotationY; 9965 info.mMatrixDirty = true; 9966 invalidateViewProperty(false, true); 9967 if (mRenderNode != null) { 9968 mRenderNode.setRotationY(rotationY); 9969 } 9970 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9971 // View was rejected last time it was drawn by its parent; this may have changed 9972 invalidateParentIfNeeded(); 9973 } 9974 } 9975 } 9976 9977 /** 9978 * The degrees that the view is rotated around the horizontal axis through the pivot point. 9979 * 9980 * @see #getPivotX() 9981 * @see #getPivotY() 9982 * @see #setRotationX(float) 9983 * 9984 * @return The degrees of X rotation. 9985 */ 9986 @ViewDebug.ExportedProperty(category = "drawing") 9987 public float getRotationX() { 9988 return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0; 9989 } 9990 9991 /** 9992 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 9993 * Increasing values result in clockwise rotation from the viewpoint of looking down the 9994 * x axis. 9995 * 9996 * When rotating large views, it is recommended to adjust the camera distance 9997 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 9998 * 9999 * @param rotationX The degrees of X rotation. 10000 * 10001 * @see #getRotationX() 10002 * @see #getPivotX() 10003 * @see #getPivotY() 10004 * @see #setRotation(float) 10005 * @see #setRotationY(float) 10006 * @see #setCameraDistance(float) 10007 * 10008 * @attr ref android.R.styleable#View_rotationX 10009 */ 10010 public void setRotationX(float rotationX) { 10011 ensureTransformationInfo(); 10012 final TransformationInfo info = mTransformationInfo; 10013 if (info.mRotationX != rotationX) { 10014 invalidateViewProperty(true, false); 10015 info.mRotationX = rotationX; 10016 info.mMatrixDirty = true; 10017 invalidateViewProperty(false, true); 10018 if (mRenderNode != null) { 10019 mRenderNode.setRotationX(rotationX); 10020 } 10021 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10022 // View was rejected last time it was drawn by its parent; this may have changed 10023 invalidateParentIfNeeded(); 10024 } 10025 } 10026 } 10027 10028 /** 10029 * The amount that the view is scaled in x around the pivot point, as a proportion of 10030 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 10031 * 10032 * <p>By default, this is 1.0f. 10033 * 10034 * @see #getPivotX() 10035 * @see #getPivotY() 10036 * @return The scaling factor. 10037 */ 10038 @ViewDebug.ExportedProperty(category = "drawing") 10039 public float getScaleX() { 10040 return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1; 10041 } 10042 10043 /** 10044 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 10045 * the view's unscaled width. A value of 1 means that no scaling is applied. 10046 * 10047 * @param scaleX The scaling factor. 10048 * @see #getPivotX() 10049 * @see #getPivotY() 10050 * 10051 * @attr ref android.R.styleable#View_scaleX 10052 */ 10053 public void setScaleX(float scaleX) { 10054 ensureTransformationInfo(); 10055 final TransformationInfo info = mTransformationInfo; 10056 if (info.mScaleX != scaleX) { 10057 invalidateViewProperty(true, false); 10058 info.mScaleX = scaleX; 10059 info.mMatrixDirty = true; 10060 invalidateViewProperty(false, true); 10061 if (mRenderNode != null) { 10062 mRenderNode.setScaleX(scaleX); 10063 } 10064 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10065 // View was rejected last time it was drawn by its parent; this may have changed 10066 invalidateParentIfNeeded(); 10067 } 10068 } 10069 } 10070 10071 /** 10072 * The amount that the view is scaled in y around the pivot point, as a proportion of 10073 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 10074 * 10075 * <p>By default, this is 1.0f. 10076 * 10077 * @see #getPivotX() 10078 * @see #getPivotY() 10079 * @return The scaling factor. 10080 */ 10081 @ViewDebug.ExportedProperty(category = "drawing") 10082 public float getScaleY() { 10083 return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1; 10084 } 10085 10086 /** 10087 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 10088 * the view's unscaled width. A value of 1 means that no scaling is applied. 10089 * 10090 * @param scaleY The scaling factor. 10091 * @see #getPivotX() 10092 * @see #getPivotY() 10093 * 10094 * @attr ref android.R.styleable#View_scaleY 10095 */ 10096 public void setScaleY(float scaleY) { 10097 ensureTransformationInfo(); 10098 final TransformationInfo info = mTransformationInfo; 10099 if (info.mScaleY != scaleY) { 10100 invalidateViewProperty(true, false); 10101 info.mScaleY = scaleY; 10102 info.mMatrixDirty = true; 10103 invalidateViewProperty(false, true); 10104 if (mRenderNode != null) { 10105 mRenderNode.setScaleY(scaleY); 10106 } 10107 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10108 // View was rejected last time it was drawn by its parent; this may have changed 10109 invalidateParentIfNeeded(); 10110 } 10111 } 10112 } 10113 10114 /** 10115 * The x location of the point around which the view is {@link #setRotation(float) rotated} 10116 * and {@link #setScaleX(float) scaled}. 10117 * 10118 * @see #getRotation() 10119 * @see #getScaleX() 10120 * @see #getScaleY() 10121 * @see #getPivotY() 10122 * @return The x location of the pivot point. 10123 * 10124 * @attr ref android.R.styleable#View_transformPivotX 10125 */ 10126 @ViewDebug.ExportedProperty(category = "drawing") 10127 public float getPivotX() { 10128 return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0; 10129 } 10130 10131 /** 10132 * Sets the x location of the point around which the view is 10133 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 10134 * By default, the pivot point is centered on the object. 10135 * Setting this property disables this behavior and causes the view to use only the 10136 * explicitly set pivotX and pivotY values. 10137 * 10138 * @param pivotX The x location of the pivot point. 10139 * @see #getRotation() 10140 * @see #getScaleX() 10141 * @see #getScaleY() 10142 * @see #getPivotY() 10143 * 10144 * @attr ref android.R.styleable#View_transformPivotX 10145 */ 10146 public void setPivotX(float pivotX) { 10147 ensureTransformationInfo(); 10148 final TransformationInfo info = mTransformationInfo; 10149 boolean pivotSet = (mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 10150 PFLAG_PIVOT_EXPLICITLY_SET; 10151 if (info.mPivotX != pivotX || !pivotSet) { 10152 mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET; 10153 invalidateViewProperty(true, false); 10154 info.mPivotX = pivotX; 10155 info.mMatrixDirty = true; 10156 invalidateViewProperty(false, true); 10157 if (mRenderNode != null) { 10158 mRenderNode.setPivotX(pivotX); 10159 } 10160 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10161 // View was rejected last time it was drawn by its parent; this may have changed 10162 invalidateParentIfNeeded(); 10163 } 10164 } 10165 } 10166 10167 /** 10168 * The y location of the point around which the view is {@link #setRotation(float) rotated} 10169 * and {@link #setScaleY(float) scaled}. 10170 * 10171 * @see #getRotation() 10172 * @see #getScaleX() 10173 * @see #getScaleY() 10174 * @see #getPivotY() 10175 * @return The y location of the pivot point. 10176 * 10177 * @attr ref android.R.styleable#View_transformPivotY 10178 */ 10179 @ViewDebug.ExportedProperty(category = "drawing") 10180 public float getPivotY() { 10181 return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0; 10182 } 10183 10184 /** 10185 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 10186 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 10187 * Setting this property disables this behavior and causes the view to use only the 10188 * explicitly set pivotX and pivotY values. 10189 * 10190 * @param pivotY The y location of the pivot point. 10191 * @see #getRotation() 10192 * @see #getScaleX() 10193 * @see #getScaleY() 10194 * @see #getPivotY() 10195 * 10196 * @attr ref android.R.styleable#View_transformPivotY 10197 */ 10198 public void setPivotY(float pivotY) { 10199 ensureTransformationInfo(); 10200 final TransformationInfo info = mTransformationInfo; 10201 boolean pivotSet = (mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 10202 PFLAG_PIVOT_EXPLICITLY_SET; 10203 if (info.mPivotY != pivotY || !pivotSet) { 10204 mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET; 10205 invalidateViewProperty(true, false); 10206 info.mPivotY = pivotY; 10207 info.mMatrixDirty = true; 10208 invalidateViewProperty(false, true); 10209 if (mRenderNode != null) { 10210 mRenderNode.setPivotY(pivotY); 10211 } 10212 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10213 // View was rejected last time it was drawn by its parent; this may have changed 10214 invalidateParentIfNeeded(); 10215 } 10216 } 10217 } 10218 10219 /** 10220 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 10221 * completely transparent and 1 means the view is completely opaque. 10222 * 10223 * <p>By default this is 1.0f. 10224 * @return The opacity of the view. 10225 */ 10226 @ViewDebug.ExportedProperty(category = "drawing") 10227 public float getAlpha() { 10228 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 10229 } 10230 10231 /** 10232 * Returns whether this View has content which overlaps. 10233 * 10234 * <p>This function, intended to be overridden by specific View types, is an optimization when 10235 * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to 10236 * an offscreen buffer and then composited into place, which can be expensive. If the view has 10237 * no overlapping rendering, the view can draw each primitive with the appropriate alpha value 10238 * directly. An example of overlapping rendering is a TextView with a background image, such as 10239 * a Button. An example of non-overlapping rendering is a TextView with no background, or an 10240 * ImageView with only the foreground image. The default implementation returns true; subclasses 10241 * should override if they have cases which can be optimized.</p> 10242 * 10243 * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas} 10244 * necessitates that a View return true if it uses the methods internally without passing the 10245 * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p> 10246 * 10247 * @return true if the content in this view might overlap, false otherwise. 10248 */ 10249 public boolean hasOverlappingRendering() { 10250 return true; 10251 } 10252 10253 /** 10254 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is 10255 * completely transparent and 1 means the view is completely opaque.</p> 10256 * 10257 * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant 10258 * performance implications, especially for large views. It is best to use the alpha property 10259 * sparingly and transiently, as in the case of fading animations.</p> 10260 * 10261 * <p>For a view with a frequently changing alpha, such as during a fading animation, it is 10262 * strongly recommended for performance reasons to either override 10263 * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a 10264 * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p> 10265 * 10266 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 10267 * responsible for applying the opacity itself.</p> 10268 * 10269 * <p>Note that if the view is backed by a 10270 * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a 10271 * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than 10272 * 1.0 will supercede the alpha of the layer paint.</p> 10273 * 10274 * @param alpha The opacity of the view. 10275 * 10276 * @see #hasOverlappingRendering() 10277 * @see #setLayerType(int, android.graphics.Paint) 10278 * 10279 * @attr ref android.R.styleable#View_alpha 10280 */ 10281 public void setAlpha(float alpha) { 10282 ensureTransformationInfo(); 10283 if (mTransformationInfo.mAlpha != alpha) { 10284 mTransformationInfo.mAlpha = alpha; 10285 if (onSetAlpha((int) (alpha * 255))) { 10286 mPrivateFlags |= PFLAG_ALPHA_SET; 10287 // subclass is handling alpha - don't optimize rendering cache invalidation 10288 invalidateParentCaches(); 10289 invalidate(true); 10290 } else { 10291 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10292 invalidateViewProperty(true, false); 10293 if (mRenderNode != null) { 10294 mRenderNode.setAlpha(getFinalAlpha()); 10295 } 10296 } 10297 } 10298 } 10299 10300 /** 10301 * Faster version of setAlpha() which performs the same steps except there are 10302 * no calls to invalidate(). The caller of this function should perform proper invalidation 10303 * on the parent and this object. The return value indicates whether the subclass handles 10304 * alpha (the return value for onSetAlpha()). 10305 * 10306 * @param alpha The new value for the alpha property 10307 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 10308 * the new value for the alpha property is different from the old value 10309 */ 10310 boolean setAlphaNoInvalidation(float alpha) { 10311 ensureTransformationInfo(); 10312 if (mTransformationInfo.mAlpha != alpha) { 10313 mTransformationInfo.mAlpha = alpha; 10314 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 10315 if (subclassHandlesAlpha) { 10316 mPrivateFlags |= PFLAG_ALPHA_SET; 10317 return true; 10318 } else { 10319 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10320 if (mRenderNode != null) { 10321 mRenderNode.setAlpha(getFinalAlpha()); 10322 } 10323 } 10324 } 10325 return false; 10326 } 10327 10328 /** 10329 * This property is hidden and intended only for use by the Fade transition, which 10330 * animates it to produce a visual translucency that does not side-effect (or get 10331 * affected by) the real alpha property. This value is composited with the other 10332 * alpha value (and the AlphaAnimation value, when that is present) to produce 10333 * a final visual translucency result, which is what is passed into the DisplayList. 10334 * 10335 * @hide 10336 */ 10337 public void setTransitionAlpha(float alpha) { 10338 ensureTransformationInfo(); 10339 if (mTransformationInfo.mTransitionAlpha != alpha) { 10340 mTransformationInfo.mTransitionAlpha = alpha; 10341 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10342 invalidateViewProperty(true, false); 10343 if (mRenderNode != null) { 10344 mRenderNode.setAlpha(getFinalAlpha()); 10345 } 10346 } 10347 } 10348 10349 /** 10350 * Calculates the visual alpha of this view, which is a combination of the actual 10351 * alpha value and the transitionAlpha value (if set). 10352 */ 10353 private float getFinalAlpha() { 10354 if (mTransformationInfo != null) { 10355 return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha; 10356 } 10357 return 1; 10358 } 10359 10360 /** 10361 * This property is hidden and intended only for use by the Fade transition, which 10362 * animates it to produce a visual translucency that does not side-effect (or get 10363 * affected by) the real alpha property. This value is composited with the other 10364 * alpha value (and the AlphaAnimation value, when that is present) to produce 10365 * a final visual translucency result, which is what is passed into the DisplayList. 10366 * 10367 * @hide 10368 */ 10369 public float getTransitionAlpha() { 10370 return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1; 10371 } 10372 10373 /** 10374 * Top position of this view relative to its parent. 10375 * 10376 * @return The top of this view, in pixels. 10377 */ 10378 @ViewDebug.CapturedViewProperty 10379 public final int getTop() { 10380 return mTop; 10381 } 10382 10383 /** 10384 * Sets the top position of this view relative to its parent. This method is meant to be called 10385 * by the layout system and should not generally be called otherwise, because the property 10386 * may be changed at any time by the layout. 10387 * 10388 * @param top The top of this view, in pixels. 10389 */ 10390 public final void setTop(int top) { 10391 if (top != mTop) { 10392 updateMatrix(); 10393 final boolean matrixIsIdentity = mTransformationInfo == null 10394 || mTransformationInfo.mMatrixIsIdentity; 10395 if (matrixIsIdentity) { 10396 if (mAttachInfo != null) { 10397 int minTop; 10398 int yLoc; 10399 if (top < mTop) { 10400 minTop = top; 10401 yLoc = top - mTop; 10402 } else { 10403 minTop = mTop; 10404 yLoc = 0; 10405 } 10406 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 10407 } 10408 } else { 10409 // Double-invalidation is necessary to capture view's old and new areas 10410 invalidate(true); 10411 } 10412 10413 int width = mRight - mLeft; 10414 int oldHeight = mBottom - mTop; 10415 10416 mTop = top; 10417 if (mRenderNode != null) { 10418 mRenderNode.setTop(mTop); 10419 } 10420 10421 sizeChange(width, mBottom - mTop, width, oldHeight); 10422 10423 if (!matrixIsIdentity) { 10424 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 10425 // A change in dimension means an auto-centered pivot point changes, too 10426 mTransformationInfo.mMatrixDirty = true; 10427 } 10428 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10429 invalidate(true); 10430 } 10431 mBackgroundSizeChanged = true; 10432 invalidateParentIfNeeded(); 10433 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10434 // View was rejected last time it was drawn by its parent; this may have changed 10435 invalidateParentIfNeeded(); 10436 } 10437 } 10438 } 10439 10440 /** 10441 * Bottom position of this view relative to its parent. 10442 * 10443 * @return The bottom of this view, in pixels. 10444 */ 10445 @ViewDebug.CapturedViewProperty 10446 public final int getBottom() { 10447 return mBottom; 10448 } 10449 10450 /** 10451 * True if this view has changed since the last time being drawn. 10452 * 10453 * @return The dirty state of this view. 10454 */ 10455 public boolean isDirty() { 10456 return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0; 10457 } 10458 10459 /** 10460 * Sets the bottom position of this view relative to its parent. This method is meant to be 10461 * called by the layout system and should not generally be called otherwise, because the 10462 * property may be changed at any time by the layout. 10463 * 10464 * @param bottom The bottom of this view, in pixels. 10465 */ 10466 public final void setBottom(int bottom) { 10467 if (bottom != mBottom) { 10468 updateMatrix(); 10469 final boolean matrixIsIdentity = mTransformationInfo == null 10470 || mTransformationInfo.mMatrixIsIdentity; 10471 if (matrixIsIdentity) { 10472 if (mAttachInfo != null) { 10473 int maxBottom; 10474 if (bottom < mBottom) { 10475 maxBottom = mBottom; 10476 } else { 10477 maxBottom = bottom; 10478 } 10479 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 10480 } 10481 } else { 10482 // Double-invalidation is necessary to capture view's old and new areas 10483 invalidate(true); 10484 } 10485 10486 int width = mRight - mLeft; 10487 int oldHeight = mBottom - mTop; 10488 10489 mBottom = bottom; 10490 if (mRenderNode != null) { 10491 mRenderNode.setBottom(mBottom); 10492 } 10493 10494 sizeChange(width, mBottom - mTop, width, oldHeight); 10495 10496 if (!matrixIsIdentity) { 10497 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 10498 // A change in dimension means an auto-centered pivot point changes, too 10499 mTransformationInfo.mMatrixDirty = true; 10500 } 10501 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10502 invalidate(true); 10503 } 10504 mBackgroundSizeChanged = true; 10505 invalidateParentIfNeeded(); 10506 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10507 // View was rejected last time it was drawn by its parent; this may have changed 10508 invalidateParentIfNeeded(); 10509 } 10510 } 10511 } 10512 10513 /** 10514 * Left position of this view relative to its parent. 10515 * 10516 * @return The left edge of this view, in pixels. 10517 */ 10518 @ViewDebug.CapturedViewProperty 10519 public final int getLeft() { 10520 return mLeft; 10521 } 10522 10523 /** 10524 * Sets the left position of this view relative to its parent. This method is meant to be called 10525 * by the layout system and should not generally be called otherwise, because the property 10526 * may be changed at any time by the layout. 10527 * 10528 * @param left The left of this view, in pixels. 10529 */ 10530 public final void setLeft(int left) { 10531 if (left != mLeft) { 10532 updateMatrix(); 10533 final boolean matrixIsIdentity = mTransformationInfo == null 10534 || mTransformationInfo.mMatrixIsIdentity; 10535 if (matrixIsIdentity) { 10536 if (mAttachInfo != null) { 10537 int minLeft; 10538 int xLoc; 10539 if (left < mLeft) { 10540 minLeft = left; 10541 xLoc = left - mLeft; 10542 } else { 10543 minLeft = mLeft; 10544 xLoc = 0; 10545 } 10546 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 10547 } 10548 } else { 10549 // Double-invalidation is necessary to capture view's old and new areas 10550 invalidate(true); 10551 } 10552 10553 int oldWidth = mRight - mLeft; 10554 int height = mBottom - mTop; 10555 10556 mLeft = left; 10557 if (mRenderNode != null) { 10558 mRenderNode.setLeft(left); 10559 } 10560 10561 sizeChange(mRight - mLeft, height, oldWidth, height); 10562 10563 if (!matrixIsIdentity) { 10564 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 10565 // A change in dimension means an auto-centered pivot point changes, too 10566 mTransformationInfo.mMatrixDirty = true; 10567 } 10568 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10569 invalidate(true); 10570 } 10571 mBackgroundSizeChanged = true; 10572 invalidateParentIfNeeded(); 10573 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10574 // View was rejected last time it was drawn by its parent; this may have changed 10575 invalidateParentIfNeeded(); 10576 } 10577 } 10578 } 10579 10580 /** 10581 * Right position of this view relative to its parent. 10582 * 10583 * @return The right edge of this view, in pixels. 10584 */ 10585 @ViewDebug.CapturedViewProperty 10586 public final int getRight() { 10587 return mRight; 10588 } 10589 10590 /** 10591 * Sets the right position of this view relative to its parent. This method is meant to be called 10592 * by the layout system and should not generally be called otherwise, because the property 10593 * may be changed at any time by the layout. 10594 * 10595 * @param right The right of this view, in pixels. 10596 */ 10597 public final void setRight(int right) { 10598 if (right != mRight) { 10599 updateMatrix(); 10600 final boolean matrixIsIdentity = mTransformationInfo == null 10601 || mTransformationInfo.mMatrixIsIdentity; 10602 if (matrixIsIdentity) { 10603 if (mAttachInfo != null) { 10604 int maxRight; 10605 if (right < mRight) { 10606 maxRight = mRight; 10607 } else { 10608 maxRight = right; 10609 } 10610 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 10611 } 10612 } else { 10613 // Double-invalidation is necessary to capture view's old and new areas 10614 invalidate(true); 10615 } 10616 10617 int oldWidth = mRight - mLeft; 10618 int height = mBottom - mTop; 10619 10620 mRight = right; 10621 if (mRenderNode != null) { 10622 mRenderNode.setRight(mRight); 10623 } 10624 10625 sizeChange(mRight - mLeft, height, oldWidth, height); 10626 10627 if (!matrixIsIdentity) { 10628 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 10629 // A change in dimension means an auto-centered pivot point changes, too 10630 mTransformationInfo.mMatrixDirty = true; 10631 } 10632 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10633 invalidate(true); 10634 } 10635 mBackgroundSizeChanged = true; 10636 invalidateParentIfNeeded(); 10637 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10638 // View was rejected last time it was drawn by its parent; this may have changed 10639 invalidateParentIfNeeded(); 10640 } 10641 } 10642 } 10643 10644 /** 10645 * The visual x position of this view, in pixels. This is equivalent to the 10646 * {@link #setTranslationX(float) translationX} property plus the current 10647 * {@link #getLeft() left} property. 10648 * 10649 * @return The visual x position of this view, in pixels. 10650 */ 10651 @ViewDebug.ExportedProperty(category = "drawing") 10652 public float getX() { 10653 return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0); 10654 } 10655 10656 /** 10657 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 10658 * {@link #setTranslationX(float) translationX} property to be the difference between 10659 * the x value passed in and the current {@link #getLeft() left} property. 10660 * 10661 * @param x The visual x position of this view, in pixels. 10662 */ 10663 public void setX(float x) { 10664 setTranslationX(x - mLeft); 10665 } 10666 10667 /** 10668 * The visual y position of this view, in pixels. This is equivalent to the 10669 * {@link #setTranslationY(float) translationY} property plus the current 10670 * {@link #getTop() top} property. 10671 * 10672 * @return The visual y position of this view, in pixels. 10673 */ 10674 @ViewDebug.ExportedProperty(category = "drawing") 10675 public float getY() { 10676 return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0); 10677 } 10678 10679 /** 10680 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 10681 * {@link #setTranslationY(float) translationY} property to be the difference between 10682 * the y value passed in and the current {@link #getTop() top} property. 10683 * 10684 * @param y The visual y position of this view, in pixels. 10685 */ 10686 public void setY(float y) { 10687 setTranslationY(y - mTop); 10688 } 10689 10690 10691 /** 10692 * The horizontal location of this view relative to its {@link #getLeft() left} position. 10693 * This position is post-layout, in addition to wherever the object's 10694 * layout placed it. 10695 * 10696 * @return The horizontal position of this view relative to its left position, in pixels. 10697 */ 10698 @ViewDebug.ExportedProperty(category = "drawing") 10699 public float getTranslationX() { 10700 return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0; 10701 } 10702 10703 /** 10704 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 10705 * This effectively positions the object post-layout, in addition to wherever the object's 10706 * layout placed it. 10707 * 10708 * @param translationX The horizontal position of this view relative to its left position, 10709 * in pixels. 10710 * 10711 * @attr ref android.R.styleable#View_translationX 10712 */ 10713 public void setTranslationX(float translationX) { 10714 ensureTransformationInfo(); 10715 final TransformationInfo info = mTransformationInfo; 10716 if (info.mTranslationX != translationX) { 10717 // Double-invalidation is necessary to capture view's old and new areas 10718 invalidateViewProperty(true, false); 10719 info.mTranslationX = translationX; 10720 info.mMatrixDirty = true; 10721 invalidateViewProperty(false, true); 10722 if (mRenderNode != null) { 10723 mRenderNode.setTranslationX(translationX); 10724 } 10725 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10726 // View was rejected last time it was drawn by its parent; this may have changed 10727 invalidateParentIfNeeded(); 10728 } 10729 } 10730 } 10731 10732 /** 10733 * The vertical location of this view relative to its {@link #getTop() top} position. 10734 * This position is post-layout, in addition to wherever the object's 10735 * layout placed it. 10736 * 10737 * @return The vertical position of this view relative to its top position, 10738 * in pixels. 10739 */ 10740 @ViewDebug.ExportedProperty(category = "drawing") 10741 public float getTranslationY() { 10742 return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0; 10743 } 10744 10745 /** 10746 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 10747 * This effectively positions the object post-layout, in addition to wherever the object's 10748 * layout placed it. 10749 * 10750 * @param translationY The vertical position of this view relative to its top position, 10751 * in pixels. 10752 * 10753 * @attr ref android.R.styleable#View_translationY 10754 */ 10755 public void setTranslationY(float translationY) { 10756 ensureTransformationInfo(); 10757 final TransformationInfo info = mTransformationInfo; 10758 if (info.mTranslationY != translationY) { 10759 invalidateViewProperty(true, false); 10760 info.mTranslationY = translationY; 10761 info.mMatrixDirty = true; 10762 invalidateViewProperty(false, true); 10763 if (mRenderNode != null) { 10764 mRenderNode.setTranslationY(translationY); 10765 } 10766 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10767 // View was rejected last time it was drawn by its parent; this may have changed 10768 invalidateParentIfNeeded(); 10769 } 10770 } 10771 } 10772 10773 /** 10774 * The depth location of this view relative to its parent. 10775 * 10776 * @return The depth of this view relative to its parent. 10777 */ 10778 @ViewDebug.ExportedProperty(category = "drawing") 10779 public float getTranslationZ() { 10780 return mTransformationInfo != null ? mTransformationInfo.mTranslationZ : 0; 10781 } 10782 10783 /** 10784 * Sets the depth location of this view relative to its parent. 10785 * 10786 * @attr ref android.R.styleable#View_translationZ 10787 */ 10788 public void setTranslationZ(float translationZ) { 10789 ensureTransformationInfo(); 10790 final TransformationInfo info = mTransformationInfo; 10791 if (info.mTranslationZ != translationZ) { 10792 invalidateViewProperty(true, false); 10793 info.mTranslationZ = translationZ; 10794 info.mMatrixDirty = true; 10795 invalidateViewProperty(false, true); 10796 if (mRenderNode != null) { 10797 mRenderNode.setTranslationZ(translationZ); 10798 } 10799 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10800 // View was rejected last time it was drawn by its parent; this may have changed 10801 invalidateParentIfNeeded(); 10802 } 10803 } 10804 } 10805 10806 /** 10807 * Returns a ValueAnimator which can be used to run a reveal animation, 10808 * clipping the content of the view to a circle. 10809 * 10810 * TODO: Make this a public API. 10811 * @hide 10812 */ 10813 public final ValueAnimator createRevealAnimator(int x, int y, 10814 float startRadius, float endRadius, boolean inverseClip) { 10815 return RevealAnimator.ofRevealCircle(this, x, y, startRadius, endRadius, inverseClip); 10816 } 10817 10818 /** 10819 * Sets the outline of the view, which defines the shape of the shadow it 10820 * casts, and can used for clipping. 10821 * <p> 10822 * If the outline is not set or is null, shadows will be cast from the 10823 * bounds of the View, and clipToOutline will be ignored. 10824 * 10825 * @param outline The new outline of the view. 10826 * Must be {@link android.graphics.Outline#isValid() valid.} 10827 * 10828 * @see #getClipToOutline() 10829 * @see #setClipToOutline(boolean) 10830 */ 10831 public void setOutline(@Nullable Outline outline) { 10832 if (outline != null && !outline.isValid()) { 10833 throw new IllegalArgumentException("Outline must not be invalid"); 10834 } 10835 10836 mPrivateFlags3 |= PFLAG3_OUTLINE_DEFINED; 10837 10838 if (outline == null) { 10839 mOutline = null; 10840 } else { 10841 // always copy the path since caller may reuse 10842 if (mOutline == null) { 10843 mOutline = new Outline(); 10844 } 10845 mOutline.set(outline); 10846 } 10847 10848 if (mRenderNode != null) { 10849 mRenderNode.setOutline(mOutline); 10850 } 10851 } 10852 10853 /** 10854 * Returns whether the outline of the View will be used for clipping. 10855 * 10856 * @see #setOutline(Outline) 10857 */ 10858 public final boolean getClipToOutline() { 10859 return ((mPrivateFlags3 & PFLAG3_CLIP_TO_OUTLINE) != 0); 10860 } 10861 10862 /** 10863 * Sets whether the outline of the View will be used for clipping. 10864 * <p> 10865 * The current implementation of outline clipping uses 10866 * {@link Canvas#clipPath(Path) path clipping}, 10867 * and thus does not support anti-aliasing, and is expensive in terms of 10868 * graphics performance. Therefore, it is strongly recommended that this 10869 * property only be set temporarily, as in an animation. For the same 10870 * reasons, there is no parallel XML attribute for this property. 10871 * <p> 10872 * If the outline of the view is not set or is empty, no clipping will be 10873 * performed. 10874 * 10875 * @see #setOutline(Outline) 10876 */ 10877 public void setClipToOutline(boolean clipToOutline) { 10878 // TODO : Add a fast invalidation here. 10879 if (getClipToOutline() != clipToOutline) { 10880 if (clipToOutline) { 10881 mPrivateFlags3 |= PFLAG3_CLIP_TO_OUTLINE; 10882 } else { 10883 mPrivateFlags3 &= ~PFLAG3_CLIP_TO_OUTLINE; 10884 } 10885 if (mRenderNode != null) { 10886 mRenderNode.setClipToOutline(clipToOutline); 10887 } 10888 } 10889 } 10890 10891 /** 10892 * Private API to be used for reveal animation 10893 * 10894 * @hide 10895 */ 10896 public void setRevealClip(boolean shouldClip, boolean inverseClip, 10897 float x, float y, float radius) { 10898 if (mRenderNode != null) { 10899 mRenderNode.setRevealClip(shouldClip, inverseClip, x, y, radius); 10900 // TODO: Handle this invalidate in a better way, or purely in native. 10901 invalidate(); 10902 } 10903 } 10904 10905 /** 10906 * Hit rectangle in parent's coordinates 10907 * 10908 * @param outRect The hit rectangle of the view. 10909 */ 10910 public void getHitRect(Rect outRect) { 10911 updateMatrix(); 10912 final TransformationInfo info = mTransformationInfo; 10913 if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) { 10914 outRect.set(mLeft, mTop, mRight, mBottom); 10915 } else { 10916 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 10917 tmpRect.set(0, 0, getWidth(), getHeight()); 10918 info.mMatrix.mapRect(tmpRect); 10919 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 10920 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 10921 } 10922 } 10923 10924 /** 10925 * Determines whether the given point, in local coordinates is inside the view. 10926 */ 10927 /*package*/ final boolean pointInView(float localX, float localY) { 10928 return localX >= 0 && localX < (mRight - mLeft) 10929 && localY >= 0 && localY < (mBottom - mTop); 10930 } 10931 10932 /** 10933 * Utility method to determine whether the given point, in local coordinates, 10934 * is inside the view, where the area of the view is expanded by the slop factor. 10935 * This method is called while processing touch-move events to determine if the event 10936 * is still within the view. 10937 * 10938 * @hide 10939 */ 10940 public boolean pointInView(float localX, float localY, float slop) { 10941 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 10942 localY < ((mBottom - mTop) + slop); 10943 } 10944 10945 /** 10946 * When a view has focus and the user navigates away from it, the next view is searched for 10947 * starting from the rectangle filled in by this method. 10948 * 10949 * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)}) 10950 * of the view. However, if your view maintains some idea of internal selection, 10951 * such as a cursor, or a selected row or column, you should override this method and 10952 * fill in a more specific rectangle. 10953 * 10954 * @param r The rectangle to fill in, in this view's coordinates. 10955 */ 10956 public void getFocusedRect(Rect r) { 10957 getDrawingRect(r); 10958 } 10959 10960 /** 10961 * If some part of this view is not clipped by any of its parents, then 10962 * return that area in r in global (root) coordinates. To convert r to local 10963 * coordinates (without taking possible View rotations into account), offset 10964 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 10965 * If the view is completely clipped or translated out, return false. 10966 * 10967 * @param r If true is returned, r holds the global coordinates of the 10968 * visible portion of this view. 10969 * @param globalOffset If true is returned, globalOffset holds the dx,dy 10970 * between this view and its root. globalOffet may be null. 10971 * @return true if r is non-empty (i.e. part of the view is visible at the 10972 * root level. 10973 */ 10974 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 10975 int width = mRight - mLeft; 10976 int height = mBottom - mTop; 10977 if (width > 0 && height > 0) { 10978 r.set(0, 0, width, height); 10979 if (globalOffset != null) { 10980 globalOffset.set(-mScrollX, -mScrollY); 10981 } 10982 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 10983 } 10984 return false; 10985 } 10986 10987 public final boolean getGlobalVisibleRect(Rect r) { 10988 return getGlobalVisibleRect(r, null); 10989 } 10990 10991 public final boolean getLocalVisibleRect(Rect r) { 10992 final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point(); 10993 if (getGlobalVisibleRect(r, offset)) { 10994 r.offset(-offset.x, -offset.y); // make r local 10995 return true; 10996 } 10997 return false; 10998 } 10999 11000 /** 11001 * Offset this view's vertical location by the specified number of pixels. 11002 * 11003 * @param offset the number of pixels to offset the view by 11004 */ 11005 public void offsetTopAndBottom(int offset) { 11006 if (offset != 0) { 11007 updateMatrix(); 11008 final boolean matrixIsIdentity = mTransformationInfo == null 11009 || mTransformationInfo.mMatrixIsIdentity; 11010 if (matrixIsIdentity) { 11011 if (mRenderNode != null) { 11012 invalidateViewProperty(false, false); 11013 } else { 11014 final ViewParent p = mParent; 11015 if (p != null && mAttachInfo != null) { 11016 final Rect r = mAttachInfo.mTmpInvalRect; 11017 int minTop; 11018 int maxBottom; 11019 int yLoc; 11020 if (offset < 0) { 11021 minTop = mTop + offset; 11022 maxBottom = mBottom; 11023 yLoc = offset; 11024 } else { 11025 minTop = mTop; 11026 maxBottom = mBottom + offset; 11027 yLoc = 0; 11028 } 11029 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 11030 p.invalidateChild(this, r); 11031 } 11032 } 11033 } else { 11034 invalidateViewProperty(false, false); 11035 } 11036 11037 mTop += offset; 11038 mBottom += offset; 11039 if (mRenderNode != null) { 11040 mRenderNode.offsetTopAndBottom(offset); 11041 invalidateViewProperty(false, false); 11042 } else { 11043 if (!matrixIsIdentity) { 11044 invalidateViewProperty(false, true); 11045 } 11046 invalidateParentIfNeeded(); 11047 } 11048 } 11049 } 11050 11051 /** 11052 * Offset this view's horizontal location by the specified amount of pixels. 11053 * 11054 * @param offset the number of pixels to offset the view by 11055 */ 11056 public void offsetLeftAndRight(int offset) { 11057 if (offset != 0) { 11058 updateMatrix(); 11059 final boolean matrixIsIdentity = mTransformationInfo == null 11060 || mTransformationInfo.mMatrixIsIdentity; 11061 if (matrixIsIdentity) { 11062 if (mRenderNode != null) { 11063 invalidateViewProperty(false, false); 11064 } else { 11065 final ViewParent p = mParent; 11066 if (p != null && mAttachInfo != null) { 11067 final Rect r = mAttachInfo.mTmpInvalRect; 11068 int minLeft; 11069 int maxRight; 11070 if (offset < 0) { 11071 minLeft = mLeft + offset; 11072 maxRight = mRight; 11073 } else { 11074 minLeft = mLeft; 11075 maxRight = mRight + offset; 11076 } 11077 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 11078 p.invalidateChild(this, r); 11079 } 11080 } 11081 } else { 11082 invalidateViewProperty(false, false); 11083 } 11084 11085 mLeft += offset; 11086 mRight += offset; 11087 if (mRenderNode != null) { 11088 mRenderNode.offsetLeftAndRight(offset); 11089 invalidateViewProperty(false, false); 11090 } else { 11091 if (!matrixIsIdentity) { 11092 invalidateViewProperty(false, true); 11093 } 11094 invalidateParentIfNeeded(); 11095 } 11096 } 11097 } 11098 11099 /** 11100 * Get the LayoutParams associated with this view. All views should have 11101 * layout parameters. These supply parameters to the <i>parent</i> of this 11102 * view specifying how it should be arranged. There are many subclasses of 11103 * ViewGroup.LayoutParams, and these correspond to the different subclasses 11104 * of ViewGroup that are responsible for arranging their children. 11105 * 11106 * This method may return null if this View is not attached to a parent 11107 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 11108 * was not invoked successfully. When a View is attached to a parent 11109 * ViewGroup, this method must not return null. 11110 * 11111 * @return The LayoutParams associated with this view, or null if no 11112 * parameters have been set yet 11113 */ 11114 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 11115 public ViewGroup.LayoutParams getLayoutParams() { 11116 return mLayoutParams; 11117 } 11118 11119 /** 11120 * Set the layout parameters associated with this view. These supply 11121 * parameters to the <i>parent</i> of this view specifying how it should be 11122 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 11123 * correspond to the different subclasses of ViewGroup that are responsible 11124 * for arranging their children. 11125 * 11126 * @param params The layout parameters for this view, cannot be null 11127 */ 11128 public void setLayoutParams(ViewGroup.LayoutParams params) { 11129 if (params == null) { 11130 throw new NullPointerException("Layout parameters cannot be null"); 11131 } 11132 mLayoutParams = params; 11133 resolveLayoutParams(); 11134 if (mParent instanceof ViewGroup) { 11135 ((ViewGroup) mParent).onSetLayoutParams(this, params); 11136 } 11137 requestLayout(); 11138 } 11139 11140 /** 11141 * Resolve the layout parameters depending on the resolved layout direction 11142 * 11143 * @hide 11144 */ 11145 public void resolveLayoutParams() { 11146 if (mLayoutParams != null) { 11147 mLayoutParams.resolveLayoutDirection(getLayoutDirection()); 11148 } 11149 } 11150 11151 /** 11152 * Set the scrolled position of your view. This will cause a call to 11153 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11154 * invalidated. 11155 * @param x the x position to scroll to 11156 * @param y the y position to scroll to 11157 */ 11158 public void scrollTo(int x, int y) { 11159 if (mScrollX != x || mScrollY != y) { 11160 int oldX = mScrollX; 11161 int oldY = mScrollY; 11162 mScrollX = x; 11163 mScrollY = y; 11164 invalidateParentCaches(); 11165 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 11166 if (!awakenScrollBars()) { 11167 postInvalidateOnAnimation(); 11168 } 11169 } 11170 } 11171 11172 /** 11173 * Move the scrolled position of your view. This will cause a call to 11174 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11175 * invalidated. 11176 * @param x the amount of pixels to scroll by horizontally 11177 * @param y the amount of pixels to scroll by vertically 11178 */ 11179 public void scrollBy(int x, int y) { 11180 scrollTo(mScrollX + x, mScrollY + y); 11181 } 11182 11183 /** 11184 * <p>Trigger the scrollbars to draw. When invoked this method starts an 11185 * animation to fade the scrollbars out after a default delay. If a subclass 11186 * provides animated scrolling, the start delay should equal the duration 11187 * of the scrolling animation.</p> 11188 * 11189 * <p>The animation starts only if at least one of the scrollbars is 11190 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 11191 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11192 * this method returns true, and false otherwise. If the animation is 11193 * started, this method calls {@link #invalidate()}; in that case the 11194 * caller should not call {@link #invalidate()}.</p> 11195 * 11196 * <p>This method should be invoked every time a subclass directly updates 11197 * the scroll parameters.</p> 11198 * 11199 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 11200 * and {@link #scrollTo(int, int)}.</p> 11201 * 11202 * @return true if the animation is played, false otherwise 11203 * 11204 * @see #awakenScrollBars(int) 11205 * @see #scrollBy(int, int) 11206 * @see #scrollTo(int, int) 11207 * @see #isHorizontalScrollBarEnabled() 11208 * @see #isVerticalScrollBarEnabled() 11209 * @see #setHorizontalScrollBarEnabled(boolean) 11210 * @see #setVerticalScrollBarEnabled(boolean) 11211 */ 11212 protected boolean awakenScrollBars() { 11213 return mScrollCache != null && 11214 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 11215 } 11216 11217 /** 11218 * Trigger the scrollbars to draw. 11219 * This method differs from awakenScrollBars() only in its default duration. 11220 * initialAwakenScrollBars() will show the scroll bars for longer than 11221 * usual to give the user more of a chance to notice them. 11222 * 11223 * @return true if the animation is played, false otherwise. 11224 */ 11225 private boolean initialAwakenScrollBars() { 11226 return mScrollCache != null && 11227 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 11228 } 11229 11230 /** 11231 * <p> 11232 * Trigger the scrollbars to draw. When invoked this method starts an 11233 * animation to fade the scrollbars out after a fixed delay. If a subclass 11234 * provides animated scrolling, the start delay should equal the duration of 11235 * the scrolling animation. 11236 * </p> 11237 * 11238 * <p> 11239 * The animation starts only if at least one of the scrollbars is enabled, 11240 * as specified by {@link #isHorizontalScrollBarEnabled()} and 11241 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11242 * this method returns true, and false otherwise. If the animation is 11243 * started, this method calls {@link #invalidate()}; in that case the caller 11244 * should not call {@link #invalidate()}. 11245 * </p> 11246 * 11247 * <p> 11248 * This method should be invoked everytime a subclass directly updates the 11249 * scroll parameters. 11250 * </p> 11251 * 11252 * @param startDelay the delay, in milliseconds, after which the animation 11253 * should start; when the delay is 0, the animation starts 11254 * immediately 11255 * @return true if the animation is played, false otherwise 11256 * 11257 * @see #scrollBy(int, int) 11258 * @see #scrollTo(int, int) 11259 * @see #isHorizontalScrollBarEnabled() 11260 * @see #isVerticalScrollBarEnabled() 11261 * @see #setHorizontalScrollBarEnabled(boolean) 11262 * @see #setVerticalScrollBarEnabled(boolean) 11263 */ 11264 protected boolean awakenScrollBars(int startDelay) { 11265 return awakenScrollBars(startDelay, true); 11266 } 11267 11268 /** 11269 * <p> 11270 * Trigger the scrollbars to draw. When invoked this method starts an 11271 * animation to fade the scrollbars out after a fixed delay. If a subclass 11272 * provides animated scrolling, the start delay should equal the duration of 11273 * the scrolling animation. 11274 * </p> 11275 * 11276 * <p> 11277 * The animation starts only if at least one of the scrollbars is enabled, 11278 * as specified by {@link #isHorizontalScrollBarEnabled()} and 11279 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11280 * this method returns true, and false otherwise. If the animation is 11281 * started, this method calls {@link #invalidate()} if the invalidate parameter 11282 * is set to true; in that case the caller 11283 * should not call {@link #invalidate()}. 11284 * </p> 11285 * 11286 * <p> 11287 * This method should be invoked everytime a subclass directly updates the 11288 * scroll parameters. 11289 * </p> 11290 * 11291 * @param startDelay the delay, in milliseconds, after which the animation 11292 * should start; when the delay is 0, the animation starts 11293 * immediately 11294 * 11295 * @param invalidate Wheter this method should call invalidate 11296 * 11297 * @return true if the animation is played, false otherwise 11298 * 11299 * @see #scrollBy(int, int) 11300 * @see #scrollTo(int, int) 11301 * @see #isHorizontalScrollBarEnabled() 11302 * @see #isVerticalScrollBarEnabled() 11303 * @see #setHorizontalScrollBarEnabled(boolean) 11304 * @see #setVerticalScrollBarEnabled(boolean) 11305 */ 11306 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 11307 final ScrollabilityCache scrollCache = mScrollCache; 11308 11309 if (scrollCache == null || !scrollCache.fadeScrollBars) { 11310 return false; 11311 } 11312 11313 if (scrollCache.scrollBar == null) { 11314 scrollCache.scrollBar = new ScrollBarDrawable(); 11315 } 11316 11317 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 11318 11319 if (invalidate) { 11320 // Invalidate to show the scrollbars 11321 postInvalidateOnAnimation(); 11322 } 11323 11324 if (scrollCache.state == ScrollabilityCache.OFF) { 11325 // FIXME: this is copied from WindowManagerService. 11326 // We should get this value from the system when it 11327 // is possible to do so. 11328 final int KEY_REPEAT_FIRST_DELAY = 750; 11329 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 11330 } 11331 11332 // Tell mScrollCache when we should start fading. This may 11333 // extend the fade start time if one was already scheduled 11334 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 11335 scrollCache.fadeStartTime = fadeStartTime; 11336 scrollCache.state = ScrollabilityCache.ON; 11337 11338 // Schedule our fader to run, unscheduling any old ones first 11339 if (mAttachInfo != null) { 11340 mAttachInfo.mHandler.removeCallbacks(scrollCache); 11341 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 11342 } 11343 11344 return true; 11345 } 11346 11347 return false; 11348 } 11349 11350 /** 11351 * Do not invalidate views which are not visible and which are not running an animation. They 11352 * will not get drawn and they should not set dirty flags as if they will be drawn 11353 */ 11354 private boolean skipInvalidate() { 11355 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 11356 (!(mParent instanceof ViewGroup) || 11357 !((ViewGroup) mParent).isViewTransitioning(this)); 11358 } 11359 11360 /** 11361 * Mark the area defined by dirty as needing to be drawn. If the view is 11362 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 11363 * point in the future. 11364 * <p> 11365 * This must be called from a UI thread. To call from a non-UI thread, call 11366 * {@link #postInvalidate()}. 11367 * <p> 11368 * <b>WARNING:</b> In API 19 and below, this method may be destructive to 11369 * {@code dirty}. 11370 * 11371 * @param dirty the rectangle representing the bounds of the dirty region 11372 */ 11373 public void invalidate(Rect dirty) { 11374 final int scrollX = mScrollX; 11375 final int scrollY = mScrollY; 11376 invalidateInternal(dirty.left - scrollX, dirty.top - scrollY, 11377 dirty.right - scrollX, dirty.bottom - scrollY, true, false); 11378 } 11379 11380 /** 11381 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The 11382 * coordinates of the dirty rect are relative to the view. If the view is 11383 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 11384 * point in the future. 11385 * <p> 11386 * This must be called from a UI thread. To call from a non-UI thread, call 11387 * {@link #postInvalidate()}. 11388 * 11389 * @param l the left position of the dirty region 11390 * @param t the top position of the dirty region 11391 * @param r the right position of the dirty region 11392 * @param b the bottom position of the dirty region 11393 */ 11394 public void invalidate(int l, int t, int r, int b) { 11395 final int scrollX = mScrollX; 11396 final int scrollY = mScrollY; 11397 invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false); 11398 } 11399 11400 /** 11401 * Invalidate the whole view. If the view is visible, 11402 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 11403 * the future. 11404 * <p> 11405 * This must be called from a UI thread. To call from a non-UI thread, call 11406 * {@link #postInvalidate()}. 11407 */ 11408 public void invalidate() { 11409 invalidate(true); 11410 } 11411 11412 /** 11413 * This is where the invalidate() work actually happens. A full invalidate() 11414 * causes the drawing cache to be invalidated, but this function can be 11415 * called with invalidateCache set to false to skip that invalidation step 11416 * for cases that do not need it (for example, a component that remains at 11417 * the same dimensions with the same content). 11418 * 11419 * @param invalidateCache Whether the drawing cache for this view should be 11420 * invalidated as well. This is usually true for a full 11421 * invalidate, but may be set to false if the View's contents or 11422 * dimensions have not changed. 11423 */ 11424 void invalidate(boolean invalidateCache) { 11425 invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true); 11426 } 11427 11428 void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache, 11429 boolean fullInvalidate) { 11430 if (skipInvalidate()) { 11431 return; 11432 } 11433 11434 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) 11435 || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) 11436 || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED 11437 || (fullInvalidate && isOpaque() != mLastIsOpaque)) { 11438 if (fullInvalidate) { 11439 mLastIsOpaque = isOpaque(); 11440 mPrivateFlags &= ~PFLAG_DRAWN; 11441 } 11442 11443 mPrivateFlags |= PFLAG_DIRTY; 11444 11445 if (invalidateCache) { 11446 mPrivateFlags |= PFLAG_INVALIDATED; 11447 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 11448 } 11449 11450 // Propagate the damage rectangle to the parent view. 11451 final AttachInfo ai = mAttachInfo; 11452 final ViewParent p = mParent; 11453 if (p != null && ai != null && l < r && t < b) { 11454 final Rect damage = ai.mTmpInvalRect; 11455 damage.set(l, t, r, b); 11456 p.invalidateChild(this, damage); 11457 } 11458 11459 // Damage the entire projection receiver, if necessary. 11460 if (mBackground != null && mBackground.isProjected()) { 11461 final View receiver = getProjectionReceiver(); 11462 if (receiver != null) { 11463 receiver.damageInParent(); 11464 } 11465 } 11466 11467 // Damage the entire IsolatedZVolume recieving this view's shadow. 11468 if (getTranslationZ() != 0) { 11469 damageShadowReceiver(); 11470 } 11471 } 11472 } 11473 11474 /** 11475 * @return this view's projection receiver, or {@code null} if none exists 11476 */ 11477 private View getProjectionReceiver() { 11478 ViewParent p = getParent(); 11479 while (p != null && p instanceof View) { 11480 final View v = (View) p; 11481 if (v.isProjectionReceiver()) { 11482 return v; 11483 } 11484 p = p.getParent(); 11485 } 11486 11487 return null; 11488 } 11489 11490 /** 11491 * @return whether the view is a projection receiver 11492 */ 11493 private boolean isProjectionReceiver() { 11494 return mBackground != null; 11495 } 11496 11497 /** 11498 * Damage area of the screen that can be covered by this View's shadow. 11499 * 11500 * This method will guarantee that any changes to shadows cast by a View 11501 * are damaged on the screen for future redraw. 11502 */ 11503 private void damageShadowReceiver() { 11504 final AttachInfo ai = mAttachInfo; 11505 if (ai != null) { 11506 ViewParent p = getParent(); 11507 if (p != null && p instanceof ViewGroup) { 11508 final ViewGroup vg = (ViewGroup) p; 11509 vg.damageInParent(); 11510 } 11511 } 11512 } 11513 11514 /** 11515 * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to 11516 * set any flags or handle all of the cases handled by the default invalidation methods. 11517 * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate 11518 * dirty rect. This method calls into fast invalidation methods in ViewGroup that 11519 * walk up the hierarchy, transforming the dirty rect as necessary. 11520 * 11521 * The method also handles normal invalidation logic if display list properties are not 11522 * being used in this view. The invalidateParent and forceRedraw flags are used by that 11523 * backup approach, to handle these cases used in the various property-setting methods. 11524 * 11525 * @param invalidateParent Force a call to invalidateParentCaches() if display list properties 11526 * are not being used in this view 11527 * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display 11528 * list properties are not being used in this view 11529 */ 11530 void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) { 11531 if (mRenderNode == null || (mPrivateFlags & PFLAG_DRAW_ANIMATION) == PFLAG_DRAW_ANIMATION) { 11532 if (invalidateParent) { 11533 invalidateParentCaches(); 11534 } 11535 if (forceRedraw) { 11536 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 11537 } 11538 invalidate(false); 11539 } else { 11540 damageInParent(); 11541 } 11542 if (invalidateParent && getTranslationZ() != 0) { 11543 damageShadowReceiver(); 11544 } 11545 } 11546 11547 /** 11548 * Tells the parent view to damage this view's bounds. 11549 * 11550 * @hide 11551 */ 11552 protected void damageInParent() { 11553 final AttachInfo ai = mAttachInfo; 11554 final ViewParent p = mParent; 11555 if (p != null && ai != null) { 11556 final Rect r = ai.mTmpInvalRect; 11557 r.set(0, 0, mRight - mLeft, mBottom - mTop); 11558 if (mParent instanceof ViewGroup) { 11559 ((ViewGroup) mParent).invalidateChildFast(this, r); 11560 } else { 11561 mParent.invalidateChild(this, r); 11562 } 11563 } 11564 } 11565 11566 /** 11567 * Utility method to transform a given Rect by the current matrix of this view. 11568 */ 11569 void transformRect(final Rect rect) { 11570 if (!getMatrix().isIdentity()) { 11571 RectF boundingRect = mAttachInfo.mTmpTransformRect; 11572 boundingRect.set(rect); 11573 getMatrix().mapRect(boundingRect); 11574 rect.set((int) Math.floor(boundingRect.left), 11575 (int) Math.floor(boundingRect.top), 11576 (int) Math.ceil(boundingRect.right), 11577 (int) Math.ceil(boundingRect.bottom)); 11578 } 11579 } 11580 11581 /** 11582 * Used to indicate that the parent of this view should clear its caches. This functionality 11583 * is used to force the parent to rebuild its display list (when hardware-accelerated), 11584 * which is necessary when various parent-managed properties of the view change, such as 11585 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 11586 * clears the parent caches and does not causes an invalidate event. 11587 * 11588 * @hide 11589 */ 11590 protected void invalidateParentCaches() { 11591 if (mParent instanceof View) { 11592 ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED; 11593 } 11594 } 11595 11596 /** 11597 * Used to indicate that the parent of this view should be invalidated. This functionality 11598 * is used to force the parent to rebuild its display list (when hardware-accelerated), 11599 * which is necessary when various parent-managed properties of the view change, such as 11600 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 11601 * an invalidation event to the parent. 11602 * 11603 * @hide 11604 */ 11605 protected void invalidateParentIfNeeded() { 11606 if (isHardwareAccelerated() && mParent instanceof View) { 11607 ((View) mParent).invalidate(true); 11608 } 11609 } 11610 11611 /** 11612 * Indicates whether this View is opaque. An opaque View guarantees that it will 11613 * draw all the pixels overlapping its bounds using a fully opaque color. 11614 * 11615 * Subclasses of View should override this method whenever possible to indicate 11616 * whether an instance is opaque. Opaque Views are treated in a special way by 11617 * the View hierarchy, possibly allowing it to perform optimizations during 11618 * invalidate/draw passes. 11619 * 11620 * @return True if this View is guaranteed to be fully opaque, false otherwise. 11621 */ 11622 @ViewDebug.ExportedProperty(category = "drawing") 11623 public boolean isOpaque() { 11624 return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK && 11625 getFinalAlpha() >= 1.0f; 11626 } 11627 11628 /** 11629 * @hide 11630 */ 11631 protected void computeOpaqueFlags() { 11632 // Opaque if: 11633 // - Has a background 11634 // - Background is opaque 11635 // - Doesn't have scrollbars or scrollbars overlay 11636 11637 if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) { 11638 mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND; 11639 } else { 11640 mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND; 11641 } 11642 11643 final int flags = mViewFlags; 11644 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 11645 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY || 11646 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) { 11647 mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS; 11648 } else { 11649 mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS; 11650 } 11651 } 11652 11653 /** 11654 * @hide 11655 */ 11656 protected boolean hasOpaqueScrollbars() { 11657 return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS; 11658 } 11659 11660 /** 11661 * @return A handler associated with the thread running the View. This 11662 * handler can be used to pump events in the UI events queue. 11663 */ 11664 public Handler getHandler() { 11665 final AttachInfo attachInfo = mAttachInfo; 11666 if (attachInfo != null) { 11667 return attachInfo.mHandler; 11668 } 11669 return null; 11670 } 11671 11672 /** 11673 * Gets the view root associated with the View. 11674 * @return The view root, or null if none. 11675 * @hide 11676 */ 11677 public ViewRootImpl getViewRootImpl() { 11678 if (mAttachInfo != null) { 11679 return mAttachInfo.mViewRootImpl; 11680 } 11681 return null; 11682 } 11683 11684 /** 11685 * @hide 11686 */ 11687 public HardwareRenderer getHardwareRenderer() { 11688 return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null; 11689 } 11690 11691 /** 11692 * <p>Causes the Runnable to be added to the message queue. 11693 * The runnable will be run on the user interface thread.</p> 11694 * 11695 * @param action The Runnable that will be executed. 11696 * 11697 * @return Returns true if the Runnable was successfully placed in to the 11698 * message queue. Returns false on failure, usually because the 11699 * looper processing the message queue is exiting. 11700 * 11701 * @see #postDelayed 11702 * @see #removeCallbacks 11703 */ 11704 public boolean post(Runnable action) { 11705 final AttachInfo attachInfo = mAttachInfo; 11706 if (attachInfo != null) { 11707 return attachInfo.mHandler.post(action); 11708 } 11709 // Assume that post will succeed later 11710 ViewRootImpl.getRunQueue().post(action); 11711 return true; 11712 } 11713 11714 /** 11715 * <p>Causes the Runnable to be added to the message queue, to be run 11716 * after the specified amount of time elapses. 11717 * The runnable will be run on the user interface thread.</p> 11718 * 11719 * @param action The Runnable that will be executed. 11720 * @param delayMillis The delay (in milliseconds) until the Runnable 11721 * will be executed. 11722 * 11723 * @return true if the Runnable was successfully placed in to the 11724 * message queue. Returns false on failure, usually because the 11725 * looper processing the message queue is exiting. Note that a 11726 * result of true does not mean the Runnable will be processed -- 11727 * if the looper is quit before the delivery time of the message 11728 * occurs then the message will be dropped. 11729 * 11730 * @see #post 11731 * @see #removeCallbacks 11732 */ 11733 public boolean postDelayed(Runnable action, long delayMillis) { 11734 final AttachInfo attachInfo = mAttachInfo; 11735 if (attachInfo != null) { 11736 return attachInfo.mHandler.postDelayed(action, delayMillis); 11737 } 11738 // Assume that post will succeed later 11739 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 11740 return true; 11741 } 11742 11743 /** 11744 * <p>Causes the Runnable to execute on the next animation time step. 11745 * The runnable will be run on the user interface thread.</p> 11746 * 11747 * @param action The Runnable that will be executed. 11748 * 11749 * @see #postOnAnimationDelayed 11750 * @see #removeCallbacks 11751 */ 11752 public void postOnAnimation(Runnable action) { 11753 final AttachInfo attachInfo = mAttachInfo; 11754 if (attachInfo != null) { 11755 attachInfo.mViewRootImpl.mChoreographer.postCallback( 11756 Choreographer.CALLBACK_ANIMATION, action, null); 11757 } else { 11758 // Assume that post will succeed later 11759 ViewRootImpl.getRunQueue().post(action); 11760 } 11761 } 11762 11763 /** 11764 * <p>Causes the Runnable to execute on the next animation time step, 11765 * after the specified amount of time elapses. 11766 * The runnable will be run on the user interface thread.</p> 11767 * 11768 * @param action The Runnable that will be executed. 11769 * @param delayMillis The delay (in milliseconds) until the Runnable 11770 * will be executed. 11771 * 11772 * @see #postOnAnimation 11773 * @see #removeCallbacks 11774 */ 11775 public void postOnAnimationDelayed(Runnable action, long delayMillis) { 11776 final AttachInfo attachInfo = mAttachInfo; 11777 if (attachInfo != null) { 11778 attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 11779 Choreographer.CALLBACK_ANIMATION, action, null, delayMillis); 11780 } else { 11781 // Assume that post will succeed later 11782 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 11783 } 11784 } 11785 11786 /** 11787 * <p>Removes the specified Runnable from the message queue.</p> 11788 * 11789 * @param action The Runnable to remove from the message handling queue 11790 * 11791 * @return true if this view could ask the Handler to remove the Runnable, 11792 * false otherwise. When the returned value is true, the Runnable 11793 * may or may not have been actually removed from the message queue 11794 * (for instance, if the Runnable was not in the queue already.) 11795 * 11796 * @see #post 11797 * @see #postDelayed 11798 * @see #postOnAnimation 11799 * @see #postOnAnimationDelayed 11800 */ 11801 public boolean removeCallbacks(Runnable action) { 11802 if (action != null) { 11803 final AttachInfo attachInfo = mAttachInfo; 11804 if (attachInfo != null) { 11805 attachInfo.mHandler.removeCallbacks(action); 11806 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 11807 Choreographer.CALLBACK_ANIMATION, action, null); 11808 } 11809 // Assume that post will succeed later 11810 ViewRootImpl.getRunQueue().removeCallbacks(action); 11811 } 11812 return true; 11813 } 11814 11815 /** 11816 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 11817 * Use this to invalidate the View from a non-UI thread.</p> 11818 * 11819 * <p>This method can be invoked from outside of the UI thread 11820 * only when this View is attached to a window.</p> 11821 * 11822 * @see #invalidate() 11823 * @see #postInvalidateDelayed(long) 11824 */ 11825 public void postInvalidate() { 11826 postInvalidateDelayed(0); 11827 } 11828 11829 /** 11830 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 11831 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 11832 * 11833 * <p>This method can be invoked from outside of the UI thread 11834 * only when this View is attached to a window.</p> 11835 * 11836 * @param left The left coordinate of the rectangle to invalidate. 11837 * @param top The top coordinate of the rectangle to invalidate. 11838 * @param right The right coordinate of the rectangle to invalidate. 11839 * @param bottom The bottom coordinate of the rectangle to invalidate. 11840 * 11841 * @see #invalidate(int, int, int, int) 11842 * @see #invalidate(Rect) 11843 * @see #postInvalidateDelayed(long, int, int, int, int) 11844 */ 11845 public void postInvalidate(int left, int top, int right, int bottom) { 11846 postInvalidateDelayed(0, left, top, right, bottom); 11847 } 11848 11849 /** 11850 * <p>Cause an invalidate to happen on a subsequent cycle through the event 11851 * loop. Waits for the specified amount of time.</p> 11852 * 11853 * <p>This method can be invoked from outside of the UI thread 11854 * only when this View is attached to a window.</p> 11855 * 11856 * @param delayMilliseconds the duration in milliseconds to delay the 11857 * invalidation by 11858 * 11859 * @see #invalidate() 11860 * @see #postInvalidate() 11861 */ 11862 public void postInvalidateDelayed(long delayMilliseconds) { 11863 // We try only with the AttachInfo because there's no point in invalidating 11864 // if we are not attached to our window 11865 final AttachInfo attachInfo = mAttachInfo; 11866 if (attachInfo != null) { 11867 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); 11868 } 11869 } 11870 11871 /** 11872 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 11873 * through the event loop. Waits for the specified amount of time.</p> 11874 * 11875 * <p>This method can be invoked from outside of the UI thread 11876 * only when this View is attached to a window.</p> 11877 * 11878 * @param delayMilliseconds the duration in milliseconds to delay the 11879 * invalidation by 11880 * @param left The left coordinate of the rectangle to invalidate. 11881 * @param top The top coordinate of the rectangle to invalidate. 11882 * @param right The right coordinate of the rectangle to invalidate. 11883 * @param bottom The bottom coordinate of the rectangle to invalidate. 11884 * 11885 * @see #invalidate(int, int, int, int) 11886 * @see #invalidate(Rect) 11887 * @see #postInvalidate(int, int, int, int) 11888 */ 11889 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 11890 int right, int bottom) { 11891 11892 // We try only with the AttachInfo because there's no point in invalidating 11893 // if we are not attached to our window 11894 final AttachInfo attachInfo = mAttachInfo; 11895 if (attachInfo != null) { 11896 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 11897 info.target = this; 11898 info.left = left; 11899 info.top = top; 11900 info.right = right; 11901 info.bottom = bottom; 11902 11903 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); 11904 } 11905 } 11906 11907 /** 11908 * <p>Cause an invalidate to happen on the next animation time step, typically the 11909 * next display frame.</p> 11910 * 11911 * <p>This method can be invoked from outside of the UI thread 11912 * only when this View is attached to a window.</p> 11913 * 11914 * @see #invalidate() 11915 */ 11916 public void postInvalidateOnAnimation() { 11917 // We try only with the AttachInfo because there's no point in invalidating 11918 // if we are not attached to our window 11919 final AttachInfo attachInfo = mAttachInfo; 11920 if (attachInfo != null) { 11921 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); 11922 } 11923 } 11924 11925 /** 11926 * <p>Cause an invalidate of the specified area to happen on the next animation 11927 * time step, typically the next display frame.</p> 11928 * 11929 * <p>This method can be invoked from outside of the UI thread 11930 * only when this View is attached to a window.</p> 11931 * 11932 * @param left The left coordinate of the rectangle to invalidate. 11933 * @param top The top coordinate of the rectangle to invalidate. 11934 * @param right The right coordinate of the rectangle to invalidate. 11935 * @param bottom The bottom coordinate of the rectangle to invalidate. 11936 * 11937 * @see #invalidate(int, int, int, int) 11938 * @see #invalidate(Rect) 11939 */ 11940 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { 11941 // We try only with the AttachInfo because there's no point in invalidating 11942 // if we are not attached to our window 11943 final AttachInfo attachInfo = mAttachInfo; 11944 if (attachInfo != null) { 11945 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 11946 info.target = this; 11947 info.left = left; 11948 info.top = top; 11949 info.right = right; 11950 info.bottom = bottom; 11951 11952 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); 11953 } 11954 } 11955 11956 /** 11957 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 11958 * This event is sent at most once every 11959 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 11960 */ 11961 private void postSendViewScrolledAccessibilityEventCallback() { 11962 if (mSendViewScrolledAccessibilityEvent == null) { 11963 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 11964 } 11965 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 11966 mSendViewScrolledAccessibilityEvent.mIsPending = true; 11967 postDelayed(mSendViewScrolledAccessibilityEvent, 11968 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 11969 } 11970 } 11971 11972 /** 11973 * Called by a parent to request that a child update its values for mScrollX 11974 * and mScrollY if necessary. This will typically be done if the child is 11975 * animating a scroll using a {@link android.widget.Scroller Scroller} 11976 * object. 11977 */ 11978 public void computeScroll() { 11979 } 11980 11981 /** 11982 * <p>Indicate whether the horizontal edges are faded when the view is 11983 * scrolled horizontally.</p> 11984 * 11985 * @return true if the horizontal edges should are faded on scroll, false 11986 * otherwise 11987 * 11988 * @see #setHorizontalFadingEdgeEnabled(boolean) 11989 * 11990 * @attr ref android.R.styleable#View_requiresFadingEdge 11991 */ 11992 public boolean isHorizontalFadingEdgeEnabled() { 11993 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 11994 } 11995 11996 /** 11997 * <p>Define whether the horizontal edges should be faded when this view 11998 * is scrolled horizontally.</p> 11999 * 12000 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 12001 * be faded when the view is scrolled 12002 * horizontally 12003 * 12004 * @see #isHorizontalFadingEdgeEnabled() 12005 * 12006 * @attr ref android.R.styleable#View_requiresFadingEdge 12007 */ 12008 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 12009 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 12010 if (horizontalFadingEdgeEnabled) { 12011 initScrollCache(); 12012 } 12013 12014 mViewFlags ^= FADING_EDGE_HORIZONTAL; 12015 } 12016 } 12017 12018 /** 12019 * <p>Indicate whether the vertical edges are faded when the view is 12020 * scrolled horizontally.</p> 12021 * 12022 * @return true if the vertical edges should are faded on scroll, false 12023 * otherwise 12024 * 12025 * @see #setVerticalFadingEdgeEnabled(boolean) 12026 * 12027 * @attr ref android.R.styleable#View_requiresFadingEdge 12028 */ 12029 public boolean isVerticalFadingEdgeEnabled() { 12030 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 12031 } 12032 12033 /** 12034 * <p>Define whether the vertical edges should be faded when this view 12035 * is scrolled vertically.</p> 12036 * 12037 * @param verticalFadingEdgeEnabled true if the vertical edges should 12038 * be faded when the view is scrolled 12039 * vertically 12040 * 12041 * @see #isVerticalFadingEdgeEnabled() 12042 * 12043 * @attr ref android.R.styleable#View_requiresFadingEdge 12044 */ 12045 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 12046 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 12047 if (verticalFadingEdgeEnabled) { 12048 initScrollCache(); 12049 } 12050 12051 mViewFlags ^= FADING_EDGE_VERTICAL; 12052 } 12053 } 12054 12055 /** 12056 * Returns the strength, or intensity, of the top faded edge. The strength is 12057 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12058 * returns 0.0 or 1.0 but no value in between. 12059 * 12060 * Subclasses should override this method to provide a smoother fade transition 12061 * when scrolling occurs. 12062 * 12063 * @return the intensity of the top fade as a float between 0.0f and 1.0f 12064 */ 12065 protected float getTopFadingEdgeStrength() { 12066 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 12067 } 12068 12069 /** 12070 * Returns the strength, or intensity, of the bottom faded edge. The strength is 12071 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12072 * returns 0.0 or 1.0 but no value in between. 12073 * 12074 * Subclasses should override this method to provide a smoother fade transition 12075 * when scrolling occurs. 12076 * 12077 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 12078 */ 12079 protected float getBottomFadingEdgeStrength() { 12080 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 12081 computeVerticalScrollRange() ? 1.0f : 0.0f; 12082 } 12083 12084 /** 12085 * Returns the strength, or intensity, of the left faded edge. The strength is 12086 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12087 * returns 0.0 or 1.0 but no value in between. 12088 * 12089 * Subclasses should override this method to provide a smoother fade transition 12090 * when scrolling occurs. 12091 * 12092 * @return the intensity of the left fade as a float between 0.0f and 1.0f 12093 */ 12094 protected float getLeftFadingEdgeStrength() { 12095 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 12096 } 12097 12098 /** 12099 * Returns the strength, or intensity, of the right faded edge. The strength is 12100 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12101 * returns 0.0 or 1.0 but no value in between. 12102 * 12103 * Subclasses should override this method to provide a smoother fade transition 12104 * when scrolling occurs. 12105 * 12106 * @return the intensity of the right fade as a float between 0.0f and 1.0f 12107 */ 12108 protected float getRightFadingEdgeStrength() { 12109 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 12110 computeHorizontalScrollRange() ? 1.0f : 0.0f; 12111 } 12112 12113 /** 12114 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 12115 * scrollbar is not drawn by default.</p> 12116 * 12117 * @return true if the horizontal scrollbar should be painted, false 12118 * otherwise 12119 * 12120 * @see #setHorizontalScrollBarEnabled(boolean) 12121 */ 12122 public boolean isHorizontalScrollBarEnabled() { 12123 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 12124 } 12125 12126 /** 12127 * <p>Define whether the horizontal scrollbar should be drawn or not. The 12128 * scrollbar is not drawn by default.</p> 12129 * 12130 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 12131 * be painted 12132 * 12133 * @see #isHorizontalScrollBarEnabled() 12134 */ 12135 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 12136 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 12137 mViewFlags ^= SCROLLBARS_HORIZONTAL; 12138 computeOpaqueFlags(); 12139 resolvePadding(); 12140 } 12141 } 12142 12143 /** 12144 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 12145 * scrollbar is not drawn by default.</p> 12146 * 12147 * @return true if the vertical scrollbar should be painted, false 12148 * otherwise 12149 * 12150 * @see #setVerticalScrollBarEnabled(boolean) 12151 */ 12152 public boolean isVerticalScrollBarEnabled() { 12153 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 12154 } 12155 12156 /** 12157 * <p>Define whether the vertical scrollbar should be drawn or not. The 12158 * scrollbar is not drawn by default.</p> 12159 * 12160 * @param verticalScrollBarEnabled true if the vertical scrollbar should 12161 * be painted 12162 * 12163 * @see #isVerticalScrollBarEnabled() 12164 */ 12165 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 12166 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 12167 mViewFlags ^= SCROLLBARS_VERTICAL; 12168 computeOpaqueFlags(); 12169 resolvePadding(); 12170 } 12171 } 12172 12173 /** 12174 * @hide 12175 */ 12176 protected void recomputePadding() { 12177 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 12178 } 12179 12180 /** 12181 * Define whether scrollbars will fade when the view is not scrolling. 12182 * 12183 * @param fadeScrollbars wheter to enable fading 12184 * 12185 * @attr ref android.R.styleable#View_fadeScrollbars 12186 */ 12187 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 12188 initScrollCache(); 12189 final ScrollabilityCache scrollabilityCache = mScrollCache; 12190 scrollabilityCache.fadeScrollBars = fadeScrollbars; 12191 if (fadeScrollbars) { 12192 scrollabilityCache.state = ScrollabilityCache.OFF; 12193 } else { 12194 scrollabilityCache.state = ScrollabilityCache.ON; 12195 } 12196 } 12197 12198 /** 12199 * 12200 * Returns true if scrollbars will fade when this view is not scrolling 12201 * 12202 * @return true if scrollbar fading is enabled 12203 * 12204 * @attr ref android.R.styleable#View_fadeScrollbars 12205 */ 12206 public boolean isScrollbarFadingEnabled() { 12207 return mScrollCache != null && mScrollCache.fadeScrollBars; 12208 } 12209 12210 /** 12211 * 12212 * Returns the delay before scrollbars fade. 12213 * 12214 * @return the delay before scrollbars fade 12215 * 12216 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 12217 */ 12218 public int getScrollBarDefaultDelayBeforeFade() { 12219 return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() : 12220 mScrollCache.scrollBarDefaultDelayBeforeFade; 12221 } 12222 12223 /** 12224 * Define the delay before scrollbars fade. 12225 * 12226 * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade 12227 * 12228 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 12229 */ 12230 public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) { 12231 getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade; 12232 } 12233 12234 /** 12235 * 12236 * Returns the scrollbar fade duration. 12237 * 12238 * @return the scrollbar fade duration 12239 * 12240 * @attr ref android.R.styleable#View_scrollbarFadeDuration 12241 */ 12242 public int getScrollBarFadeDuration() { 12243 return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() : 12244 mScrollCache.scrollBarFadeDuration; 12245 } 12246 12247 /** 12248 * Define the scrollbar fade duration. 12249 * 12250 * @param scrollBarFadeDuration - the scrollbar fade duration 12251 * 12252 * @attr ref android.R.styleable#View_scrollbarFadeDuration 12253 */ 12254 public void setScrollBarFadeDuration(int scrollBarFadeDuration) { 12255 getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration; 12256 } 12257 12258 /** 12259 * 12260 * Returns the scrollbar size. 12261 * 12262 * @return the scrollbar size 12263 * 12264 * @attr ref android.R.styleable#View_scrollbarSize 12265 */ 12266 public int getScrollBarSize() { 12267 return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() : 12268 mScrollCache.scrollBarSize; 12269 } 12270 12271 /** 12272 * Define the scrollbar size. 12273 * 12274 * @param scrollBarSize - the scrollbar size 12275 * 12276 * @attr ref android.R.styleable#View_scrollbarSize 12277 */ 12278 public void setScrollBarSize(int scrollBarSize) { 12279 getScrollCache().scrollBarSize = scrollBarSize; 12280 } 12281 12282 /** 12283 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 12284 * inset. When inset, they add to the padding of the view. And the scrollbars 12285 * can be drawn inside the padding area or on the edge of the view. For example, 12286 * if a view has a background drawable and you want to draw the scrollbars 12287 * inside the padding specified by the drawable, you can use 12288 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 12289 * appear at the edge of the view, ignoring the padding, then you can use 12290 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 12291 * @param style the style of the scrollbars. Should be one of 12292 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 12293 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 12294 * @see #SCROLLBARS_INSIDE_OVERLAY 12295 * @see #SCROLLBARS_INSIDE_INSET 12296 * @see #SCROLLBARS_OUTSIDE_OVERLAY 12297 * @see #SCROLLBARS_OUTSIDE_INSET 12298 * 12299 * @attr ref android.R.styleable#View_scrollbarStyle 12300 */ 12301 public void setScrollBarStyle(@ScrollBarStyle int style) { 12302 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 12303 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 12304 computeOpaqueFlags(); 12305 resolvePadding(); 12306 } 12307 } 12308 12309 /** 12310 * <p>Returns the current scrollbar style.</p> 12311 * @return the current scrollbar style 12312 * @see #SCROLLBARS_INSIDE_OVERLAY 12313 * @see #SCROLLBARS_INSIDE_INSET 12314 * @see #SCROLLBARS_OUTSIDE_OVERLAY 12315 * @see #SCROLLBARS_OUTSIDE_INSET 12316 * 12317 * @attr ref android.R.styleable#View_scrollbarStyle 12318 */ 12319 @ViewDebug.ExportedProperty(mapping = { 12320 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 12321 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 12322 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 12323 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 12324 }) 12325 @ScrollBarStyle 12326 public int getScrollBarStyle() { 12327 return mViewFlags & SCROLLBARS_STYLE_MASK; 12328 } 12329 12330 /** 12331 * <p>Compute the horizontal range that the horizontal scrollbar 12332 * represents.</p> 12333 * 12334 * <p>The range is expressed in arbitrary units that must be the same as the 12335 * units used by {@link #computeHorizontalScrollExtent()} and 12336 * {@link #computeHorizontalScrollOffset()}.</p> 12337 * 12338 * <p>The default range is the drawing width of this view.</p> 12339 * 12340 * @return the total horizontal range represented by the horizontal 12341 * scrollbar 12342 * 12343 * @see #computeHorizontalScrollExtent() 12344 * @see #computeHorizontalScrollOffset() 12345 * @see android.widget.ScrollBarDrawable 12346 */ 12347 protected int computeHorizontalScrollRange() { 12348 return getWidth(); 12349 } 12350 12351 /** 12352 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 12353 * within the horizontal range. This value is used to compute the position 12354 * of the thumb within the scrollbar's track.</p> 12355 * 12356 * <p>The range is expressed in arbitrary units that must be the same as the 12357 * units used by {@link #computeHorizontalScrollRange()} and 12358 * {@link #computeHorizontalScrollExtent()}.</p> 12359 * 12360 * <p>The default offset is the scroll offset of this view.</p> 12361 * 12362 * @return the horizontal offset of the scrollbar's thumb 12363 * 12364 * @see #computeHorizontalScrollRange() 12365 * @see #computeHorizontalScrollExtent() 12366 * @see android.widget.ScrollBarDrawable 12367 */ 12368 protected int computeHorizontalScrollOffset() { 12369 return mScrollX; 12370 } 12371 12372 /** 12373 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 12374 * within the horizontal range. This value is used to compute the length 12375 * of the thumb within the scrollbar's track.</p> 12376 * 12377 * <p>The range is expressed in arbitrary units that must be the same as the 12378 * units used by {@link #computeHorizontalScrollRange()} and 12379 * {@link #computeHorizontalScrollOffset()}.</p> 12380 * 12381 * <p>The default extent is the drawing width of this view.</p> 12382 * 12383 * @return the horizontal extent of the scrollbar's thumb 12384 * 12385 * @see #computeHorizontalScrollRange() 12386 * @see #computeHorizontalScrollOffset() 12387 * @see android.widget.ScrollBarDrawable 12388 */ 12389 protected int computeHorizontalScrollExtent() { 12390 return getWidth(); 12391 } 12392 12393 /** 12394 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 12395 * 12396 * <p>The range is expressed in arbitrary units that must be the same as the 12397 * units used by {@link #computeVerticalScrollExtent()} and 12398 * {@link #computeVerticalScrollOffset()}.</p> 12399 * 12400 * @return the total vertical range represented by the vertical scrollbar 12401 * 12402 * <p>The default range is the drawing height of this view.</p> 12403 * 12404 * @see #computeVerticalScrollExtent() 12405 * @see #computeVerticalScrollOffset() 12406 * @see android.widget.ScrollBarDrawable 12407 */ 12408 protected int computeVerticalScrollRange() { 12409 return getHeight(); 12410 } 12411 12412 /** 12413 * <p>Compute the vertical offset of the vertical scrollbar's thumb 12414 * within the horizontal range. This value is used to compute the position 12415 * of the thumb within the scrollbar's track.</p> 12416 * 12417 * <p>The range is expressed in arbitrary units that must be the same as the 12418 * units used by {@link #computeVerticalScrollRange()} and 12419 * {@link #computeVerticalScrollExtent()}.</p> 12420 * 12421 * <p>The default offset is the scroll offset of this view.</p> 12422 * 12423 * @return the vertical offset of the scrollbar's thumb 12424 * 12425 * @see #computeVerticalScrollRange() 12426 * @see #computeVerticalScrollExtent() 12427 * @see android.widget.ScrollBarDrawable 12428 */ 12429 protected int computeVerticalScrollOffset() { 12430 return mScrollY; 12431 } 12432 12433 /** 12434 * <p>Compute the vertical extent of the vertical scrollbar's thumb 12435 * within the vertical range. This value is used to compute the length 12436 * of the thumb within the scrollbar's track.</p> 12437 * 12438 * <p>The range is expressed in arbitrary units that must be the same as the 12439 * units used by {@link #computeVerticalScrollRange()} and 12440 * {@link #computeVerticalScrollOffset()}.</p> 12441 * 12442 * <p>The default extent is the drawing height of this view.</p> 12443 * 12444 * @return the vertical extent of the scrollbar's thumb 12445 * 12446 * @see #computeVerticalScrollRange() 12447 * @see #computeVerticalScrollOffset() 12448 * @see android.widget.ScrollBarDrawable 12449 */ 12450 protected int computeVerticalScrollExtent() { 12451 return getHeight(); 12452 } 12453 12454 /** 12455 * Check if this view can be scrolled horizontally in a certain direction. 12456 * 12457 * @param direction Negative to check scrolling left, positive to check scrolling right. 12458 * @return true if this view can be scrolled in the specified direction, false otherwise. 12459 */ 12460 public boolean canScrollHorizontally(int direction) { 12461 final int offset = computeHorizontalScrollOffset(); 12462 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 12463 if (range == 0) return false; 12464 if (direction < 0) { 12465 return offset > 0; 12466 } else { 12467 return offset < range - 1; 12468 } 12469 } 12470 12471 /** 12472 * Check if this view can be scrolled vertically in a certain direction. 12473 * 12474 * @param direction Negative to check scrolling up, positive to check scrolling down. 12475 * @return true if this view can be scrolled in the specified direction, false otherwise. 12476 */ 12477 public boolean canScrollVertically(int direction) { 12478 final int offset = computeVerticalScrollOffset(); 12479 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 12480 if (range == 0) return false; 12481 if (direction < 0) { 12482 return offset > 0; 12483 } else { 12484 return offset < range - 1; 12485 } 12486 } 12487 12488 /** 12489 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 12490 * scrollbars are painted only if they have been awakened first.</p> 12491 * 12492 * @param canvas the canvas on which to draw the scrollbars 12493 * 12494 * @see #awakenScrollBars(int) 12495 */ 12496 protected final void onDrawScrollBars(Canvas canvas) { 12497 // scrollbars are drawn only when the animation is running 12498 final ScrollabilityCache cache = mScrollCache; 12499 if (cache != null) { 12500 12501 int state = cache.state; 12502 12503 if (state == ScrollabilityCache.OFF) { 12504 return; 12505 } 12506 12507 boolean invalidate = false; 12508 12509 if (state == ScrollabilityCache.FADING) { 12510 // We're fading -- get our fade interpolation 12511 if (cache.interpolatorValues == null) { 12512 cache.interpolatorValues = new float[1]; 12513 } 12514 12515 float[] values = cache.interpolatorValues; 12516 12517 // Stops the animation if we're done 12518 if (cache.scrollBarInterpolator.timeToValues(values) == 12519 Interpolator.Result.FREEZE_END) { 12520 cache.state = ScrollabilityCache.OFF; 12521 } else { 12522 cache.scrollBar.setAlpha(Math.round(values[0])); 12523 } 12524 12525 // This will make the scroll bars inval themselves after 12526 // drawing. We only want this when we're fading so that 12527 // we prevent excessive redraws 12528 invalidate = true; 12529 } else { 12530 // We're just on -- but we may have been fading before so 12531 // reset alpha 12532 cache.scrollBar.setAlpha(255); 12533 } 12534 12535 12536 final int viewFlags = mViewFlags; 12537 12538 final boolean drawHorizontalScrollBar = 12539 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 12540 final boolean drawVerticalScrollBar = 12541 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 12542 && !isVerticalScrollBarHidden(); 12543 12544 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 12545 final int width = mRight - mLeft; 12546 final int height = mBottom - mTop; 12547 12548 final ScrollBarDrawable scrollBar = cache.scrollBar; 12549 12550 final int scrollX = mScrollX; 12551 final int scrollY = mScrollY; 12552 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 12553 12554 int left; 12555 int top; 12556 int right; 12557 int bottom; 12558 12559 if (drawHorizontalScrollBar) { 12560 int size = scrollBar.getSize(false); 12561 if (size <= 0) { 12562 size = cache.scrollBarSize; 12563 } 12564 12565 scrollBar.setParameters(computeHorizontalScrollRange(), 12566 computeHorizontalScrollOffset(), 12567 computeHorizontalScrollExtent(), false); 12568 final int verticalScrollBarGap = drawVerticalScrollBar ? 12569 getVerticalScrollbarWidth() : 0; 12570 top = scrollY + height - size - (mUserPaddingBottom & inside); 12571 left = scrollX + (mPaddingLeft & inside); 12572 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 12573 bottom = top + size; 12574 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 12575 if (invalidate) { 12576 invalidate(left, top, right, bottom); 12577 } 12578 } 12579 12580 if (drawVerticalScrollBar) { 12581 int size = scrollBar.getSize(true); 12582 if (size <= 0) { 12583 size = cache.scrollBarSize; 12584 } 12585 12586 scrollBar.setParameters(computeVerticalScrollRange(), 12587 computeVerticalScrollOffset(), 12588 computeVerticalScrollExtent(), true); 12589 int verticalScrollbarPosition = mVerticalScrollbarPosition; 12590 if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) { 12591 verticalScrollbarPosition = isLayoutRtl() ? 12592 SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT; 12593 } 12594 switch (verticalScrollbarPosition) { 12595 default: 12596 case SCROLLBAR_POSITION_RIGHT: 12597 left = scrollX + width - size - (mUserPaddingRight & inside); 12598 break; 12599 case SCROLLBAR_POSITION_LEFT: 12600 left = scrollX + (mUserPaddingLeft & inside); 12601 break; 12602 } 12603 top = scrollY + (mPaddingTop & inside); 12604 right = left + size; 12605 bottom = scrollY + height - (mUserPaddingBottom & inside); 12606 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 12607 if (invalidate) { 12608 invalidate(left, top, right, bottom); 12609 } 12610 } 12611 } 12612 } 12613 } 12614 12615 /** 12616 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 12617 * FastScroller is visible. 12618 * @return whether to temporarily hide the vertical scrollbar 12619 * @hide 12620 */ 12621 protected boolean isVerticalScrollBarHidden() { 12622 return false; 12623 } 12624 12625 /** 12626 * <p>Draw the horizontal scrollbar if 12627 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 12628 * 12629 * @param canvas the canvas on which to draw the scrollbar 12630 * @param scrollBar the scrollbar's drawable 12631 * 12632 * @see #isHorizontalScrollBarEnabled() 12633 * @see #computeHorizontalScrollRange() 12634 * @see #computeHorizontalScrollExtent() 12635 * @see #computeHorizontalScrollOffset() 12636 * @see android.widget.ScrollBarDrawable 12637 * @hide 12638 */ 12639 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 12640 int l, int t, int r, int b) { 12641 scrollBar.setBounds(l, t, r, b); 12642 scrollBar.draw(canvas); 12643 } 12644 12645 /** 12646 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 12647 * returns true.</p> 12648 * 12649 * @param canvas the canvas on which to draw the scrollbar 12650 * @param scrollBar the scrollbar's drawable 12651 * 12652 * @see #isVerticalScrollBarEnabled() 12653 * @see #computeVerticalScrollRange() 12654 * @see #computeVerticalScrollExtent() 12655 * @see #computeVerticalScrollOffset() 12656 * @see android.widget.ScrollBarDrawable 12657 * @hide 12658 */ 12659 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 12660 int l, int t, int r, int b) { 12661 scrollBar.setBounds(l, t, r, b); 12662 scrollBar.draw(canvas); 12663 } 12664 12665 /** 12666 * Implement this to do your drawing. 12667 * 12668 * @param canvas the canvas on which the background will be drawn 12669 */ 12670 protected void onDraw(Canvas canvas) { 12671 } 12672 12673 /* 12674 * Caller is responsible for calling requestLayout if necessary. 12675 * (This allows addViewInLayout to not request a new layout.) 12676 */ 12677 void assignParent(ViewParent parent) { 12678 if (mParent == null) { 12679 mParent = parent; 12680 } else if (parent == null) { 12681 mParent = null; 12682 } else { 12683 throw new RuntimeException("view " + this + " being added, but" 12684 + " it already has a parent"); 12685 } 12686 } 12687 12688 /** 12689 * This is called when the view is attached to a window. At this point it 12690 * has a Surface and will start drawing. Note that this function is 12691 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 12692 * however it may be called any time before the first onDraw -- including 12693 * before or after {@link #onMeasure(int, int)}. 12694 * 12695 * @see #onDetachedFromWindow() 12696 */ 12697 protected void onAttachedToWindow() { 12698 if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 12699 mParent.requestTransparentRegion(this); 12700 } 12701 12702 if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { 12703 initialAwakenScrollBars(); 12704 mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 12705 } 12706 12707 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 12708 12709 jumpDrawablesToCurrentState(); 12710 12711 resetSubtreeAccessibilityStateChanged(); 12712 12713 if (isFocused()) { 12714 InputMethodManager imm = InputMethodManager.peekInstance(); 12715 imm.focusIn(this); 12716 } 12717 } 12718 12719 /** 12720 * Resolve all RTL related properties. 12721 * 12722 * @return true if resolution of RTL properties has been done 12723 * 12724 * @hide 12725 */ 12726 public boolean resolveRtlPropertiesIfNeeded() { 12727 if (!needRtlPropertiesResolution()) return false; 12728 12729 // Order is important here: LayoutDirection MUST be resolved first 12730 if (!isLayoutDirectionResolved()) { 12731 resolveLayoutDirection(); 12732 resolveLayoutParams(); 12733 } 12734 // ... then we can resolve the others properties depending on the resolved LayoutDirection. 12735 if (!isTextDirectionResolved()) { 12736 resolveTextDirection(); 12737 } 12738 if (!isTextAlignmentResolved()) { 12739 resolveTextAlignment(); 12740 } 12741 // Should resolve Drawables before Padding because we need the layout direction of the 12742 // Drawable to correctly resolve Padding. 12743 if (!isDrawablesResolved()) { 12744 resolveDrawables(); 12745 } 12746 if (!isPaddingResolved()) { 12747 resolvePadding(); 12748 } 12749 onRtlPropertiesChanged(getLayoutDirection()); 12750 return true; 12751 } 12752 12753 /** 12754 * Reset resolution of all RTL related properties. 12755 * 12756 * @hide 12757 */ 12758 public void resetRtlProperties() { 12759 resetResolvedLayoutDirection(); 12760 resetResolvedTextDirection(); 12761 resetResolvedTextAlignment(); 12762 resetResolvedPadding(); 12763 resetResolvedDrawables(); 12764 } 12765 12766 /** 12767 * @see #onScreenStateChanged(int) 12768 */ 12769 void dispatchScreenStateChanged(int screenState) { 12770 onScreenStateChanged(screenState); 12771 } 12772 12773 /** 12774 * This method is called whenever the state of the screen this view is 12775 * attached to changes. A state change will usually occurs when the screen 12776 * turns on or off (whether it happens automatically or the user does it 12777 * manually.) 12778 * 12779 * @param screenState The new state of the screen. Can be either 12780 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF} 12781 */ 12782 public void onScreenStateChanged(int screenState) { 12783 } 12784 12785 /** 12786 * Return true if the application tag in the AndroidManifest has set "supportRtl" to true 12787 */ 12788 private boolean hasRtlSupport() { 12789 return mContext.getApplicationInfo().hasRtlSupport(); 12790 } 12791 12792 /** 12793 * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or 12794 * RTL not supported) 12795 */ 12796 private boolean isRtlCompatibilityMode() { 12797 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 12798 return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport(); 12799 } 12800 12801 /** 12802 * @return true if RTL properties need resolution. 12803 * 12804 */ 12805 private boolean needRtlPropertiesResolution() { 12806 return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED; 12807 } 12808 12809 /** 12810 * Called when any RTL property (layout direction or text direction or text alignment) has 12811 * been changed. 12812 * 12813 * Subclasses need to override this method to take care of cached information that depends on the 12814 * resolved layout direction, or to inform child views that inherit their layout direction. 12815 * 12816 * The default implementation does nothing. 12817 * 12818 * @param layoutDirection the direction of the layout 12819 * 12820 * @see #LAYOUT_DIRECTION_LTR 12821 * @see #LAYOUT_DIRECTION_RTL 12822 */ 12823 public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) { 12824 } 12825 12826 /** 12827 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 12828 * that the parent directionality can and will be resolved before its children. 12829 * 12830 * @return true if resolution has been done, false otherwise. 12831 * 12832 * @hide 12833 */ 12834 public boolean resolveLayoutDirection() { 12835 // Clear any previous layout direction resolution 12836 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 12837 12838 if (hasRtlSupport()) { 12839 // Set resolved depending on layout direction 12840 switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> 12841 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) { 12842 case LAYOUT_DIRECTION_INHERIT: 12843 // We cannot resolve yet. LTR is by default and let the resolution happen again 12844 // later to get the correct resolved value 12845 if (!canResolveLayoutDirection()) return false; 12846 12847 // Parent has not yet resolved, LTR is still the default 12848 try { 12849 if (!mParent.isLayoutDirectionResolved()) return false; 12850 12851 if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 12852 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12853 } 12854 } catch (AbstractMethodError e) { 12855 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 12856 " does not fully implement ViewParent", e); 12857 } 12858 break; 12859 case LAYOUT_DIRECTION_RTL: 12860 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12861 break; 12862 case LAYOUT_DIRECTION_LOCALE: 12863 if((LAYOUT_DIRECTION_RTL == 12864 TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) { 12865 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12866 } 12867 break; 12868 default: 12869 // Nothing to do, LTR by default 12870 } 12871 } 12872 12873 // Set to resolved 12874 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 12875 return true; 12876 } 12877 12878 /** 12879 * Check if layout direction resolution can be done. 12880 * 12881 * @return true if layout direction resolution can be done otherwise return false. 12882 */ 12883 public boolean canResolveLayoutDirection() { 12884 switch (getRawLayoutDirection()) { 12885 case LAYOUT_DIRECTION_INHERIT: 12886 if (mParent != null) { 12887 try { 12888 return mParent.canResolveLayoutDirection(); 12889 } catch (AbstractMethodError e) { 12890 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 12891 " does not fully implement ViewParent", e); 12892 } 12893 } 12894 return false; 12895 12896 default: 12897 return true; 12898 } 12899 } 12900 12901 /** 12902 * Reset the resolved layout direction. Layout direction will be resolved during a call to 12903 * {@link #onMeasure(int, int)}. 12904 * 12905 * @hide 12906 */ 12907 public void resetResolvedLayoutDirection() { 12908 // Reset the current resolved bits 12909 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 12910 } 12911 12912 /** 12913 * @return true if the layout direction is inherited. 12914 * 12915 * @hide 12916 */ 12917 public boolean isLayoutDirectionInherited() { 12918 return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT); 12919 } 12920 12921 /** 12922 * @return true if layout direction has been resolved. 12923 */ 12924 public boolean isLayoutDirectionResolved() { 12925 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED; 12926 } 12927 12928 /** 12929 * Return if padding has been resolved 12930 * 12931 * @hide 12932 */ 12933 boolean isPaddingResolved() { 12934 return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED; 12935 } 12936 12937 /** 12938 * Resolves padding depending on layout direction, if applicable, and 12939 * recomputes internal padding values to adjust for scroll bars. 12940 * 12941 * @hide 12942 */ 12943 public void resolvePadding() { 12944 final int resolvedLayoutDirection = getLayoutDirection(); 12945 12946 if (!isRtlCompatibilityMode()) { 12947 // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account. 12948 // If start / end padding are defined, they will be resolved (hence overriding) to 12949 // left / right or right / left depending on the resolved layout direction. 12950 // If start / end padding are not defined, use the left / right ones. 12951 if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) { 12952 Rect padding = sThreadLocal.get(); 12953 if (padding == null) { 12954 padding = new Rect(); 12955 sThreadLocal.set(padding); 12956 } 12957 mBackground.getPadding(padding); 12958 if (!mLeftPaddingDefined) { 12959 mUserPaddingLeftInitial = padding.left; 12960 } 12961 if (!mRightPaddingDefined) { 12962 mUserPaddingRightInitial = padding.right; 12963 } 12964 } 12965 switch (resolvedLayoutDirection) { 12966 case LAYOUT_DIRECTION_RTL: 12967 if (mUserPaddingStart != UNDEFINED_PADDING) { 12968 mUserPaddingRight = mUserPaddingStart; 12969 } else { 12970 mUserPaddingRight = mUserPaddingRightInitial; 12971 } 12972 if (mUserPaddingEnd != UNDEFINED_PADDING) { 12973 mUserPaddingLeft = mUserPaddingEnd; 12974 } else { 12975 mUserPaddingLeft = mUserPaddingLeftInitial; 12976 } 12977 break; 12978 case LAYOUT_DIRECTION_LTR: 12979 default: 12980 if (mUserPaddingStart != UNDEFINED_PADDING) { 12981 mUserPaddingLeft = mUserPaddingStart; 12982 } else { 12983 mUserPaddingLeft = mUserPaddingLeftInitial; 12984 } 12985 if (mUserPaddingEnd != UNDEFINED_PADDING) { 12986 mUserPaddingRight = mUserPaddingEnd; 12987 } else { 12988 mUserPaddingRight = mUserPaddingRightInitial; 12989 } 12990 } 12991 12992 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 12993 } 12994 12995 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 12996 onRtlPropertiesChanged(resolvedLayoutDirection); 12997 12998 mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED; 12999 } 13000 13001 /** 13002 * Reset the resolved layout direction. 13003 * 13004 * @hide 13005 */ 13006 public void resetResolvedPadding() { 13007 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 13008 } 13009 13010 /** 13011 * This is called when the view is detached from a window. At this point it 13012 * no longer has a surface for drawing. 13013 * 13014 * @see #onAttachedToWindow() 13015 */ 13016 protected void onDetachedFromWindow() { 13017 } 13018 13019 /** 13020 * This is a framework-internal mirror of onDetachedFromWindow() that's called 13021 * after onDetachedFromWindow(). 13022 * 13023 * If you override this you *MUST* call super.onDetachedFromWindowInternal()! 13024 * The super method should be called at the end of the overriden method to ensure 13025 * subclasses are destroyed first 13026 * 13027 * @hide 13028 */ 13029 protected void onDetachedFromWindowInternal() { 13030 mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT; 13031 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 13032 13033 removeUnsetPressCallback(); 13034 removeLongPressCallback(); 13035 removePerformClickCallback(); 13036 removeSendViewScrolledAccessibilityEventCallback(); 13037 13038 destroyDrawingCache(); 13039 destroyLayer(false); 13040 13041 cleanupDraw(); 13042 13043 mCurrentAnimation = null; 13044 } 13045 13046 private void cleanupDraw() { 13047 resetDisplayList(); 13048 if (mAttachInfo != null) { 13049 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 13050 } 13051 } 13052 13053 /** 13054 * This method ensures the hardware renderer is in a valid state 13055 * before executing the specified action. 13056 * 13057 * This method will attempt to set a valid state even if the window 13058 * the renderer is attached to was destroyed. 13059 * 13060 * This method is not guaranteed to work. If the hardware renderer 13061 * does not exist or cannot be put in a valid state, this method 13062 * will not executed the specified action. 13063 * 13064 * The specified action is executed synchronously. 13065 * 13066 * @param action The action to execute after the renderer is in a valid state 13067 * 13068 * @return True if the specified Runnable was executed, false otherwise 13069 * 13070 * @hide 13071 */ 13072 public boolean executeHardwareAction(Runnable action) { 13073 //noinspection SimplifiableIfStatement 13074 if (mAttachInfo != null && mAttachInfo.mHardwareRenderer != null) { 13075 return mAttachInfo.mHardwareRenderer.safelyRun(action); 13076 } 13077 return false; 13078 } 13079 13080 void invalidateInheritedLayoutMode(int layoutModeOfRoot) { 13081 } 13082 13083 /** 13084 * @return The number of times this view has been attached to a window 13085 */ 13086 protected int getWindowAttachCount() { 13087 return mWindowAttachCount; 13088 } 13089 13090 /** 13091 * Retrieve a unique token identifying the window this view is attached to. 13092 * @return Return the window's token for use in 13093 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 13094 */ 13095 public IBinder getWindowToken() { 13096 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 13097 } 13098 13099 /** 13100 * Retrieve the {@link WindowId} for the window this view is 13101 * currently attached to. 13102 */ 13103 public WindowId getWindowId() { 13104 if (mAttachInfo == null) { 13105 return null; 13106 } 13107 if (mAttachInfo.mWindowId == null) { 13108 try { 13109 mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId( 13110 mAttachInfo.mWindowToken); 13111 mAttachInfo.mWindowId = new WindowId( 13112 mAttachInfo.mIWindowId); 13113 } catch (RemoteException e) { 13114 } 13115 } 13116 return mAttachInfo.mWindowId; 13117 } 13118 13119 /** 13120 * Retrieve a unique token identifying the top-level "real" window of 13121 * the window that this view is attached to. That is, this is like 13122 * {@link #getWindowToken}, except if the window this view in is a panel 13123 * window (attached to another containing window), then the token of 13124 * the containing window is returned instead. 13125 * 13126 * @return Returns the associated window token, either 13127 * {@link #getWindowToken()} or the containing window's token. 13128 */ 13129 public IBinder getApplicationWindowToken() { 13130 AttachInfo ai = mAttachInfo; 13131 if (ai != null) { 13132 IBinder appWindowToken = ai.mPanelParentWindowToken; 13133 if (appWindowToken == null) { 13134 appWindowToken = ai.mWindowToken; 13135 } 13136 return appWindowToken; 13137 } 13138 return null; 13139 } 13140 13141 /** 13142 * Gets the logical display to which the view's window has been attached. 13143 * 13144 * @return The logical display, or null if the view is not currently attached to a window. 13145 */ 13146 public Display getDisplay() { 13147 return mAttachInfo != null ? mAttachInfo.mDisplay : null; 13148 } 13149 13150 /** 13151 * Retrieve private session object this view hierarchy is using to 13152 * communicate with the window manager. 13153 * @return the session object to communicate with the window manager 13154 */ 13155 /*package*/ IWindowSession getWindowSession() { 13156 return mAttachInfo != null ? mAttachInfo.mSession : null; 13157 } 13158 13159 /** 13160 * @param info the {@link android.view.View.AttachInfo} to associated with 13161 * this view 13162 */ 13163 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 13164 //System.out.println("Attached! " + this); 13165 mAttachInfo = info; 13166 if (mOverlay != null) { 13167 mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility); 13168 } 13169 mWindowAttachCount++; 13170 // We will need to evaluate the drawable state at least once. 13171 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 13172 if (mFloatingTreeObserver != null) { 13173 info.mTreeObserver.merge(mFloatingTreeObserver); 13174 mFloatingTreeObserver = null; 13175 } 13176 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) { 13177 mAttachInfo.mScrollContainers.add(this); 13178 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 13179 } 13180 performCollectViewAttributes(mAttachInfo, visibility); 13181 onAttachedToWindow(); 13182 13183 ListenerInfo li = mListenerInfo; 13184 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 13185 li != null ? li.mOnAttachStateChangeListeners : null; 13186 if (listeners != null && listeners.size() > 0) { 13187 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 13188 // perform the dispatching. The iterator is a safe guard against listeners that 13189 // could mutate the list by calling the various add/remove methods. This prevents 13190 // the array from being modified while we iterate it. 13191 for (OnAttachStateChangeListener listener : listeners) { 13192 listener.onViewAttachedToWindow(this); 13193 } 13194 } 13195 13196 int vis = info.mWindowVisibility; 13197 if (vis != GONE) { 13198 onWindowVisibilityChanged(vis); 13199 } 13200 if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) { 13201 // If nobody has evaluated the drawable state yet, then do it now. 13202 refreshDrawableState(); 13203 } 13204 needGlobalAttributesUpdate(false); 13205 } 13206 13207 void dispatchDetachedFromWindow() { 13208 AttachInfo info = mAttachInfo; 13209 if (info != null) { 13210 int vis = info.mWindowVisibility; 13211 if (vis != GONE) { 13212 onWindowVisibilityChanged(GONE); 13213 } 13214 } 13215 13216 onDetachedFromWindow(); 13217 onDetachedFromWindowInternal(); 13218 13219 ListenerInfo li = mListenerInfo; 13220 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 13221 li != null ? li.mOnAttachStateChangeListeners : null; 13222 if (listeners != null && listeners.size() > 0) { 13223 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 13224 // perform the dispatching. The iterator is a safe guard against listeners that 13225 // could mutate the list by calling the various add/remove methods. This prevents 13226 // the array from being modified while we iterate it. 13227 for (OnAttachStateChangeListener listener : listeners) { 13228 listener.onViewDetachedFromWindow(this); 13229 } 13230 } 13231 13232 if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 13233 mAttachInfo.mScrollContainers.remove(this); 13234 mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED; 13235 } 13236 13237 mAttachInfo = null; 13238 if (mOverlay != null) { 13239 mOverlay.getOverlayView().dispatchDetachedFromWindow(); 13240 } 13241 } 13242 13243 /** 13244 * Cancel any deferred high-level input events that were previously posted to the event queue. 13245 * 13246 * <p>Many views post high-level events such as click handlers to the event queue 13247 * to run deferred in order to preserve a desired user experience - clearing visible 13248 * pressed states before executing, etc. This method will abort any events of this nature 13249 * that are currently in flight.</p> 13250 * 13251 * <p>Custom views that generate their own high-level deferred input events should override 13252 * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p> 13253 * 13254 * <p>This will also cancel pending input events for any child views.</p> 13255 * 13256 * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases. 13257 * This will not impact newer events posted after this call that may occur as a result of 13258 * lower-level input events still waiting in the queue. If you are trying to prevent 13259 * double-submitted events for the duration of some sort of asynchronous transaction 13260 * you should also take other steps to protect against unexpected double inputs e.g. calling 13261 * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when 13262 * the transaction completes, tracking already submitted transaction IDs, etc.</p> 13263 */ 13264 public final void cancelPendingInputEvents() { 13265 dispatchCancelPendingInputEvents(); 13266 } 13267 13268 /** 13269 * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight. 13270 * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling. 13271 */ 13272 void dispatchCancelPendingInputEvents() { 13273 mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER; 13274 onCancelPendingInputEvents(); 13275 if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) { 13276 throw new SuperNotCalledException("View " + getClass().getSimpleName() + 13277 " did not call through to super.onCancelPendingInputEvents()"); 13278 } 13279 } 13280 13281 /** 13282 * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or 13283 * a parent view. 13284 * 13285 * <p>This method is responsible for removing any pending high-level input events that were 13286 * posted to the event queue to run later. Custom view classes that post their own deferred 13287 * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or 13288 * {@link android.os.Handler} should override this method, call 13289 * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate. 13290 * </p> 13291 */ 13292 public void onCancelPendingInputEvents() { 13293 removePerformClickCallback(); 13294 cancelLongPress(); 13295 mPrivateFlags3 |= PFLAG3_CALLED_SUPER; 13296 } 13297 13298 /** 13299 * Store this view hierarchy's frozen state into the given container. 13300 * 13301 * @param container The SparseArray in which to save the view's state. 13302 * 13303 * @see #restoreHierarchyState(android.util.SparseArray) 13304 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13305 * @see #onSaveInstanceState() 13306 */ 13307 public void saveHierarchyState(SparseArray<Parcelable> container) { 13308 dispatchSaveInstanceState(container); 13309 } 13310 13311 /** 13312 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 13313 * this view and its children. May be overridden to modify how freezing happens to a 13314 * view's children; for example, some views may want to not store state for their children. 13315 * 13316 * @param container The SparseArray in which to save the view's state. 13317 * 13318 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13319 * @see #saveHierarchyState(android.util.SparseArray) 13320 * @see #onSaveInstanceState() 13321 */ 13322 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 13323 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 13324 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 13325 Parcelable state = onSaveInstanceState(); 13326 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 13327 throw new IllegalStateException( 13328 "Derived class did not call super.onSaveInstanceState()"); 13329 } 13330 if (state != null) { 13331 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 13332 // + ": " + state); 13333 container.put(mID, state); 13334 } 13335 } 13336 } 13337 13338 /** 13339 * Hook allowing a view to generate a representation of its internal state 13340 * that can later be used to create a new instance with that same state. 13341 * This state should only contain information that is not persistent or can 13342 * not be reconstructed later. For example, you will never store your 13343 * current position on screen because that will be computed again when a 13344 * new instance of the view is placed in its view hierarchy. 13345 * <p> 13346 * Some examples of things you may store here: the current cursor position 13347 * in a text view (but usually not the text itself since that is stored in a 13348 * content provider or other persistent storage), the currently selected 13349 * item in a list view. 13350 * 13351 * @return Returns a Parcelable object containing the view's current dynamic 13352 * state, or null if there is nothing interesting to save. The 13353 * default implementation returns null. 13354 * @see #onRestoreInstanceState(android.os.Parcelable) 13355 * @see #saveHierarchyState(android.util.SparseArray) 13356 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13357 * @see #setSaveEnabled(boolean) 13358 */ 13359 protected Parcelable onSaveInstanceState() { 13360 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 13361 return BaseSavedState.EMPTY_STATE; 13362 } 13363 13364 /** 13365 * Restore this view hierarchy's frozen state from the given container. 13366 * 13367 * @param container The SparseArray which holds previously frozen states. 13368 * 13369 * @see #saveHierarchyState(android.util.SparseArray) 13370 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13371 * @see #onRestoreInstanceState(android.os.Parcelable) 13372 */ 13373 public void restoreHierarchyState(SparseArray<Parcelable> container) { 13374 dispatchRestoreInstanceState(container); 13375 } 13376 13377 /** 13378 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 13379 * state for this view and its children. May be overridden to modify how restoring 13380 * happens to a view's children; for example, some views may want to not store state 13381 * for their children. 13382 * 13383 * @param container The SparseArray which holds previously saved state. 13384 * 13385 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13386 * @see #restoreHierarchyState(android.util.SparseArray) 13387 * @see #onRestoreInstanceState(android.os.Parcelable) 13388 */ 13389 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 13390 if (mID != NO_ID) { 13391 Parcelable state = container.get(mID); 13392 if (state != null) { 13393 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 13394 // + ": " + state); 13395 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 13396 onRestoreInstanceState(state); 13397 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 13398 throw new IllegalStateException( 13399 "Derived class did not call super.onRestoreInstanceState()"); 13400 } 13401 } 13402 } 13403 } 13404 13405 /** 13406 * Hook allowing a view to re-apply a representation of its internal state that had previously 13407 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 13408 * null state. 13409 * 13410 * @param state The frozen state that had previously been returned by 13411 * {@link #onSaveInstanceState}. 13412 * 13413 * @see #onSaveInstanceState() 13414 * @see #restoreHierarchyState(android.util.SparseArray) 13415 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13416 */ 13417 protected void onRestoreInstanceState(Parcelable state) { 13418 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 13419 if (state != BaseSavedState.EMPTY_STATE && state != null) { 13420 throw new IllegalArgumentException("Wrong state class, expecting View State but " 13421 + "received " + state.getClass().toString() + " instead. This usually happens " 13422 + "when two views of different type have the same id in the same hierarchy. " 13423 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 13424 + "other views do not use the same id."); 13425 } 13426 } 13427 13428 /** 13429 * <p>Return the time at which the drawing of the view hierarchy started.</p> 13430 * 13431 * @return the drawing start time in milliseconds 13432 */ 13433 public long getDrawingTime() { 13434 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 13435 } 13436 13437 /** 13438 * <p>Enables or disables the duplication of the parent's state into this view. When 13439 * duplication is enabled, this view gets its drawable state from its parent rather 13440 * than from its own internal properties.</p> 13441 * 13442 * <p>Note: in the current implementation, setting this property to true after the 13443 * view was added to a ViewGroup might have no effect at all. This property should 13444 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 13445 * 13446 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 13447 * property is enabled, an exception will be thrown.</p> 13448 * 13449 * <p>Note: if the child view uses and updates additionnal states which are unknown to the 13450 * parent, these states should not be affected by this method.</p> 13451 * 13452 * @param enabled True to enable duplication of the parent's drawable state, false 13453 * to disable it. 13454 * 13455 * @see #getDrawableState() 13456 * @see #isDuplicateParentStateEnabled() 13457 */ 13458 public void setDuplicateParentStateEnabled(boolean enabled) { 13459 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 13460 } 13461 13462 /** 13463 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 13464 * 13465 * @return True if this view's drawable state is duplicated from the parent, 13466 * false otherwise 13467 * 13468 * @see #getDrawableState() 13469 * @see #setDuplicateParentStateEnabled(boolean) 13470 */ 13471 public boolean isDuplicateParentStateEnabled() { 13472 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 13473 } 13474 13475 /** 13476 * <p>Specifies the type of layer backing this view. The layer can be 13477 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13478 * {@link #LAYER_TYPE_HARDWARE}.</p> 13479 * 13480 * <p>A layer is associated with an optional {@link android.graphics.Paint} 13481 * instance that controls how the layer is composed on screen. The following 13482 * properties of the paint are taken into account when composing the layer:</p> 13483 * <ul> 13484 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 13485 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 13486 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 13487 * </ul> 13488 * 13489 * <p>If this view has an alpha value set to < 1.0 by calling 13490 * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded 13491 * by this view's alpha value.</p> 13492 * 13493 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE}, 13494 * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE} 13495 * for more information on when and how to use layers.</p> 13496 * 13497 * @param layerType The type of layer to use with this view, must be one of 13498 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13499 * {@link #LAYER_TYPE_HARDWARE} 13500 * @param paint The paint used to compose the layer. This argument is optional 13501 * and can be null. It is ignored when the layer type is 13502 * {@link #LAYER_TYPE_NONE} 13503 * 13504 * @see #getLayerType() 13505 * @see #LAYER_TYPE_NONE 13506 * @see #LAYER_TYPE_SOFTWARE 13507 * @see #LAYER_TYPE_HARDWARE 13508 * @see #setAlpha(float) 13509 * 13510 * @attr ref android.R.styleable#View_layerType 13511 */ 13512 public void setLayerType(int layerType, Paint paint) { 13513 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 13514 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 13515 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 13516 } 13517 13518 if (layerType == mLayerType) { 13519 setLayerPaint(paint); 13520 return; 13521 } 13522 13523 // Destroy any previous software drawing cache if needed 13524 switch (mLayerType) { 13525 case LAYER_TYPE_HARDWARE: 13526 destroyLayer(false); 13527 // fall through - non-accelerated views may use software layer mechanism instead 13528 case LAYER_TYPE_SOFTWARE: 13529 destroyDrawingCache(); 13530 break; 13531 default: 13532 break; 13533 } 13534 13535 mLayerType = layerType; 13536 final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE; 13537 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 13538 mLocalDirtyRect = layerDisabled ? null : new Rect(); 13539 13540 invalidateParentCaches(); 13541 invalidate(true); 13542 } 13543 13544 /** 13545 * Updates the {@link Paint} object used with the current layer (used only if the current 13546 * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint 13547 * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time 13548 * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to 13549 * ensure that the view gets redrawn immediately. 13550 * 13551 * <p>A layer is associated with an optional {@link android.graphics.Paint} 13552 * instance that controls how the layer is composed on screen. The following 13553 * properties of the paint are taken into account when composing the layer:</p> 13554 * <ul> 13555 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 13556 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 13557 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 13558 * </ul> 13559 * 13560 * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the 13561 * alpha value of the layer's paint is superceded by this view's alpha value.</p> 13562 * 13563 * @param paint The paint used to compose the layer. This argument is optional 13564 * and can be null. It is ignored when the layer type is 13565 * {@link #LAYER_TYPE_NONE} 13566 * 13567 * @see #setLayerType(int, android.graphics.Paint) 13568 */ 13569 public void setLayerPaint(Paint paint) { 13570 int layerType = getLayerType(); 13571 if (layerType != LAYER_TYPE_NONE) { 13572 mLayerPaint = paint == null ? new Paint() : paint; 13573 if (layerType == LAYER_TYPE_HARDWARE) { 13574 HardwareLayer layer = getHardwareLayer(); 13575 if (layer != null) { 13576 layer.setLayerPaint(mLayerPaint); 13577 } 13578 invalidateViewProperty(false, false); 13579 } else { 13580 invalidate(); 13581 } 13582 } 13583 } 13584 13585 /** 13586 * Indicates whether this view has a static layer. A view with layer type 13587 * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are 13588 * dynamic. 13589 */ 13590 boolean hasStaticLayer() { 13591 return true; 13592 } 13593 13594 /** 13595 * Indicates what type of layer is currently associated with this view. By default 13596 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 13597 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 13598 * for more information on the different types of layers. 13599 * 13600 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13601 * {@link #LAYER_TYPE_HARDWARE} 13602 * 13603 * @see #setLayerType(int, android.graphics.Paint) 13604 * @see #buildLayer() 13605 * @see #LAYER_TYPE_NONE 13606 * @see #LAYER_TYPE_SOFTWARE 13607 * @see #LAYER_TYPE_HARDWARE 13608 */ 13609 public int getLayerType() { 13610 return mLayerType; 13611 } 13612 13613 /** 13614 * Forces this view's layer to be created and this view to be rendered 13615 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 13616 * invoking this method will have no effect. 13617 * 13618 * This method can for instance be used to render a view into its layer before 13619 * starting an animation. If this view is complex, rendering into the layer 13620 * before starting the animation will avoid skipping frames. 13621 * 13622 * @throws IllegalStateException If this view is not attached to a window 13623 * 13624 * @see #setLayerType(int, android.graphics.Paint) 13625 */ 13626 public void buildLayer() { 13627 if (mLayerType == LAYER_TYPE_NONE) return; 13628 13629 final AttachInfo attachInfo = mAttachInfo; 13630 if (attachInfo == null) { 13631 throw new IllegalStateException("This view must be attached to a window first"); 13632 } 13633 13634 switch (mLayerType) { 13635 case LAYER_TYPE_HARDWARE: 13636 getHardwareLayer(); 13637 // TODO: We need a better way to handle this case 13638 // If views have registered pre-draw listeners they need 13639 // to be notified before we build the layer. Those listeners 13640 // may however rely on other events to happen first so we 13641 // cannot just invoke them here until they don't cancel the 13642 // current frame 13643 if (!attachInfo.mTreeObserver.hasOnPreDrawListeners()) { 13644 attachInfo.mViewRootImpl.dispatchFlushHardwareLayerUpdates(); 13645 } 13646 break; 13647 case LAYER_TYPE_SOFTWARE: 13648 buildDrawingCache(true); 13649 break; 13650 } 13651 } 13652 13653 /** 13654 * <p>Returns a hardware layer that can be used to draw this view again 13655 * without executing its draw method.</p> 13656 * 13657 * @return A HardwareLayer ready to render, or null if an error occurred. 13658 */ 13659 HardwareLayer getHardwareLayer() { 13660 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null || 13661 !mAttachInfo.mHardwareRenderer.isEnabled()) { 13662 return null; 13663 } 13664 13665 final int width = mRight - mLeft; 13666 final int height = mBottom - mTop; 13667 13668 if (width == 0 || height == 0) { 13669 return null; 13670 } 13671 13672 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) { 13673 if (mHardwareLayer == null) { 13674 mHardwareLayer = mAttachInfo.mHardwareRenderer.createDisplayListLayer( 13675 width, height); 13676 mLocalDirtyRect.set(0, 0, width, height); 13677 } else if (mHardwareLayer.isValid()) { 13678 // This should not be necessary but applications that change 13679 // the parameters of their background drawable without calling 13680 // this.setBackground(Drawable) can leave the view in a bad state 13681 // (for instance isOpaque() returns true, but the background is 13682 // not opaque.) 13683 computeOpaqueFlags(); 13684 13685 if (mHardwareLayer.prepare(width, height, isOpaque())) { 13686 mLocalDirtyRect.set(0, 0, width, height); 13687 } 13688 } 13689 13690 // The layer is not valid if the underlying GPU resources cannot be allocated 13691 mHardwareLayer.flushChanges(); 13692 if (!mHardwareLayer.isValid()) { 13693 return null; 13694 } 13695 13696 mHardwareLayer.setLayerPaint(mLayerPaint); 13697 RenderNode displayList = mHardwareLayer.startRecording(); 13698 updateDisplayListIfDirty(displayList, true); 13699 mHardwareLayer.endRecording(mLocalDirtyRect); 13700 mLocalDirtyRect.setEmpty(); 13701 } 13702 13703 return mHardwareLayer; 13704 } 13705 13706 /** 13707 * Destroys this View's hardware layer if possible. 13708 * 13709 * @return True if the layer was destroyed, false otherwise. 13710 * 13711 * @see #setLayerType(int, android.graphics.Paint) 13712 * @see #LAYER_TYPE_HARDWARE 13713 */ 13714 boolean destroyLayer(boolean valid) { 13715 if (mHardwareLayer != null) { 13716 mHardwareLayer.destroy(); 13717 mHardwareLayer = null; 13718 13719 invalidate(true); 13720 invalidateParentCaches(); 13721 return true; 13722 } 13723 return false; 13724 } 13725 13726 /** 13727 * Destroys all hardware rendering resources. This method is invoked 13728 * when the system needs to reclaim resources. Upon execution of this 13729 * method, you should free any OpenGL resources created by the view. 13730 * 13731 * Note: you <strong>must</strong> call 13732 * <code>super.destroyHardwareResources()</code> when overriding 13733 * this method. 13734 * 13735 * @hide 13736 */ 13737 protected void destroyHardwareResources() { 13738 resetDisplayList(); 13739 destroyLayer(true); 13740 } 13741 13742 /** 13743 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 13744 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 13745 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 13746 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 13747 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 13748 * null.</p> 13749 * 13750 * <p>Enabling the drawing cache is similar to 13751 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 13752 * acceleration is turned off. When hardware acceleration is turned on, enabling the 13753 * drawing cache has no effect on rendering because the system uses a different mechanism 13754 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 13755 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 13756 * for information on how to enable software and hardware layers.</p> 13757 * 13758 * <p>This API can be used to manually generate 13759 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 13760 * {@link #getDrawingCache()}.</p> 13761 * 13762 * @param enabled true to enable the drawing cache, false otherwise 13763 * 13764 * @see #isDrawingCacheEnabled() 13765 * @see #getDrawingCache() 13766 * @see #buildDrawingCache() 13767 * @see #setLayerType(int, android.graphics.Paint) 13768 */ 13769 public void setDrawingCacheEnabled(boolean enabled) { 13770 mCachingFailed = false; 13771 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 13772 } 13773 13774 /** 13775 * <p>Indicates whether the drawing cache is enabled for this view.</p> 13776 * 13777 * @return true if the drawing cache is enabled 13778 * 13779 * @see #setDrawingCacheEnabled(boolean) 13780 * @see #getDrawingCache() 13781 */ 13782 @ViewDebug.ExportedProperty(category = "drawing") 13783 public boolean isDrawingCacheEnabled() { 13784 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 13785 } 13786 13787 /** 13788 * Debugging utility which recursively outputs the dirty state of a view and its 13789 * descendants. 13790 * 13791 * @hide 13792 */ 13793 @SuppressWarnings({"UnusedDeclaration"}) 13794 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 13795 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) + 13796 ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" + 13797 (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) + 13798 ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")"); 13799 if (clear) { 13800 mPrivateFlags &= clearMask; 13801 } 13802 if (this instanceof ViewGroup) { 13803 ViewGroup parent = (ViewGroup) this; 13804 final int count = parent.getChildCount(); 13805 for (int i = 0; i < count; i++) { 13806 final View child = parent.getChildAt(i); 13807 child.outputDirtyFlags(indent + " ", clear, clearMask); 13808 } 13809 } 13810 } 13811 13812 /** 13813 * This method is used by ViewGroup to cause its children to restore or recreate their 13814 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 13815 * to recreate its own display list, which would happen if it went through the normal 13816 * draw/dispatchDraw mechanisms. 13817 * 13818 * @hide 13819 */ 13820 protected void dispatchGetDisplayList() {} 13821 13822 /** 13823 * A view that is not attached or hardware accelerated cannot create a display list. 13824 * This method checks these conditions and returns the appropriate result. 13825 * 13826 * @return true if view has the ability to create a display list, false otherwise. 13827 * 13828 * @hide 13829 */ 13830 public boolean canHaveDisplayList() { 13831 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 13832 } 13833 13834 /** 13835 * Returns a DisplayList. If the incoming displayList is null, one will be created. 13836 * Otherwise, the same display list will be returned (after having been rendered into 13837 * along the way, depending on the invalidation state of the view). 13838 * 13839 * @param renderNode The previous version of this displayList, could be null. 13840 * @param isLayer Whether the requester of the display list is a layer. If so, 13841 * the view will avoid creating a layer inside the resulting display list. 13842 * @return A new or reused DisplayList object. 13843 */ 13844 private void updateDisplayListIfDirty(@NonNull RenderNode renderNode, boolean isLayer) { 13845 final HardwareRenderer renderer = getHardwareRenderer(); 13846 if (renderNode == null) { 13847 throw new IllegalArgumentException("RenderNode must not be null"); 13848 } 13849 if (renderer == null || !canHaveDisplayList()) { 13850 // can't populate RenderNode, don't try 13851 return; 13852 } 13853 13854 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 13855 || !renderNode.isValid() 13856 || (!isLayer && mRecreateDisplayList)) { 13857 // Don't need to recreate the display list, just need to tell our 13858 // children to restore/recreate theirs 13859 if (renderNode.isValid() 13860 && !isLayer 13861 && !mRecreateDisplayList) { 13862 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13863 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13864 dispatchGetDisplayList(); 13865 13866 return; // no work needed 13867 } 13868 13869 if (!isLayer) { 13870 // If we got here, we're recreating it. Mark it as such to ensure that 13871 // we copy in child display lists into ours in drawChild() 13872 mRecreateDisplayList = true; 13873 } 13874 13875 boolean caching = false; 13876 int width = mRight - mLeft; 13877 int height = mBottom - mTop; 13878 int layerType = getLayerType(); 13879 13880 final HardwareCanvas canvas = renderNode.start(width, height); 13881 13882 try { 13883 if (!isLayer && layerType != LAYER_TYPE_NONE) { 13884 if (layerType == LAYER_TYPE_HARDWARE) { 13885 final HardwareLayer layer = getHardwareLayer(); 13886 if (layer != null && layer.isValid()) { 13887 canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint); 13888 } else { 13889 canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint, 13890 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | 13891 Canvas.CLIP_TO_LAYER_SAVE_FLAG); 13892 } 13893 caching = true; 13894 } else { 13895 buildDrawingCache(true); 13896 Bitmap cache = getDrawingCache(true); 13897 if (cache != null) { 13898 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 13899 caching = true; 13900 } 13901 } 13902 } else { 13903 13904 computeScroll(); 13905 13906 canvas.translate(-mScrollX, -mScrollY); 13907 if (!isLayer) { 13908 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13909 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13910 } 13911 13912 // Fast path for layouts with no backgrounds 13913 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 13914 dispatchDraw(canvas); 13915 if (mOverlay != null && !mOverlay.isEmpty()) { 13916 mOverlay.getOverlayView().draw(canvas); 13917 } 13918 } else { 13919 draw(canvas); 13920 } 13921 } 13922 } finally { 13923 renderNode.end(renderer, canvas); 13924 renderNode.setCaching(caching); 13925 if (isLayer) { 13926 renderNode.setLeftTopRightBottom(0, 0, width, height); 13927 } else { 13928 setDisplayListProperties(renderNode); 13929 } 13930 13931 if (renderer != getHardwareRenderer()) { 13932 Log.w(VIEW_LOG_TAG, "View was detached during a draw() call!"); 13933 // TODO: Should this be elevated to a crash? 13934 // For now have it behaves the same as it previously did, it 13935 // will result in the DisplayListData being destroyed later 13936 // than it could be but oh well... 13937 } 13938 } 13939 } else if (!isLayer) { 13940 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13941 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13942 } 13943 } 13944 13945 /** 13946 * Returns a RenderNode with View draw content recorded, which can be 13947 * used to draw this view again without executing its draw method. 13948 * 13949 * @return A RenderNode ready to replay, or null if caching is not enabled. 13950 * 13951 * @hide 13952 */ 13953 public RenderNode getDisplayList() { 13954 ensureRenderNode(); 13955 updateDisplayListIfDirty(mRenderNode, false); 13956 return mRenderNode; 13957 } 13958 13959 private void resetDisplayList() { 13960 if (mRenderNode != null && mRenderNode.isValid()) { 13961 mRenderNode.destroyDisplayListData(); 13962 } 13963 13964 if (mBackgroundDisplayList != null && mBackgroundDisplayList.isValid()) { 13965 mBackgroundDisplayList.destroyDisplayListData(); 13966 } 13967 } 13968 13969 /** 13970 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 13971 * 13972 * @return A non-scaled bitmap representing this view or null if cache is disabled. 13973 * 13974 * @see #getDrawingCache(boolean) 13975 */ 13976 public Bitmap getDrawingCache() { 13977 return getDrawingCache(false); 13978 } 13979 13980 /** 13981 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 13982 * is null when caching is disabled. If caching is enabled and the cache is not ready, 13983 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 13984 * draw from the cache when the cache is enabled. To benefit from the cache, you must 13985 * request the drawing cache by calling this method and draw it on screen if the 13986 * returned bitmap is not null.</p> 13987 * 13988 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 13989 * this method will create a bitmap of the same size as this view. Because this bitmap 13990 * will be drawn scaled by the parent ViewGroup, the result on screen might show 13991 * scaling artifacts. To avoid such artifacts, you should call this method by setting 13992 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 13993 * size than the view. This implies that your application must be able to handle this 13994 * size.</p> 13995 * 13996 * @param autoScale Indicates whether the generated bitmap should be scaled based on 13997 * the current density of the screen when the application is in compatibility 13998 * mode. 13999 * 14000 * @return A bitmap representing this view or null if cache is disabled. 14001 * 14002 * @see #setDrawingCacheEnabled(boolean) 14003 * @see #isDrawingCacheEnabled() 14004 * @see #buildDrawingCache(boolean) 14005 * @see #destroyDrawingCache() 14006 */ 14007 public Bitmap getDrawingCache(boolean autoScale) { 14008 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 14009 return null; 14010 } 14011 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 14012 buildDrawingCache(autoScale); 14013 } 14014 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 14015 } 14016 14017 /** 14018 * <p>Frees the resources used by the drawing cache. If you call 14019 * {@link #buildDrawingCache()} manually without calling 14020 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 14021 * should cleanup the cache with this method afterwards.</p> 14022 * 14023 * @see #setDrawingCacheEnabled(boolean) 14024 * @see #buildDrawingCache() 14025 * @see #getDrawingCache() 14026 */ 14027 public void destroyDrawingCache() { 14028 if (mDrawingCache != null) { 14029 mDrawingCache.recycle(); 14030 mDrawingCache = null; 14031 } 14032 if (mUnscaledDrawingCache != null) { 14033 mUnscaledDrawingCache.recycle(); 14034 mUnscaledDrawingCache = null; 14035 } 14036 } 14037 14038 /** 14039 * Setting a solid background color for the drawing cache's bitmaps will improve 14040 * performance and memory usage. Note, though that this should only be used if this 14041 * view will always be drawn on top of a solid color. 14042 * 14043 * @param color The background color to use for the drawing cache's bitmap 14044 * 14045 * @see #setDrawingCacheEnabled(boolean) 14046 * @see #buildDrawingCache() 14047 * @see #getDrawingCache() 14048 */ 14049 public void setDrawingCacheBackgroundColor(int color) { 14050 if (color != mDrawingCacheBackgroundColor) { 14051 mDrawingCacheBackgroundColor = color; 14052 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 14053 } 14054 } 14055 14056 /** 14057 * @see #setDrawingCacheBackgroundColor(int) 14058 * 14059 * @return The background color to used for the drawing cache's bitmap 14060 */ 14061 public int getDrawingCacheBackgroundColor() { 14062 return mDrawingCacheBackgroundColor; 14063 } 14064 14065 /** 14066 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 14067 * 14068 * @see #buildDrawingCache(boolean) 14069 */ 14070 public void buildDrawingCache() { 14071 buildDrawingCache(false); 14072 } 14073 14074 /** 14075 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 14076 * 14077 * <p>If you call {@link #buildDrawingCache()} manually without calling 14078 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 14079 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 14080 * 14081 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 14082 * this method will create a bitmap of the same size as this view. Because this bitmap 14083 * will be drawn scaled by the parent ViewGroup, the result on screen might show 14084 * scaling artifacts. To avoid such artifacts, you should call this method by setting 14085 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 14086 * size than the view. This implies that your application must be able to handle this 14087 * size.</p> 14088 * 14089 * <p>You should avoid calling this method when hardware acceleration is enabled. If 14090 * you do not need the drawing cache bitmap, calling this method will increase memory 14091 * usage and cause the view to be rendered in software once, thus negatively impacting 14092 * performance.</p> 14093 * 14094 * @see #getDrawingCache() 14095 * @see #destroyDrawingCache() 14096 */ 14097 public void buildDrawingCache(boolean autoScale) { 14098 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ? 14099 mDrawingCache == null : mUnscaledDrawingCache == null)) { 14100 mCachingFailed = false; 14101 14102 int width = mRight - mLeft; 14103 int height = mBottom - mTop; 14104 14105 final AttachInfo attachInfo = mAttachInfo; 14106 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 14107 14108 if (autoScale && scalingRequired) { 14109 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 14110 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 14111 } 14112 14113 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 14114 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 14115 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 14116 14117 final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4); 14118 final long drawingCacheSize = 14119 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize(); 14120 if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) { 14121 if (width > 0 && height > 0) { 14122 Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs " 14123 + projectedBitmapSize + " bytes, only " 14124 + drawingCacheSize + " available"); 14125 } 14126 destroyDrawingCache(); 14127 mCachingFailed = true; 14128 return; 14129 } 14130 14131 boolean clear = true; 14132 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 14133 14134 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 14135 Bitmap.Config quality; 14136 if (!opaque) { 14137 // Never pick ARGB_4444 because it looks awful 14138 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 14139 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 14140 case DRAWING_CACHE_QUALITY_AUTO: 14141 case DRAWING_CACHE_QUALITY_LOW: 14142 case DRAWING_CACHE_QUALITY_HIGH: 14143 default: 14144 quality = Bitmap.Config.ARGB_8888; 14145 break; 14146 } 14147 } else { 14148 // Optimization for translucent windows 14149 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 14150 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 14151 } 14152 14153 // Try to cleanup memory 14154 if (bitmap != null) bitmap.recycle(); 14155 14156 try { 14157 bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 14158 width, height, quality); 14159 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 14160 if (autoScale) { 14161 mDrawingCache = bitmap; 14162 } else { 14163 mUnscaledDrawingCache = bitmap; 14164 } 14165 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 14166 } catch (OutOfMemoryError e) { 14167 // If there is not enough memory to create the bitmap cache, just 14168 // ignore the issue as bitmap caches are not required to draw the 14169 // view hierarchy 14170 if (autoScale) { 14171 mDrawingCache = null; 14172 } else { 14173 mUnscaledDrawingCache = null; 14174 } 14175 mCachingFailed = true; 14176 return; 14177 } 14178 14179 clear = drawingCacheBackgroundColor != 0; 14180 } 14181 14182 Canvas canvas; 14183 if (attachInfo != null) { 14184 canvas = attachInfo.mCanvas; 14185 if (canvas == null) { 14186 canvas = new Canvas(); 14187 } 14188 canvas.setBitmap(bitmap); 14189 // Temporarily clobber the cached Canvas in case one of our children 14190 // is also using a drawing cache. Without this, the children would 14191 // steal the canvas by attaching their own bitmap to it and bad, bad 14192 // thing would happen (invisible views, corrupted drawings, etc.) 14193 attachInfo.mCanvas = null; 14194 } else { 14195 // This case should hopefully never or seldom happen 14196 canvas = new Canvas(bitmap); 14197 } 14198 14199 if (clear) { 14200 bitmap.eraseColor(drawingCacheBackgroundColor); 14201 } 14202 14203 computeScroll(); 14204 final int restoreCount = canvas.save(); 14205 14206 if (autoScale && scalingRequired) { 14207 final float scale = attachInfo.mApplicationScale; 14208 canvas.scale(scale, scale); 14209 } 14210 14211 canvas.translate(-mScrollX, -mScrollY); 14212 14213 mPrivateFlags |= PFLAG_DRAWN; 14214 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 14215 mLayerType != LAYER_TYPE_NONE) { 14216 mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID; 14217 } 14218 14219 // Fast path for layouts with no backgrounds 14220 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14221 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14222 dispatchDraw(canvas); 14223 if (mOverlay != null && !mOverlay.isEmpty()) { 14224 mOverlay.getOverlayView().draw(canvas); 14225 } 14226 } else { 14227 draw(canvas); 14228 } 14229 14230 canvas.restoreToCount(restoreCount); 14231 canvas.setBitmap(null); 14232 14233 if (attachInfo != null) { 14234 // Restore the cached Canvas for our siblings 14235 attachInfo.mCanvas = canvas; 14236 } 14237 } 14238 } 14239 14240 /** 14241 * Create a snapshot of the view into a bitmap. We should probably make 14242 * some form of this public, but should think about the API. 14243 */ 14244 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 14245 int width = mRight - mLeft; 14246 int height = mBottom - mTop; 14247 14248 final AttachInfo attachInfo = mAttachInfo; 14249 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 14250 width = (int) ((width * scale) + 0.5f); 14251 height = (int) ((height * scale) + 0.5f); 14252 14253 Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 14254 width > 0 ? width : 1, height > 0 ? height : 1, quality); 14255 if (bitmap == null) { 14256 throw new OutOfMemoryError(); 14257 } 14258 14259 Resources resources = getResources(); 14260 if (resources != null) { 14261 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 14262 } 14263 14264 Canvas canvas; 14265 if (attachInfo != null) { 14266 canvas = attachInfo.mCanvas; 14267 if (canvas == null) { 14268 canvas = new Canvas(); 14269 } 14270 canvas.setBitmap(bitmap); 14271 // Temporarily clobber the cached Canvas in case one of our children 14272 // is also using a drawing cache. Without this, the children would 14273 // steal the canvas by attaching their own bitmap to it and bad, bad 14274 // things would happen (invisible views, corrupted drawings, etc.) 14275 attachInfo.mCanvas = null; 14276 } else { 14277 // This case should hopefully never or seldom happen 14278 canvas = new Canvas(bitmap); 14279 } 14280 14281 if ((backgroundColor & 0xff000000) != 0) { 14282 bitmap.eraseColor(backgroundColor); 14283 } 14284 14285 computeScroll(); 14286 final int restoreCount = canvas.save(); 14287 canvas.scale(scale, scale); 14288 canvas.translate(-mScrollX, -mScrollY); 14289 14290 // Temporarily remove the dirty mask 14291 int flags = mPrivateFlags; 14292 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14293 14294 // Fast path for layouts with no backgrounds 14295 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14296 dispatchDraw(canvas); 14297 if (mOverlay != null && !mOverlay.isEmpty()) { 14298 mOverlay.getOverlayView().draw(canvas); 14299 } 14300 } else { 14301 draw(canvas); 14302 } 14303 14304 mPrivateFlags = flags; 14305 14306 canvas.restoreToCount(restoreCount); 14307 canvas.setBitmap(null); 14308 14309 if (attachInfo != null) { 14310 // Restore the cached Canvas for our siblings 14311 attachInfo.mCanvas = canvas; 14312 } 14313 14314 return bitmap; 14315 } 14316 14317 /** 14318 * Indicates whether this View is currently in edit mode. A View is usually 14319 * in edit mode when displayed within a developer tool. For instance, if 14320 * this View is being drawn by a visual user interface builder, this method 14321 * should return true. 14322 * 14323 * Subclasses should check the return value of this method to provide 14324 * different behaviors if their normal behavior might interfere with the 14325 * host environment. For instance: the class spawns a thread in its 14326 * constructor, the drawing code relies on device-specific features, etc. 14327 * 14328 * This method is usually checked in the drawing code of custom widgets. 14329 * 14330 * @return True if this View is in edit mode, false otherwise. 14331 */ 14332 public boolean isInEditMode() { 14333 return false; 14334 } 14335 14336 /** 14337 * If the View draws content inside its padding and enables fading edges, 14338 * it needs to support padding offsets. Padding offsets are added to the 14339 * fading edges to extend the length of the fade so that it covers pixels 14340 * drawn inside the padding. 14341 * 14342 * Subclasses of this class should override this method if they need 14343 * to draw content inside the padding. 14344 * 14345 * @return True if padding offset must be applied, false otherwise. 14346 * 14347 * @see #getLeftPaddingOffset() 14348 * @see #getRightPaddingOffset() 14349 * @see #getTopPaddingOffset() 14350 * @see #getBottomPaddingOffset() 14351 * 14352 * @since CURRENT 14353 */ 14354 protected boolean isPaddingOffsetRequired() { 14355 return false; 14356 } 14357 14358 /** 14359 * Amount by which to extend the left fading region. Called only when 14360 * {@link #isPaddingOffsetRequired()} returns true. 14361 * 14362 * @return The left padding offset in pixels. 14363 * 14364 * @see #isPaddingOffsetRequired() 14365 * 14366 * @since CURRENT 14367 */ 14368 protected int getLeftPaddingOffset() { 14369 return 0; 14370 } 14371 14372 /** 14373 * Amount by which to extend the right fading region. Called only when 14374 * {@link #isPaddingOffsetRequired()} returns true. 14375 * 14376 * @return The right padding offset in pixels. 14377 * 14378 * @see #isPaddingOffsetRequired() 14379 * 14380 * @since CURRENT 14381 */ 14382 protected int getRightPaddingOffset() { 14383 return 0; 14384 } 14385 14386 /** 14387 * Amount by which to extend the top fading region. Called only when 14388 * {@link #isPaddingOffsetRequired()} returns true. 14389 * 14390 * @return The top padding offset in pixels. 14391 * 14392 * @see #isPaddingOffsetRequired() 14393 * 14394 * @since CURRENT 14395 */ 14396 protected int getTopPaddingOffset() { 14397 return 0; 14398 } 14399 14400 /** 14401 * Amount by which to extend the bottom fading region. Called only when 14402 * {@link #isPaddingOffsetRequired()} returns true. 14403 * 14404 * @return The bottom padding offset in pixels. 14405 * 14406 * @see #isPaddingOffsetRequired() 14407 * 14408 * @since CURRENT 14409 */ 14410 protected int getBottomPaddingOffset() { 14411 return 0; 14412 } 14413 14414 /** 14415 * @hide 14416 * @param offsetRequired 14417 */ 14418 protected int getFadeTop(boolean offsetRequired) { 14419 int top = mPaddingTop; 14420 if (offsetRequired) top += getTopPaddingOffset(); 14421 return top; 14422 } 14423 14424 /** 14425 * @hide 14426 * @param offsetRequired 14427 */ 14428 protected int getFadeHeight(boolean offsetRequired) { 14429 int padding = mPaddingTop; 14430 if (offsetRequired) padding += getTopPaddingOffset(); 14431 return mBottom - mTop - mPaddingBottom - padding; 14432 } 14433 14434 /** 14435 * <p>Indicates whether this view is attached to a hardware accelerated 14436 * window or not.</p> 14437 * 14438 * <p>Even if this method returns true, it does not mean that every call 14439 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 14440 * accelerated {@link android.graphics.Canvas}. For instance, if this view 14441 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 14442 * window is hardware accelerated, 14443 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 14444 * return false, and this method will return true.</p> 14445 * 14446 * @return True if the view is attached to a window and the window is 14447 * hardware accelerated; false in any other case. 14448 */ 14449 public boolean isHardwareAccelerated() { 14450 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 14451 } 14452 14453 /** 14454 * Sets a rectangular area on this view to which the view will be clipped 14455 * when it is drawn. Setting the value to null will remove the clip bounds 14456 * and the view will draw normally, using its full bounds. 14457 * 14458 * @param clipBounds The rectangular area, in the local coordinates of 14459 * this view, to which future drawing operations will be clipped. 14460 */ 14461 public void setClipBounds(Rect clipBounds) { 14462 if (clipBounds != null) { 14463 if (clipBounds.equals(mClipBounds)) { 14464 return; 14465 } 14466 if (mClipBounds == null) { 14467 invalidate(); 14468 mClipBounds = new Rect(clipBounds); 14469 } else { 14470 invalidate(Math.min(mClipBounds.left, clipBounds.left), 14471 Math.min(mClipBounds.top, clipBounds.top), 14472 Math.max(mClipBounds.right, clipBounds.right), 14473 Math.max(mClipBounds.bottom, clipBounds.bottom)); 14474 mClipBounds.set(clipBounds); 14475 } 14476 } else { 14477 if (mClipBounds != null) { 14478 invalidate(); 14479 mClipBounds = null; 14480 } 14481 } 14482 } 14483 14484 /** 14485 * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}. 14486 * 14487 * @return A copy of the current clip bounds if clip bounds are set, 14488 * otherwise null. 14489 */ 14490 public Rect getClipBounds() { 14491 return (mClipBounds != null) ? new Rect(mClipBounds) : null; 14492 } 14493 14494 /** 14495 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 14496 * case of an active Animation being run on the view. 14497 */ 14498 private boolean drawAnimation(ViewGroup parent, long drawingTime, 14499 Animation a, boolean scalingRequired) { 14500 Transformation invalidationTransform; 14501 final int flags = parent.mGroupFlags; 14502 final boolean initialized = a.isInitialized(); 14503 if (!initialized) { 14504 a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight()); 14505 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 14506 if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler); 14507 onAnimationStart(); 14508 } 14509 14510 final Transformation t = parent.getChildTransformation(); 14511 boolean more = a.getTransformation(drawingTime, t, 1f); 14512 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 14513 if (parent.mInvalidationTransformation == null) { 14514 parent.mInvalidationTransformation = new Transformation(); 14515 } 14516 invalidationTransform = parent.mInvalidationTransformation; 14517 a.getTransformation(drawingTime, invalidationTransform, 1f); 14518 } else { 14519 invalidationTransform = t; 14520 } 14521 14522 if (more) { 14523 if (!a.willChangeBounds()) { 14524 if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) == 14525 ViewGroup.FLAG_OPTIMIZE_INVALIDATE) { 14526 parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED; 14527 } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) { 14528 // The child need to draw an animation, potentially offscreen, so 14529 // make sure we do not cancel invalidate requests 14530 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 14531 parent.invalidate(mLeft, mTop, mRight, mBottom); 14532 } 14533 } else { 14534 if (parent.mInvalidateRegion == null) { 14535 parent.mInvalidateRegion = new RectF(); 14536 } 14537 final RectF region = parent.mInvalidateRegion; 14538 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 14539 invalidationTransform); 14540 14541 // The child need to draw an animation, potentially offscreen, so 14542 // make sure we do not cancel invalidate requests 14543 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 14544 14545 final int left = mLeft + (int) region.left; 14546 final int top = mTop + (int) region.top; 14547 parent.invalidate(left, top, left + (int) (region.width() + .5f), 14548 top + (int) (region.height() + .5f)); 14549 } 14550 } 14551 return more; 14552 } 14553 14554 /** 14555 * This method is called by getDisplayList() when a display list is created or re-rendered. 14556 * It sets or resets the current value of all properties on that display list (resetting is 14557 * necessary when a display list is being re-created, because we need to make sure that 14558 * previously-set transform values 14559 */ 14560 void setDisplayListProperties(RenderNode displayList) { 14561 if (displayList != null) { 14562 displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 14563 displayList.setHasOverlappingRendering(hasOverlappingRendering()); 14564 if (mParent instanceof ViewGroup) { 14565 displayList.setClipToBounds( 14566 (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0); 14567 } 14568 displayList.setOutline(mOutline); 14569 displayList.setClipToOutline(getClipToOutline()); 14570 float alpha = 1; 14571 if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags & 14572 ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 14573 ViewGroup parentVG = (ViewGroup) mParent; 14574 final Transformation t = parentVG.getChildTransformation(); 14575 if (parentVG.getChildStaticTransformation(this, t)) { 14576 final int transformType = t.getTransformationType(); 14577 if (transformType != Transformation.TYPE_IDENTITY) { 14578 if ((transformType & Transformation.TYPE_ALPHA) != 0) { 14579 alpha = t.getAlpha(); 14580 } 14581 if ((transformType & Transformation.TYPE_MATRIX) != 0) { 14582 displayList.setStaticMatrix(t.getMatrix()); 14583 } 14584 } 14585 } 14586 } 14587 if (mTransformationInfo != null) { 14588 alpha *= getFinalAlpha(); 14589 if (alpha < 1) { 14590 final int multipliedAlpha = (int) (255 * alpha); 14591 if (onSetAlpha(multipliedAlpha)) { 14592 alpha = 1; 14593 } 14594 } 14595 displayList.setTransformationInfo(alpha, 14596 mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY, 14597 mTransformationInfo.mTranslationZ, 14598 mTransformationInfo.mRotation, mTransformationInfo.mRotationX, 14599 mTransformationInfo.mRotationY, mTransformationInfo.mScaleX, 14600 mTransformationInfo.mScaleY); 14601 if (mTransformationInfo.mCamera == null) { 14602 mTransformationInfo.mCamera = new Camera(); 14603 mTransformationInfo.matrix3D = new Matrix(); 14604 } 14605 displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ()); 14606 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == PFLAG_PIVOT_EXPLICITLY_SET) { 14607 displayList.setPivotX(getPivotX()); 14608 displayList.setPivotY(getPivotY()); 14609 } 14610 } else if (alpha < 1) { 14611 displayList.setAlpha(alpha); 14612 } 14613 } 14614 } 14615 14616 /** 14617 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 14618 * This draw() method is an implementation detail and is not intended to be overridden or 14619 * to be called from anywhere else other than ViewGroup.drawChild(). 14620 */ 14621 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 14622 boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 14623 boolean more = false; 14624 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 14625 final int flags = parent.mGroupFlags; 14626 14627 if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) { 14628 parent.getChildTransformation().clear(); 14629 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14630 } 14631 14632 Transformation transformToApply = null; 14633 boolean concatMatrix = false; 14634 14635 boolean scalingRequired = false; 14636 boolean caching; 14637 int layerType = getLayerType(); 14638 14639 final boolean hardwareAccelerated = canvas.isHardwareAccelerated(); 14640 if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 || 14641 (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) { 14642 caching = true; 14643 // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList 14644 if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired; 14645 } else { 14646 caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated; 14647 } 14648 14649 final Animation a = getAnimation(); 14650 if (a != null) { 14651 more = drawAnimation(parent, drawingTime, a, scalingRequired); 14652 concatMatrix = a.willChangeTransformationMatrix(); 14653 if (concatMatrix) { 14654 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 14655 } 14656 transformToApply = parent.getChildTransformation(); 14657 } else { 14658 if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) == 14659 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM && mRenderNode != null) { 14660 // No longer animating: clear out old animation matrix 14661 mRenderNode.setAnimationMatrix(null); 14662 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 14663 } 14664 if (!useDisplayListProperties && 14665 (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 14666 final Transformation t = parent.getChildTransformation(); 14667 final boolean hasTransform = parent.getChildStaticTransformation(this, t); 14668 if (hasTransform) { 14669 final int transformType = t.getTransformationType(); 14670 transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null; 14671 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 14672 } 14673 } 14674 } 14675 14676 concatMatrix |= !childHasIdentityMatrix; 14677 14678 // Sets the flag as early as possible to allow draw() implementations 14679 // to call invalidate() successfully when doing animations 14680 mPrivateFlags |= PFLAG_DRAWN; 14681 14682 if (!concatMatrix && 14683 (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS | 14684 ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN && 14685 canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 14686 (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) { 14687 mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED; 14688 return more; 14689 } 14690 mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED; 14691 14692 if (hardwareAccelerated) { 14693 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 14694 // retain the flag's value temporarily in the mRecreateDisplayList flag 14695 mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED; 14696 mPrivateFlags &= ~PFLAG_INVALIDATED; 14697 } 14698 14699 RenderNode displayList = null; 14700 Bitmap cache = null; 14701 boolean hasDisplayList = false; 14702 if (caching) { 14703 if (!hardwareAccelerated) { 14704 if (layerType != LAYER_TYPE_NONE) { 14705 layerType = LAYER_TYPE_SOFTWARE; 14706 buildDrawingCache(true); 14707 } 14708 cache = getDrawingCache(true); 14709 } else { 14710 switch (layerType) { 14711 case LAYER_TYPE_SOFTWARE: 14712 if (useDisplayListProperties) { 14713 hasDisplayList = canHaveDisplayList(); 14714 } else { 14715 buildDrawingCache(true); 14716 cache = getDrawingCache(true); 14717 } 14718 break; 14719 case LAYER_TYPE_HARDWARE: 14720 if (useDisplayListProperties) { 14721 hasDisplayList = canHaveDisplayList(); 14722 } 14723 break; 14724 case LAYER_TYPE_NONE: 14725 // Delay getting the display list until animation-driven alpha values are 14726 // set up and possibly passed on to the view 14727 hasDisplayList = canHaveDisplayList(); 14728 break; 14729 } 14730 } 14731 } 14732 useDisplayListProperties &= hasDisplayList; 14733 if (useDisplayListProperties) { 14734 displayList = getDisplayList(); 14735 if (!displayList.isValid()) { 14736 // Uncommon, but possible. If a view is removed from the hierarchy during the call 14737 // to getDisplayList(), the display list will be marked invalid and we should not 14738 // try to use it again. 14739 displayList = null; 14740 hasDisplayList = false; 14741 useDisplayListProperties = false; 14742 } 14743 } 14744 14745 int sx = 0; 14746 int sy = 0; 14747 if (!hasDisplayList) { 14748 computeScroll(); 14749 sx = mScrollX; 14750 sy = mScrollY; 14751 } 14752 14753 final boolean hasNoCache = cache == null || hasDisplayList; 14754 final boolean offsetForScroll = cache == null && !hasDisplayList && 14755 layerType != LAYER_TYPE_HARDWARE; 14756 14757 int restoreTo = -1; 14758 if (!useDisplayListProperties || transformToApply != null) { 14759 restoreTo = canvas.save(); 14760 } 14761 if (offsetForScroll) { 14762 canvas.translate(mLeft - sx, mTop - sy); 14763 } else { 14764 if (!useDisplayListProperties) { 14765 canvas.translate(mLeft, mTop); 14766 } 14767 if (scalingRequired) { 14768 if (useDisplayListProperties) { 14769 // TODO: Might not need this if we put everything inside the DL 14770 restoreTo = canvas.save(); 14771 } 14772 // mAttachInfo cannot be null, otherwise scalingRequired == false 14773 final float scale = 1.0f / mAttachInfo.mApplicationScale; 14774 canvas.scale(scale, scale); 14775 } 14776 } 14777 14778 float alpha = useDisplayListProperties ? 1 : (getAlpha() * getTransitionAlpha()); 14779 if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() || 14780 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 14781 if (transformToApply != null || !childHasIdentityMatrix) { 14782 int transX = 0; 14783 int transY = 0; 14784 14785 if (offsetForScroll) { 14786 transX = -sx; 14787 transY = -sy; 14788 } 14789 14790 if (transformToApply != null) { 14791 if (concatMatrix) { 14792 if (useDisplayListProperties) { 14793 displayList.setAnimationMatrix(transformToApply.getMatrix()); 14794 } else { 14795 // Undo the scroll translation, apply the transformation matrix, 14796 // then redo the scroll translate to get the correct result. 14797 canvas.translate(-transX, -transY); 14798 canvas.concat(transformToApply.getMatrix()); 14799 canvas.translate(transX, transY); 14800 } 14801 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14802 } 14803 14804 float transformAlpha = transformToApply.getAlpha(); 14805 if (transformAlpha < 1) { 14806 alpha *= transformAlpha; 14807 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14808 } 14809 } 14810 14811 if (!childHasIdentityMatrix && !useDisplayListProperties) { 14812 canvas.translate(-transX, -transY); 14813 canvas.concat(getMatrix()); 14814 canvas.translate(transX, transY); 14815 } 14816 } 14817 14818 // Deal with alpha if it is or used to be <1 14819 if (alpha < 1 || 14820 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 14821 if (alpha < 1) { 14822 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA; 14823 } else { 14824 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA; 14825 } 14826 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14827 if (hasNoCache) { 14828 final int multipliedAlpha = (int) (255 * alpha); 14829 if (!onSetAlpha(multipliedAlpha)) { 14830 int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 14831 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 || 14832 layerType != LAYER_TYPE_NONE) { 14833 layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG; 14834 } 14835 if (useDisplayListProperties) { 14836 displayList.setAlpha(alpha * getAlpha() * getTransitionAlpha()); 14837 } else if (layerType == LAYER_TYPE_NONE) { 14838 final int scrollX = hasDisplayList ? 0 : sx; 14839 final int scrollY = hasDisplayList ? 0 : sy; 14840 canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft, 14841 scrollY + mBottom - mTop, multipliedAlpha, layerFlags); 14842 } 14843 } else { 14844 // Alpha is handled by the child directly, clobber the layer's alpha 14845 mPrivateFlags |= PFLAG_ALPHA_SET; 14846 } 14847 } 14848 } 14849 } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 14850 onSetAlpha(255); 14851 mPrivateFlags &= ~PFLAG_ALPHA_SET; 14852 } 14853 14854 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN && 14855 !useDisplayListProperties && cache == null) { 14856 if (offsetForScroll) { 14857 canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop)); 14858 } else { 14859 if (!scalingRequired || cache == null) { 14860 canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop); 14861 } else { 14862 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 14863 } 14864 } 14865 } 14866 14867 if (!useDisplayListProperties && hasDisplayList) { 14868 displayList = getDisplayList(); 14869 if (!displayList.isValid()) { 14870 // Uncommon, but possible. If a view is removed from the hierarchy during the call 14871 // to getDisplayList(), the display list will be marked invalid and we should not 14872 // try to use it again. 14873 displayList = null; 14874 hasDisplayList = false; 14875 } 14876 } 14877 14878 if (hasNoCache) { 14879 boolean layerRendered = false; 14880 if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) { 14881 final HardwareLayer layer = getHardwareLayer(); 14882 if (layer != null && layer.isValid()) { 14883 mLayerPaint.setAlpha((int) (alpha * 255)); 14884 ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint); 14885 layerRendered = true; 14886 } else { 14887 final int scrollX = hasDisplayList ? 0 : sx; 14888 final int scrollY = hasDisplayList ? 0 : sy; 14889 canvas.saveLayer(scrollX, scrollY, 14890 scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint, 14891 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG); 14892 } 14893 } 14894 14895 if (!layerRendered) { 14896 if (!hasDisplayList) { 14897 // Fast path for layouts with no backgrounds 14898 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14899 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14900 dispatchDraw(canvas); 14901 } else { 14902 draw(canvas); 14903 } 14904 } else { 14905 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14906 ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags); 14907 } 14908 } 14909 } else if (cache != null) { 14910 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14911 Paint cachePaint; 14912 14913 if (layerType == LAYER_TYPE_NONE) { 14914 cachePaint = parent.mCachePaint; 14915 if (cachePaint == null) { 14916 cachePaint = new Paint(); 14917 cachePaint.setDither(false); 14918 parent.mCachePaint = cachePaint; 14919 } 14920 if (alpha < 1) { 14921 cachePaint.setAlpha((int) (alpha * 255)); 14922 parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 14923 } else if ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) { 14924 cachePaint.setAlpha(255); 14925 parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 14926 } 14927 } else { 14928 cachePaint = mLayerPaint; 14929 cachePaint.setAlpha((int) (alpha * 255)); 14930 } 14931 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 14932 } 14933 14934 if (restoreTo >= 0) { 14935 canvas.restoreToCount(restoreTo); 14936 } 14937 14938 if (a != null && !more) { 14939 if (!hardwareAccelerated && !a.getFillAfter()) { 14940 onSetAlpha(255); 14941 } 14942 parent.finishAnimatingView(this, a); 14943 } 14944 14945 if (more && hardwareAccelerated) { 14946 if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 14947 // alpha animations should cause the child to recreate its display list 14948 invalidate(true); 14949 } 14950 } 14951 14952 mRecreateDisplayList = false; 14953 14954 return more; 14955 } 14956 14957 /** 14958 * Manually render this view (and all of its children) to the given Canvas. 14959 * The view must have already done a full layout before this function is 14960 * called. When implementing a view, implement 14961 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 14962 * If you do need to override this method, call the superclass version. 14963 * 14964 * @param canvas The Canvas to which the View is rendered. 14965 */ 14966 public void draw(Canvas canvas) { 14967 if (mClipBounds != null) { 14968 canvas.clipRect(mClipBounds); 14969 } 14970 final int privateFlags = mPrivateFlags; 14971 final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE && 14972 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 14973 mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN; 14974 14975 /* 14976 * Draw traversal performs several drawing steps which must be executed 14977 * in the appropriate order: 14978 * 14979 * 1. Draw the background 14980 * 2. If necessary, save the canvas' layers to prepare for fading 14981 * 3. Draw view's content 14982 * 4. Draw children 14983 * 5. If necessary, draw the fading edges and restore layers 14984 * 6. Draw decorations (scrollbars for instance) 14985 */ 14986 14987 // Step 1, draw the background, if needed 14988 int saveCount; 14989 14990 if (!dirtyOpaque) { 14991 drawBackground(canvas); 14992 } 14993 14994 // skip step 2 & 5 if possible (common case) 14995 final int viewFlags = mViewFlags; 14996 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 14997 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 14998 if (!verticalEdges && !horizontalEdges) { 14999 // Step 3, draw the content 15000 if (!dirtyOpaque) onDraw(canvas); 15001 15002 // Step 4, draw the children 15003 dispatchDraw(canvas); 15004 15005 // Step 6, draw decorations (scrollbars) 15006 onDrawScrollBars(canvas); 15007 15008 if (mOverlay != null && !mOverlay.isEmpty()) { 15009 mOverlay.getOverlayView().dispatchDraw(canvas); 15010 } 15011 15012 // we're done... 15013 return; 15014 } 15015 15016 /* 15017 * Here we do the full fledged routine... 15018 * (this is an uncommon case where speed matters less, 15019 * this is why we repeat some of the tests that have been 15020 * done above) 15021 */ 15022 15023 boolean drawTop = false; 15024 boolean drawBottom = false; 15025 boolean drawLeft = false; 15026 boolean drawRight = false; 15027 15028 float topFadeStrength = 0.0f; 15029 float bottomFadeStrength = 0.0f; 15030 float leftFadeStrength = 0.0f; 15031 float rightFadeStrength = 0.0f; 15032 15033 // Step 2, save the canvas' layers 15034 int paddingLeft = mPaddingLeft; 15035 15036 final boolean offsetRequired = isPaddingOffsetRequired(); 15037 if (offsetRequired) { 15038 paddingLeft += getLeftPaddingOffset(); 15039 } 15040 15041 int left = mScrollX + paddingLeft; 15042 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 15043 int top = mScrollY + getFadeTop(offsetRequired); 15044 int bottom = top + getFadeHeight(offsetRequired); 15045 15046 if (offsetRequired) { 15047 right += getRightPaddingOffset(); 15048 bottom += getBottomPaddingOffset(); 15049 } 15050 15051 final ScrollabilityCache scrollabilityCache = mScrollCache; 15052 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 15053 int length = (int) fadeHeight; 15054 15055 // clip the fade length if top and bottom fades overlap 15056 // overlapping fades produce odd-looking artifacts 15057 if (verticalEdges && (top + length > bottom - length)) { 15058 length = (bottom - top) / 2; 15059 } 15060 15061 // also clip horizontal fades if necessary 15062 if (horizontalEdges && (left + length > right - length)) { 15063 length = (right - left) / 2; 15064 } 15065 15066 if (verticalEdges) { 15067 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 15068 drawTop = topFadeStrength * fadeHeight > 1.0f; 15069 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 15070 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 15071 } 15072 15073 if (horizontalEdges) { 15074 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 15075 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 15076 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 15077 drawRight = rightFadeStrength * fadeHeight > 1.0f; 15078 } 15079 15080 saveCount = canvas.getSaveCount(); 15081 15082 int solidColor = getSolidColor(); 15083 if (solidColor == 0) { 15084 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 15085 15086 if (drawTop) { 15087 canvas.saveLayer(left, top, right, top + length, null, flags); 15088 } 15089 15090 if (drawBottom) { 15091 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 15092 } 15093 15094 if (drawLeft) { 15095 canvas.saveLayer(left, top, left + length, bottom, null, flags); 15096 } 15097 15098 if (drawRight) { 15099 canvas.saveLayer(right - length, top, right, bottom, null, flags); 15100 } 15101 } else { 15102 scrollabilityCache.setFadeColor(solidColor); 15103 } 15104 15105 // Step 3, draw the content 15106 if (!dirtyOpaque) onDraw(canvas); 15107 15108 // Step 4, draw the children 15109 dispatchDraw(canvas); 15110 15111 // Step 5, draw the fade effect and restore layers 15112 final Paint p = scrollabilityCache.paint; 15113 final Matrix matrix = scrollabilityCache.matrix; 15114 final Shader fade = scrollabilityCache.shader; 15115 15116 if (drawTop) { 15117 matrix.setScale(1, fadeHeight * topFadeStrength); 15118 matrix.postTranslate(left, top); 15119 fade.setLocalMatrix(matrix); 15120 canvas.drawRect(left, top, right, top + length, p); 15121 } 15122 15123 if (drawBottom) { 15124 matrix.setScale(1, fadeHeight * bottomFadeStrength); 15125 matrix.postRotate(180); 15126 matrix.postTranslate(left, bottom); 15127 fade.setLocalMatrix(matrix); 15128 canvas.drawRect(left, bottom - length, right, bottom, p); 15129 } 15130 15131 if (drawLeft) { 15132 matrix.setScale(1, fadeHeight * leftFadeStrength); 15133 matrix.postRotate(-90); 15134 matrix.postTranslate(left, top); 15135 fade.setLocalMatrix(matrix); 15136 canvas.drawRect(left, top, left + length, bottom, p); 15137 } 15138 15139 if (drawRight) { 15140 matrix.setScale(1, fadeHeight * rightFadeStrength); 15141 matrix.postRotate(90); 15142 matrix.postTranslate(right, top); 15143 fade.setLocalMatrix(matrix); 15144 canvas.drawRect(right - length, top, right, bottom, p); 15145 } 15146 15147 canvas.restoreToCount(saveCount); 15148 15149 // Step 6, draw decorations (scrollbars) 15150 onDrawScrollBars(canvas); 15151 15152 if (mOverlay != null && !mOverlay.isEmpty()) { 15153 mOverlay.getOverlayView().dispatchDraw(canvas); 15154 } 15155 } 15156 15157 /** 15158 * Draws the background onto the specified canvas. 15159 * 15160 * @param canvas Canvas on which to draw the background 15161 */ 15162 private void drawBackground(Canvas canvas) { 15163 final Drawable background = mBackground; 15164 if (background == null) { 15165 return; 15166 } 15167 15168 if (mBackgroundSizeChanged) { 15169 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 15170 mBackgroundSizeChanged = false; 15171 if ((mPrivateFlags3 & PFLAG3_OUTLINE_DEFINED) == 0) { 15172 // Outline not currently define, query from background 15173 mOutline = background.getOutline(); 15174 if (mRenderNode != null) { 15175 mRenderNode.setOutline(mOutline); 15176 } 15177 } 15178 } 15179 15180 // Attempt to use a display list if requested. 15181 if (canvas.isHardwareAccelerated() && mAttachInfo != null 15182 && mAttachInfo.mHardwareRenderer != null) { 15183 mBackgroundDisplayList = getDrawableDisplayList(background, mBackgroundDisplayList); 15184 15185 final RenderNode displayList = mBackgroundDisplayList; 15186 if (displayList != null && displayList.isValid()) { 15187 setBackgroundDisplayListProperties(displayList); 15188 ((HardwareCanvas) canvas).drawDisplayList(displayList); 15189 return; 15190 } 15191 } 15192 15193 final int scrollX = mScrollX; 15194 final int scrollY = mScrollY; 15195 if ((scrollX | scrollY) == 0) { 15196 background.draw(canvas); 15197 } else { 15198 canvas.translate(scrollX, scrollY); 15199 background.draw(canvas); 15200 canvas.translate(-scrollX, -scrollY); 15201 } 15202 } 15203 15204 /** 15205 * Set up background drawable display list properties. 15206 * 15207 * @param displayList Valid display list for the background drawable 15208 */ 15209 private void setBackgroundDisplayListProperties(RenderNode displayList) { 15210 displayList.setTranslationX(mScrollX); 15211 displayList.setTranslationY(mScrollY); 15212 } 15213 15214 /** 15215 * Creates a new display list or updates the existing display list for the 15216 * specified Drawable. 15217 * 15218 * @param drawable Drawable for which to create a display list 15219 * @param displayList Existing display list, or {@code null} 15220 * @return A valid display list for the specified drawable 15221 */ 15222 private RenderNode getDrawableDisplayList(Drawable drawable, RenderNode displayList) { 15223 if (displayList == null) { 15224 displayList = RenderNode.create(drawable.getClass().getName()); 15225 } 15226 15227 final Rect bounds = drawable.getBounds(); 15228 final int width = bounds.width(); 15229 final int height = bounds.height(); 15230 final HardwareCanvas canvas = displayList.start(width, height); 15231 drawable.draw(canvas); 15232 displayList.end(getHardwareRenderer(), canvas); 15233 15234 // Set up drawable properties that are view-independent. 15235 displayList.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom); 15236 displayList.setProjectBackwards(drawable.isProjected()); 15237 displayList.setProjectionReceiver(true); 15238 displayList.setClipToBounds(false); 15239 return displayList; 15240 } 15241 15242 /** 15243 * Returns the overlay for this view, creating it if it does not yet exist. 15244 * Adding drawables to the overlay will cause them to be displayed whenever 15245 * the view itself is redrawn. Objects in the overlay should be actively 15246 * managed: remove them when they should not be displayed anymore. The 15247 * overlay will always have the same size as its host view. 15248 * 15249 * <p>Note: Overlays do not currently work correctly with {@link 15250 * SurfaceView} or {@link TextureView}; contents in overlays for these 15251 * types of views may not display correctly.</p> 15252 * 15253 * @return The ViewOverlay object for this view. 15254 * @see ViewOverlay 15255 */ 15256 public ViewOverlay getOverlay() { 15257 if (mOverlay == null) { 15258 mOverlay = new ViewOverlay(mContext, this); 15259 } 15260 return mOverlay; 15261 } 15262 15263 /** 15264 * Override this if your view is known to always be drawn on top of a solid color background, 15265 * and needs to draw fading edges. Returning a non-zero color enables the view system to 15266 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 15267 * should be set to 0xFF. 15268 * 15269 * @see #setVerticalFadingEdgeEnabled(boolean) 15270 * @see #setHorizontalFadingEdgeEnabled(boolean) 15271 * 15272 * @return The known solid color background for this view, or 0 if the color may vary 15273 */ 15274 @ViewDebug.ExportedProperty(category = "drawing") 15275 public int getSolidColor() { 15276 return 0; 15277 } 15278 15279 /** 15280 * Build a human readable string representation of the specified view flags. 15281 * 15282 * @param flags the view flags to convert to a string 15283 * @return a String representing the supplied flags 15284 */ 15285 private static String printFlags(int flags) { 15286 String output = ""; 15287 int numFlags = 0; 15288 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 15289 output += "TAKES_FOCUS"; 15290 numFlags++; 15291 } 15292 15293 switch (flags & VISIBILITY_MASK) { 15294 case INVISIBLE: 15295 if (numFlags > 0) { 15296 output += " "; 15297 } 15298 output += "INVISIBLE"; 15299 // USELESS HERE numFlags++; 15300 break; 15301 case GONE: 15302 if (numFlags > 0) { 15303 output += " "; 15304 } 15305 output += "GONE"; 15306 // USELESS HERE numFlags++; 15307 break; 15308 default: 15309 break; 15310 } 15311 return output; 15312 } 15313 15314 /** 15315 * Build a human readable string representation of the specified private 15316 * view flags. 15317 * 15318 * @param privateFlags the private view flags to convert to a string 15319 * @return a String representing the supplied flags 15320 */ 15321 private static String printPrivateFlags(int privateFlags) { 15322 String output = ""; 15323 int numFlags = 0; 15324 15325 if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) { 15326 output += "WANTS_FOCUS"; 15327 numFlags++; 15328 } 15329 15330 if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) { 15331 if (numFlags > 0) { 15332 output += " "; 15333 } 15334 output += "FOCUSED"; 15335 numFlags++; 15336 } 15337 15338 if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) { 15339 if (numFlags > 0) { 15340 output += " "; 15341 } 15342 output += "SELECTED"; 15343 numFlags++; 15344 } 15345 15346 if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) { 15347 if (numFlags > 0) { 15348 output += " "; 15349 } 15350 output += "IS_ROOT_NAMESPACE"; 15351 numFlags++; 15352 } 15353 15354 if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) { 15355 if (numFlags > 0) { 15356 output += " "; 15357 } 15358 output += "HAS_BOUNDS"; 15359 numFlags++; 15360 } 15361 15362 if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) { 15363 if (numFlags > 0) { 15364 output += " "; 15365 } 15366 output += "DRAWN"; 15367 // USELESS HERE numFlags++; 15368 } 15369 return output; 15370 } 15371 15372 /** 15373 * <p>Indicates whether or not this view's layout will be requested during 15374 * the next hierarchy layout pass.</p> 15375 * 15376 * @return true if the layout will be forced during next layout pass 15377 */ 15378 public boolean isLayoutRequested() { 15379 return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 15380 } 15381 15382 /** 15383 * Return true if o is a ViewGroup that is laying out using optical bounds. 15384 * @hide 15385 */ 15386 public static boolean isLayoutModeOptical(Object o) { 15387 return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical(); 15388 } 15389 15390 private boolean setOpticalFrame(int left, int top, int right, int bottom) { 15391 Insets parentInsets = mParent instanceof View ? 15392 ((View) mParent).getOpticalInsets() : Insets.NONE; 15393 Insets childInsets = getOpticalInsets(); 15394 return setFrame( 15395 left + parentInsets.left - childInsets.left, 15396 top + parentInsets.top - childInsets.top, 15397 right + parentInsets.left + childInsets.right, 15398 bottom + parentInsets.top + childInsets.bottom); 15399 } 15400 15401 /** 15402 * Assign a size and position to a view and all of its 15403 * descendants 15404 * 15405 * <p>This is the second phase of the layout mechanism. 15406 * (The first is measuring). In this phase, each parent calls 15407 * layout on all of its children to position them. 15408 * This is typically done using the child measurements 15409 * that were stored in the measure pass().</p> 15410 * 15411 * <p>Derived classes should not override this method. 15412 * Derived classes with children should override 15413 * onLayout. In that method, they should 15414 * call layout on each of their children.</p> 15415 * 15416 * @param l Left position, relative to parent 15417 * @param t Top position, relative to parent 15418 * @param r Right position, relative to parent 15419 * @param b Bottom position, relative to parent 15420 */ 15421 @SuppressWarnings({"unchecked"}) 15422 public void layout(int l, int t, int r, int b) { 15423 if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) { 15424 onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec); 15425 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 15426 } 15427 15428 int oldL = mLeft; 15429 int oldT = mTop; 15430 int oldB = mBottom; 15431 int oldR = mRight; 15432 15433 boolean changed = isLayoutModeOptical(mParent) ? 15434 setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b); 15435 15436 if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) { 15437 onLayout(changed, l, t, r, b); 15438 mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED; 15439 15440 ListenerInfo li = mListenerInfo; 15441 if (li != null && li.mOnLayoutChangeListeners != null) { 15442 ArrayList<OnLayoutChangeListener> listenersCopy = 15443 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 15444 int numListeners = listenersCopy.size(); 15445 for (int i = 0; i < numListeners; ++i) { 15446 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 15447 } 15448 } 15449 } 15450 15451 mPrivateFlags &= ~PFLAG_FORCE_LAYOUT; 15452 mPrivateFlags3 |= PFLAG3_IS_LAID_OUT; 15453 } 15454 15455 /** 15456 * Called from layout when this view should 15457 * assign a size and position to each of its children. 15458 * 15459 * Derived classes with children should override 15460 * this method and call layout on each of 15461 * their children. 15462 * @param changed This is a new size or position for this view 15463 * @param left Left position, relative to parent 15464 * @param top Top position, relative to parent 15465 * @param right Right position, relative to parent 15466 * @param bottom Bottom position, relative to parent 15467 */ 15468 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 15469 } 15470 15471 /** 15472 * Assign a size and position to this view. 15473 * 15474 * This is called from layout. 15475 * 15476 * @param left Left position, relative to parent 15477 * @param top Top position, relative to parent 15478 * @param right Right position, relative to parent 15479 * @param bottom Bottom position, relative to parent 15480 * @return true if the new size and position are different than the 15481 * previous ones 15482 * {@hide} 15483 */ 15484 protected boolean setFrame(int left, int top, int right, int bottom) { 15485 boolean changed = false; 15486 15487 if (DBG) { 15488 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 15489 + right + "," + bottom + ")"); 15490 } 15491 15492 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 15493 changed = true; 15494 15495 // Remember our drawn bit 15496 int drawn = mPrivateFlags & PFLAG_DRAWN; 15497 15498 int oldWidth = mRight - mLeft; 15499 int oldHeight = mBottom - mTop; 15500 int newWidth = right - left; 15501 int newHeight = bottom - top; 15502 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 15503 15504 // Invalidate our old position 15505 invalidate(sizeChanged); 15506 15507 mLeft = left; 15508 mTop = top; 15509 mRight = right; 15510 mBottom = bottom; 15511 if (mRenderNode != null) { 15512 mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 15513 } 15514 15515 mPrivateFlags |= PFLAG_HAS_BOUNDS; 15516 15517 15518 if (sizeChanged) { 15519 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 15520 // A change in dimension means an auto-centered pivot point changes, too 15521 if (mTransformationInfo != null) { 15522 mTransformationInfo.mMatrixDirty = true; 15523 } 15524 } 15525 sizeChange(newWidth, newHeight, oldWidth, oldHeight); 15526 } 15527 15528 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) { 15529 // If we are visible, force the DRAWN bit to on so that 15530 // this invalidate will go through (at least to our parent). 15531 // This is because someone may have invalidated this view 15532 // before this call to setFrame came in, thereby clearing 15533 // the DRAWN bit. 15534 mPrivateFlags |= PFLAG_DRAWN; 15535 invalidate(sizeChanged); 15536 // parent display list may need to be recreated based on a change in the bounds 15537 // of any child 15538 invalidateParentCaches(); 15539 } 15540 15541 // Reset drawn bit to original value (invalidate turns it off) 15542 mPrivateFlags |= drawn; 15543 15544 mBackgroundSizeChanged = true; 15545 15546 notifySubtreeAccessibilityStateChangedIfNeeded(); 15547 } 15548 return changed; 15549 } 15550 15551 private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) { 15552 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 15553 if (mOverlay != null) { 15554 mOverlay.getOverlayView().setRight(newWidth); 15555 mOverlay.getOverlayView().setBottom(newHeight); 15556 } 15557 } 15558 15559 /** 15560 * Finalize inflating a view from XML. This is called as the last phase 15561 * of inflation, after all child views have been added. 15562 * 15563 * <p>Even if the subclass overrides onFinishInflate, they should always be 15564 * sure to call the super method, so that we get called. 15565 */ 15566 protected void onFinishInflate() { 15567 } 15568 15569 /** 15570 * Returns the resources associated with this view. 15571 * 15572 * @return Resources object. 15573 */ 15574 public Resources getResources() { 15575 return mResources; 15576 } 15577 15578 /** 15579 * Invalidates the specified Drawable. 15580 * 15581 * @param drawable the drawable to invalidate 15582 */ 15583 @Override 15584 public void invalidateDrawable(Drawable drawable) { 15585 if (verifyDrawable(drawable)) { 15586 final Rect dirty = drawable.getDirtyBounds(); 15587 final int scrollX = mScrollX; 15588 final int scrollY = mScrollY; 15589 15590 invalidate(dirty.left + scrollX, dirty.top + scrollY, 15591 dirty.right + scrollX, dirty.bottom + scrollY); 15592 } 15593 } 15594 15595 /** 15596 * Schedules an action on a drawable to occur at a specified time. 15597 * 15598 * @param who the recipient of the action 15599 * @param what the action to run on the drawable 15600 * @param when the time at which the action must occur. Uses the 15601 * {@link SystemClock#uptimeMillis} timebase. 15602 */ 15603 @Override 15604 public void scheduleDrawable(Drawable who, Runnable what, long when) { 15605 if (verifyDrawable(who) && what != null) { 15606 final long delay = when - SystemClock.uptimeMillis(); 15607 if (mAttachInfo != null) { 15608 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 15609 Choreographer.CALLBACK_ANIMATION, what, who, 15610 Choreographer.subtractFrameDelay(delay)); 15611 } else { 15612 ViewRootImpl.getRunQueue().postDelayed(what, delay); 15613 } 15614 } 15615 } 15616 15617 /** 15618 * Cancels a scheduled action on a drawable. 15619 * 15620 * @param who the recipient of the action 15621 * @param what the action to cancel 15622 */ 15623 @Override 15624 public void unscheduleDrawable(Drawable who, Runnable what) { 15625 if (verifyDrawable(who) && what != null) { 15626 if (mAttachInfo != null) { 15627 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 15628 Choreographer.CALLBACK_ANIMATION, what, who); 15629 } 15630 ViewRootImpl.getRunQueue().removeCallbacks(what); 15631 } 15632 } 15633 15634 /** 15635 * Unschedule any events associated with the given Drawable. This can be 15636 * used when selecting a new Drawable into a view, so that the previous 15637 * one is completely unscheduled. 15638 * 15639 * @param who The Drawable to unschedule. 15640 * 15641 * @see #drawableStateChanged 15642 */ 15643 public void unscheduleDrawable(Drawable who) { 15644 if (mAttachInfo != null && who != null) { 15645 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 15646 Choreographer.CALLBACK_ANIMATION, null, who); 15647 } 15648 } 15649 15650 /** 15651 * Resolve the Drawables depending on the layout direction. This is implicitly supposing 15652 * that the View directionality can and will be resolved before its Drawables. 15653 * 15654 * Will call {@link View#onResolveDrawables} when resolution is done. 15655 * 15656 * @hide 15657 */ 15658 protected void resolveDrawables() { 15659 // Drawables resolution may need to happen before resolving the layout direction (which is 15660 // done only during the measure() call). 15661 // If the layout direction is not resolved yet, we cannot resolve the Drawables except in 15662 // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT. 15663 // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or 15664 // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout 15665 // direction to be resolved as its resolved value will be the same as its raw value. 15666 if (!isLayoutDirectionResolved() && 15667 getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) { 15668 return; 15669 } 15670 15671 final int layoutDirection = isLayoutDirectionResolved() ? 15672 getLayoutDirection() : getRawLayoutDirection(); 15673 15674 if (mBackground != null) { 15675 mBackground.setLayoutDirection(layoutDirection); 15676 } 15677 mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED; 15678 onResolveDrawables(layoutDirection); 15679 } 15680 15681 /** 15682 * Called when layout direction has been resolved. 15683 * 15684 * The default implementation does nothing. 15685 * 15686 * @param layoutDirection The resolved layout direction. 15687 * 15688 * @see #LAYOUT_DIRECTION_LTR 15689 * @see #LAYOUT_DIRECTION_RTL 15690 * 15691 * @hide 15692 */ 15693 public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) { 15694 } 15695 15696 /** 15697 * @hide 15698 */ 15699 protected void resetResolvedDrawables() { 15700 mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED; 15701 } 15702 15703 private boolean isDrawablesResolved() { 15704 return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED; 15705 } 15706 15707 /** 15708 * If your view subclass is displaying its own Drawable objects, it should 15709 * override this function and return true for any Drawable it is 15710 * displaying. This allows animations for those drawables to be 15711 * scheduled. 15712 * 15713 * <p>Be sure to call through to the super class when overriding this 15714 * function. 15715 * 15716 * @param who The Drawable to verify. Return true if it is one you are 15717 * displaying, else return the result of calling through to the 15718 * super class. 15719 * 15720 * @return boolean If true than the Drawable is being displayed in the 15721 * view; else false and it is not allowed to animate. 15722 * 15723 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 15724 * @see #drawableStateChanged() 15725 */ 15726 protected boolean verifyDrawable(Drawable who) { 15727 return who == mBackground; 15728 } 15729 15730 /** 15731 * This function is called whenever the state of the view changes in such 15732 * a way that it impacts the state of drawables being shown. 15733 * 15734 * <p>Be sure to call through to the superclass when overriding this 15735 * function. 15736 * 15737 * @see Drawable#setState(int[]) 15738 */ 15739 protected void drawableStateChanged() { 15740 final Drawable d = mBackground; 15741 if (d != null && d.isStateful()) { 15742 d.setState(getDrawableState()); 15743 } 15744 } 15745 15746 /** 15747 * Call this to force a view to update its drawable state. This will cause 15748 * drawableStateChanged to be called on this view. Views that are interested 15749 * in the new state should call getDrawableState. 15750 * 15751 * @see #drawableStateChanged 15752 * @see #getDrawableState 15753 */ 15754 public void refreshDrawableState() { 15755 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 15756 drawableStateChanged(); 15757 15758 ViewParent parent = mParent; 15759 if (parent != null) { 15760 parent.childDrawableStateChanged(this); 15761 } 15762 } 15763 15764 /** 15765 * Return an array of resource IDs of the drawable states representing the 15766 * current state of the view. 15767 * 15768 * @return The current drawable state 15769 * 15770 * @see Drawable#setState(int[]) 15771 * @see #drawableStateChanged() 15772 * @see #onCreateDrawableState(int) 15773 */ 15774 public final int[] getDrawableState() { 15775 if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) { 15776 return mDrawableState; 15777 } else { 15778 mDrawableState = onCreateDrawableState(0); 15779 mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY; 15780 return mDrawableState; 15781 } 15782 } 15783 15784 /** 15785 * Generate the new {@link android.graphics.drawable.Drawable} state for 15786 * this view. This is called by the view 15787 * system when the cached Drawable state is determined to be invalid. To 15788 * retrieve the current state, you should use {@link #getDrawableState}. 15789 * 15790 * @param extraSpace if non-zero, this is the number of extra entries you 15791 * would like in the returned array in which you can place your own 15792 * states. 15793 * 15794 * @return Returns an array holding the current {@link Drawable} state of 15795 * the view. 15796 * 15797 * @see #mergeDrawableStates(int[], int[]) 15798 */ 15799 protected int[] onCreateDrawableState(int extraSpace) { 15800 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 15801 mParent instanceof View) { 15802 return ((View) mParent).onCreateDrawableState(extraSpace); 15803 } 15804 15805 int[] drawableState; 15806 15807 int privateFlags = mPrivateFlags; 15808 15809 int viewStateIndex = 0; 15810 if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED; 15811 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED; 15812 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED; 15813 if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED; 15814 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED; 15815 if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED; 15816 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 15817 HardwareRenderer.isAvailable()) { 15818 // This is set if HW acceleration is requested, even if the current 15819 // process doesn't allow it. This is just to allow app preview 15820 // windows to better match their app. 15821 viewStateIndex |= VIEW_STATE_ACCELERATED; 15822 } 15823 if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED; 15824 15825 final int privateFlags2 = mPrivateFlags2; 15826 if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT; 15827 if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED; 15828 15829 drawableState = VIEW_STATE_SETS[viewStateIndex]; 15830 15831 //noinspection ConstantIfStatement 15832 if (false) { 15833 Log.i("View", "drawableStateIndex=" + viewStateIndex); 15834 Log.i("View", toString() 15835 + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0) 15836 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 15837 + " fo=" + hasFocus() 15838 + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0) 15839 + " wf=" + hasWindowFocus() 15840 + ": " + Arrays.toString(drawableState)); 15841 } 15842 15843 if (extraSpace == 0) { 15844 return drawableState; 15845 } 15846 15847 final int[] fullState; 15848 if (drawableState != null) { 15849 fullState = new int[drawableState.length + extraSpace]; 15850 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 15851 } else { 15852 fullState = new int[extraSpace]; 15853 } 15854 15855 return fullState; 15856 } 15857 15858 /** 15859 * Merge your own state values in <var>additionalState</var> into the base 15860 * state values <var>baseState</var> that were returned by 15861 * {@link #onCreateDrawableState(int)}. 15862 * 15863 * @param baseState The base state values returned by 15864 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 15865 * own additional state values. 15866 * 15867 * @param additionalState The additional state values you would like 15868 * added to <var>baseState</var>; this array is not modified. 15869 * 15870 * @return As a convenience, the <var>baseState</var> array you originally 15871 * passed into the function is returned. 15872 * 15873 * @see #onCreateDrawableState(int) 15874 */ 15875 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 15876 final int N = baseState.length; 15877 int i = N - 1; 15878 while (i >= 0 && baseState[i] == 0) { 15879 i--; 15880 } 15881 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 15882 return baseState; 15883 } 15884 15885 /** 15886 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 15887 * on all Drawable objects associated with this view. 15888 */ 15889 public void jumpDrawablesToCurrentState() { 15890 if (mBackground != null) { 15891 mBackground.jumpToCurrentState(); 15892 } 15893 } 15894 15895 /** 15896 * Sets the background color for this view. 15897 * @param color the color of the background 15898 */ 15899 @RemotableViewMethod 15900 public void setBackgroundColor(int color) { 15901 if (mBackground instanceof ColorDrawable) { 15902 ((ColorDrawable) mBackground.mutate()).setColor(color); 15903 computeOpaqueFlags(); 15904 mBackgroundResource = 0; 15905 } else { 15906 setBackground(new ColorDrawable(color)); 15907 } 15908 } 15909 15910 /** 15911 * Set the background to a given resource. The resource should refer to 15912 * a Drawable object or 0 to remove the background. 15913 * @param resid The identifier of the resource. 15914 * 15915 * @attr ref android.R.styleable#View_background 15916 */ 15917 @RemotableViewMethod 15918 public void setBackgroundResource(int resid) { 15919 if (resid != 0 && resid == mBackgroundResource) { 15920 return; 15921 } 15922 15923 Drawable d= null; 15924 if (resid != 0) { 15925 d = mContext.getDrawable(resid); 15926 } 15927 setBackground(d); 15928 15929 mBackgroundResource = resid; 15930 } 15931 15932 /** 15933 * Set the background to a given Drawable, or remove the background. If the 15934 * background has padding, this View's padding is set to the background's 15935 * padding. However, when a background is removed, this View's padding isn't 15936 * touched. If setting the padding is desired, please use 15937 * {@link #setPadding(int, int, int, int)}. 15938 * 15939 * @param background The Drawable to use as the background, or null to remove the 15940 * background 15941 */ 15942 public void setBackground(Drawable background) { 15943 //noinspection deprecation 15944 setBackgroundDrawable(background); 15945 } 15946 15947 /** 15948 * @deprecated use {@link #setBackground(Drawable)} instead 15949 */ 15950 @Deprecated 15951 public void setBackgroundDrawable(Drawable background) { 15952 computeOpaqueFlags(); 15953 15954 if (background == mBackground) { 15955 return; 15956 } 15957 15958 boolean requestLayout = false; 15959 15960 mBackgroundResource = 0; 15961 15962 /* 15963 * Regardless of whether we're setting a new background or not, we want 15964 * to clear the previous drawable. 15965 */ 15966 if (mBackground != null) { 15967 mBackground.setCallback(null); 15968 unscheduleDrawable(mBackground); 15969 } 15970 15971 if (background != null) { 15972 Rect padding = sThreadLocal.get(); 15973 if (padding == null) { 15974 padding = new Rect(); 15975 sThreadLocal.set(padding); 15976 } 15977 resetResolvedDrawables(); 15978 background.setLayoutDirection(getLayoutDirection()); 15979 if (background.getPadding(padding)) { 15980 resetResolvedPadding(); 15981 switch (background.getLayoutDirection()) { 15982 case LAYOUT_DIRECTION_RTL: 15983 mUserPaddingLeftInitial = padding.right; 15984 mUserPaddingRightInitial = padding.left; 15985 internalSetPadding(padding.right, padding.top, padding.left, padding.bottom); 15986 break; 15987 case LAYOUT_DIRECTION_LTR: 15988 default: 15989 mUserPaddingLeftInitial = padding.left; 15990 mUserPaddingRightInitial = padding.right; 15991 internalSetPadding(padding.left, padding.top, padding.right, padding.bottom); 15992 } 15993 mLeftPaddingDefined = false; 15994 mRightPaddingDefined = false; 15995 } 15996 15997 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 15998 // if it has a different minimum size, we should layout again 15999 if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() || 16000 mBackground.getMinimumWidth() != background.getMinimumWidth()) { 16001 requestLayout = true; 16002 } 16003 16004 background.setCallback(this); 16005 if (background.isStateful()) { 16006 background.setState(getDrawableState()); 16007 } 16008 background.setVisible(getVisibility() == VISIBLE, false); 16009 mBackground = background; 16010 16011 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 16012 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 16013 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 16014 requestLayout = true; 16015 } 16016 } else { 16017 /* Remove the background */ 16018 mBackground = null; 16019 16020 if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) { 16021 /* 16022 * This view ONLY drew the background before and we're removing 16023 * the background, so now it won't draw anything 16024 * (hence we SKIP_DRAW) 16025 */ 16026 mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND; 16027 mPrivateFlags |= PFLAG_SKIP_DRAW; 16028 } 16029 16030 /* 16031 * When the background is set, we try to apply its padding to this 16032 * View. When the background is removed, we don't touch this View's 16033 * padding. This is noted in the Javadocs. Hence, we don't need to 16034 * requestLayout(), the invalidate() below is sufficient. 16035 */ 16036 16037 // The old background's minimum size could have affected this 16038 // View's layout, so let's requestLayout 16039 requestLayout = true; 16040 } 16041 16042 computeOpaqueFlags(); 16043 16044 if (requestLayout) { 16045 requestLayout(); 16046 } 16047 16048 mBackgroundSizeChanged = true; 16049 invalidate(true); 16050 } 16051 16052 /** 16053 * Gets the background drawable 16054 * 16055 * @return The drawable used as the background for this view, if any. 16056 * 16057 * @see #setBackground(Drawable) 16058 * 16059 * @attr ref android.R.styleable#View_background 16060 */ 16061 public Drawable getBackground() { 16062 return mBackground; 16063 } 16064 16065 /** 16066 * Sets the padding. The view may add on the space required to display 16067 * the scrollbars, depending on the style and visibility of the scrollbars. 16068 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 16069 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 16070 * from the values set in this call. 16071 * 16072 * @attr ref android.R.styleable#View_padding 16073 * @attr ref android.R.styleable#View_paddingBottom 16074 * @attr ref android.R.styleable#View_paddingLeft 16075 * @attr ref android.R.styleable#View_paddingRight 16076 * @attr ref android.R.styleable#View_paddingTop 16077 * @param left the left padding in pixels 16078 * @param top the top padding in pixels 16079 * @param right the right padding in pixels 16080 * @param bottom the bottom padding in pixels 16081 */ 16082 public void setPadding(int left, int top, int right, int bottom) { 16083 resetResolvedPadding(); 16084 16085 mUserPaddingStart = UNDEFINED_PADDING; 16086 mUserPaddingEnd = UNDEFINED_PADDING; 16087 16088 mUserPaddingLeftInitial = left; 16089 mUserPaddingRightInitial = right; 16090 16091 mLeftPaddingDefined = true; 16092 mRightPaddingDefined = true; 16093 16094 internalSetPadding(left, top, right, bottom); 16095 } 16096 16097 /** 16098 * @hide 16099 */ 16100 protected void internalSetPadding(int left, int top, int right, int bottom) { 16101 mUserPaddingLeft = left; 16102 mUserPaddingRight = right; 16103 mUserPaddingBottom = bottom; 16104 16105 final int viewFlags = mViewFlags; 16106 boolean changed = false; 16107 16108 // Common case is there are no scroll bars. 16109 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 16110 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 16111 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 16112 ? 0 : getVerticalScrollbarWidth(); 16113 switch (mVerticalScrollbarPosition) { 16114 case SCROLLBAR_POSITION_DEFAULT: 16115 if (isLayoutRtl()) { 16116 left += offset; 16117 } else { 16118 right += offset; 16119 } 16120 break; 16121 case SCROLLBAR_POSITION_RIGHT: 16122 right += offset; 16123 break; 16124 case SCROLLBAR_POSITION_LEFT: 16125 left += offset; 16126 break; 16127 } 16128 } 16129 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 16130 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 16131 ? 0 : getHorizontalScrollbarHeight(); 16132 } 16133 } 16134 16135 if (mPaddingLeft != left) { 16136 changed = true; 16137 mPaddingLeft = left; 16138 } 16139 if (mPaddingTop != top) { 16140 changed = true; 16141 mPaddingTop = top; 16142 } 16143 if (mPaddingRight != right) { 16144 changed = true; 16145 mPaddingRight = right; 16146 } 16147 if (mPaddingBottom != bottom) { 16148 changed = true; 16149 mPaddingBottom = bottom; 16150 } 16151 16152 if (changed) { 16153 requestLayout(); 16154 } 16155 } 16156 16157 /** 16158 * Sets the relative padding. The view may add on the space required to display 16159 * the scrollbars, depending on the style and visibility of the scrollbars. 16160 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 16161 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 16162 * from the values set in this call. 16163 * 16164 * @attr ref android.R.styleable#View_padding 16165 * @attr ref android.R.styleable#View_paddingBottom 16166 * @attr ref android.R.styleable#View_paddingStart 16167 * @attr ref android.R.styleable#View_paddingEnd 16168 * @attr ref android.R.styleable#View_paddingTop 16169 * @param start the start padding in pixels 16170 * @param top the top padding in pixels 16171 * @param end the end padding in pixels 16172 * @param bottom the bottom padding in pixels 16173 */ 16174 public void setPaddingRelative(int start, int top, int end, int bottom) { 16175 resetResolvedPadding(); 16176 16177 mUserPaddingStart = start; 16178 mUserPaddingEnd = end; 16179 mLeftPaddingDefined = true; 16180 mRightPaddingDefined = true; 16181 16182 switch(getLayoutDirection()) { 16183 case LAYOUT_DIRECTION_RTL: 16184 mUserPaddingLeftInitial = end; 16185 mUserPaddingRightInitial = start; 16186 internalSetPadding(end, top, start, bottom); 16187 break; 16188 case LAYOUT_DIRECTION_LTR: 16189 default: 16190 mUserPaddingLeftInitial = start; 16191 mUserPaddingRightInitial = end; 16192 internalSetPadding(start, top, end, bottom); 16193 } 16194 } 16195 16196 /** 16197 * Returns the top padding of this view. 16198 * 16199 * @return the top padding in pixels 16200 */ 16201 public int getPaddingTop() { 16202 return mPaddingTop; 16203 } 16204 16205 /** 16206 * Returns the bottom padding of this view. If there are inset and enabled 16207 * scrollbars, this value may include the space required to display the 16208 * scrollbars as well. 16209 * 16210 * @return the bottom padding in pixels 16211 */ 16212 public int getPaddingBottom() { 16213 return mPaddingBottom; 16214 } 16215 16216 /** 16217 * Returns the left padding of this view. If there are inset and enabled 16218 * scrollbars, this value may include the space required to display the 16219 * scrollbars as well. 16220 * 16221 * @return the left padding in pixels 16222 */ 16223 public int getPaddingLeft() { 16224 if (!isPaddingResolved()) { 16225 resolvePadding(); 16226 } 16227 return mPaddingLeft; 16228 } 16229 16230 /** 16231 * Returns the start padding of this view depending on its resolved layout direction. 16232 * If there are inset and enabled scrollbars, this value may include the space 16233 * required to display the scrollbars as well. 16234 * 16235 * @return the start padding in pixels 16236 */ 16237 public int getPaddingStart() { 16238 if (!isPaddingResolved()) { 16239 resolvePadding(); 16240 } 16241 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 16242 mPaddingRight : mPaddingLeft; 16243 } 16244 16245 /** 16246 * Returns the right padding of this view. If there are inset and enabled 16247 * scrollbars, this value may include the space required to display the 16248 * scrollbars as well. 16249 * 16250 * @return the right padding in pixels 16251 */ 16252 public int getPaddingRight() { 16253 if (!isPaddingResolved()) { 16254 resolvePadding(); 16255 } 16256 return mPaddingRight; 16257 } 16258 16259 /** 16260 * Returns the end padding of this view depending on its resolved layout direction. 16261 * If there are inset and enabled scrollbars, this value may include the space 16262 * required to display the scrollbars as well. 16263 * 16264 * @return the end padding in pixels 16265 */ 16266 public int getPaddingEnd() { 16267 if (!isPaddingResolved()) { 16268 resolvePadding(); 16269 } 16270 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 16271 mPaddingLeft : mPaddingRight; 16272 } 16273 16274 /** 16275 * Return if the padding as been set thru relative values 16276 * {@link #setPaddingRelative(int, int, int, int)} or thru 16277 * @attr ref android.R.styleable#View_paddingStart or 16278 * @attr ref android.R.styleable#View_paddingEnd 16279 * 16280 * @return true if the padding is relative or false if it is not. 16281 */ 16282 public boolean isPaddingRelative() { 16283 return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING); 16284 } 16285 16286 Insets computeOpticalInsets() { 16287 return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets(); 16288 } 16289 16290 /** 16291 * @hide 16292 */ 16293 public void resetPaddingToInitialValues() { 16294 if (isRtlCompatibilityMode()) { 16295 mPaddingLeft = mUserPaddingLeftInitial; 16296 mPaddingRight = mUserPaddingRightInitial; 16297 return; 16298 } 16299 if (isLayoutRtl()) { 16300 mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial; 16301 mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial; 16302 } else { 16303 mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial; 16304 mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial; 16305 } 16306 } 16307 16308 /** 16309 * @hide 16310 */ 16311 public Insets getOpticalInsets() { 16312 if (mLayoutInsets == null) { 16313 mLayoutInsets = computeOpticalInsets(); 16314 } 16315 return mLayoutInsets; 16316 } 16317 16318 /** 16319 * Changes the selection state of this view. A view can be selected or not. 16320 * Note that selection is not the same as focus. Views are typically 16321 * selected in the context of an AdapterView like ListView or GridView; 16322 * the selected view is the view that is highlighted. 16323 * 16324 * @param selected true if the view must be selected, false otherwise 16325 */ 16326 public void setSelected(boolean selected) { 16327 //noinspection DoubleNegation 16328 if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) { 16329 mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0); 16330 if (!selected) resetPressedState(); 16331 invalidate(true); 16332 refreshDrawableState(); 16333 dispatchSetSelected(selected); 16334 notifyViewAccessibilityStateChangedIfNeeded( 16335 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 16336 } 16337 } 16338 16339 /** 16340 * Dispatch setSelected to all of this View's children. 16341 * 16342 * @see #setSelected(boolean) 16343 * 16344 * @param selected The new selected state 16345 */ 16346 protected void dispatchSetSelected(boolean selected) { 16347 } 16348 16349 /** 16350 * Indicates the selection state of this view. 16351 * 16352 * @return true if the view is selected, false otherwise 16353 */ 16354 @ViewDebug.ExportedProperty 16355 public boolean isSelected() { 16356 return (mPrivateFlags & PFLAG_SELECTED) != 0; 16357 } 16358 16359 /** 16360 * Changes the activated state of this view. A view can be activated or not. 16361 * Note that activation is not the same as selection. Selection is 16362 * a transient property, representing the view (hierarchy) the user is 16363 * currently interacting with. Activation is a longer-term state that the 16364 * user can move views in and out of. For example, in a list view with 16365 * single or multiple selection enabled, the views in the current selection 16366 * set are activated. (Um, yeah, we are deeply sorry about the terminology 16367 * here.) The activated state is propagated down to children of the view it 16368 * is set on. 16369 * 16370 * @param activated true if the view must be activated, false otherwise 16371 */ 16372 public void setActivated(boolean activated) { 16373 //noinspection DoubleNegation 16374 if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) { 16375 mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0); 16376 invalidate(true); 16377 refreshDrawableState(); 16378 dispatchSetActivated(activated); 16379 } 16380 } 16381 16382 /** 16383 * Dispatch setActivated to all of this View's children. 16384 * 16385 * @see #setActivated(boolean) 16386 * 16387 * @param activated The new activated state 16388 */ 16389 protected void dispatchSetActivated(boolean activated) { 16390 } 16391 16392 /** 16393 * Indicates the activation state of this view. 16394 * 16395 * @return true if the view is activated, false otherwise 16396 */ 16397 @ViewDebug.ExportedProperty 16398 public boolean isActivated() { 16399 return (mPrivateFlags & PFLAG_ACTIVATED) != 0; 16400 } 16401 16402 /** 16403 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 16404 * observer can be used to get notifications when global events, like 16405 * layout, happen. 16406 * 16407 * The returned ViewTreeObserver observer is not guaranteed to remain 16408 * valid for the lifetime of this View. If the caller of this method keeps 16409 * a long-lived reference to ViewTreeObserver, it should always check for 16410 * the return value of {@link ViewTreeObserver#isAlive()}. 16411 * 16412 * @return The ViewTreeObserver for this view's hierarchy. 16413 */ 16414 public ViewTreeObserver getViewTreeObserver() { 16415 if (mAttachInfo != null) { 16416 return mAttachInfo.mTreeObserver; 16417 } 16418 if (mFloatingTreeObserver == null) { 16419 mFloatingTreeObserver = new ViewTreeObserver(); 16420 } 16421 return mFloatingTreeObserver; 16422 } 16423 16424 /** 16425 * <p>Finds the topmost view in the current view hierarchy.</p> 16426 * 16427 * @return the topmost view containing this view 16428 */ 16429 public View getRootView() { 16430 if (mAttachInfo != null) { 16431 final View v = mAttachInfo.mRootView; 16432 if (v != null) { 16433 return v; 16434 } 16435 } 16436 16437 View parent = this; 16438 16439 while (parent.mParent != null && parent.mParent instanceof View) { 16440 parent = (View) parent.mParent; 16441 } 16442 16443 return parent; 16444 } 16445 16446 /** 16447 * Transforms a motion event from view-local coordinates to on-screen 16448 * coordinates. 16449 * 16450 * @param ev the view-local motion event 16451 * @return false if the transformation could not be applied 16452 * @hide 16453 */ 16454 public boolean toGlobalMotionEvent(MotionEvent ev) { 16455 final AttachInfo info = mAttachInfo; 16456 if (info == null) { 16457 return false; 16458 } 16459 16460 final Matrix m = info.mTmpMatrix; 16461 m.set(Matrix.IDENTITY_MATRIX); 16462 transformMatrixToGlobal(m); 16463 ev.transform(m); 16464 return true; 16465 } 16466 16467 /** 16468 * Transforms a motion event from on-screen coordinates to view-local 16469 * coordinates. 16470 * 16471 * @param ev the on-screen motion event 16472 * @return false if the transformation could not be applied 16473 * @hide 16474 */ 16475 public boolean toLocalMotionEvent(MotionEvent ev) { 16476 final AttachInfo info = mAttachInfo; 16477 if (info == null) { 16478 return false; 16479 } 16480 16481 final Matrix m = info.mTmpMatrix; 16482 m.set(Matrix.IDENTITY_MATRIX); 16483 transformMatrixToLocal(m); 16484 ev.transform(m); 16485 return true; 16486 } 16487 16488 /** 16489 * Modifies the input matrix such that it maps view-local coordinates to 16490 * on-screen coordinates. 16491 * 16492 * @param m input matrix to modify 16493 */ 16494 void transformMatrixToGlobal(Matrix m) { 16495 final ViewParent parent = mParent; 16496 if (parent instanceof View) { 16497 final View vp = (View) parent; 16498 vp.transformMatrixToGlobal(m); 16499 m.postTranslate(-vp.mScrollX, -vp.mScrollY); 16500 } else if (parent instanceof ViewRootImpl) { 16501 final ViewRootImpl vr = (ViewRootImpl) parent; 16502 vr.transformMatrixToGlobal(m); 16503 m.postTranslate(0, -vr.mCurScrollY); 16504 } 16505 16506 m.postTranslate(mLeft, mTop); 16507 16508 if (!hasIdentityMatrix()) { 16509 m.postConcat(getMatrix()); 16510 } 16511 } 16512 16513 /** 16514 * Modifies the input matrix such that it maps on-screen coordinates to 16515 * view-local coordinates. 16516 * 16517 * @param m input matrix to modify 16518 */ 16519 void transformMatrixToLocal(Matrix m) { 16520 final ViewParent parent = mParent; 16521 if (parent instanceof View) { 16522 final View vp = (View) parent; 16523 vp.transformMatrixToLocal(m); 16524 m.preTranslate(vp.mScrollX, vp.mScrollY); 16525 } else if (parent instanceof ViewRootImpl) { 16526 final ViewRootImpl vr = (ViewRootImpl) parent; 16527 vr.transformMatrixToLocal(m); 16528 m.preTranslate(0, vr.mCurScrollY); 16529 } 16530 16531 m.preTranslate(-mLeft, -mTop); 16532 16533 if (!hasIdentityMatrix()) { 16534 m.preConcat(getInverseMatrix()); 16535 } 16536 } 16537 16538 /** 16539 * <p>Computes the coordinates of this view on the screen. The argument 16540 * must be an array of two integers. After the method returns, the array 16541 * contains the x and y location in that order.</p> 16542 * 16543 * @param location an array of two integers in which to hold the coordinates 16544 */ 16545 public void getLocationOnScreen(int[] location) { 16546 getLocationInWindow(location); 16547 16548 final AttachInfo info = mAttachInfo; 16549 if (info != null) { 16550 location[0] += info.mWindowLeft; 16551 location[1] += info.mWindowTop; 16552 } 16553 } 16554 16555 /** 16556 * <p>Computes the coordinates of this view in its window. The argument 16557 * must be an array of two integers. After the method returns, the array 16558 * contains the x and y location in that order.</p> 16559 * 16560 * @param location an array of two integers in which to hold the coordinates 16561 */ 16562 public void getLocationInWindow(int[] location) { 16563 if (location == null || location.length < 2) { 16564 throw new IllegalArgumentException("location must be an array of two integers"); 16565 } 16566 16567 if (mAttachInfo == null) { 16568 // When the view is not attached to a window, this method does not make sense 16569 location[0] = location[1] = 0; 16570 return; 16571 } 16572 16573 float[] position = mAttachInfo.mTmpTransformLocation; 16574 position[0] = position[1] = 0.0f; 16575 16576 if (!hasIdentityMatrix()) { 16577 getMatrix().mapPoints(position); 16578 } 16579 16580 position[0] += mLeft; 16581 position[1] += mTop; 16582 16583 ViewParent viewParent = mParent; 16584 while (viewParent instanceof View) { 16585 final View view = (View) viewParent; 16586 16587 position[0] -= view.mScrollX; 16588 position[1] -= view.mScrollY; 16589 16590 if (!view.hasIdentityMatrix()) { 16591 view.getMatrix().mapPoints(position); 16592 } 16593 16594 position[0] += view.mLeft; 16595 position[1] += view.mTop; 16596 16597 viewParent = view.mParent; 16598 } 16599 16600 if (viewParent instanceof ViewRootImpl) { 16601 // *cough* 16602 final ViewRootImpl vr = (ViewRootImpl) viewParent; 16603 position[1] -= vr.mCurScrollY; 16604 } 16605 16606 location[0] = (int) (position[0] + 0.5f); 16607 location[1] = (int) (position[1] + 0.5f); 16608 } 16609 16610 /** 16611 * {@hide} 16612 * @param id the id of the view to be found 16613 * @return the view of the specified id, null if cannot be found 16614 */ 16615 protected View findViewTraversal(int id) { 16616 if (id == mID) { 16617 return this; 16618 } 16619 return null; 16620 } 16621 16622 /** 16623 * {@hide} 16624 * @param tag the tag of the view to be found 16625 * @return the view of specified tag, null if cannot be found 16626 */ 16627 protected View findViewWithTagTraversal(Object tag) { 16628 if (tag != null && tag.equals(mTag)) { 16629 return this; 16630 } 16631 return null; 16632 } 16633 16634 /** 16635 * {@hide} 16636 * @param predicate The predicate to evaluate. 16637 * @param childToSkip If not null, ignores this child during the recursive traversal. 16638 * @return The first view that matches the predicate or null. 16639 */ 16640 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 16641 if (predicate.apply(this)) { 16642 return this; 16643 } 16644 return null; 16645 } 16646 16647 /** 16648 * Look for a child view with the given id. If this view has the given 16649 * id, return this view. 16650 * 16651 * @param id The id to search for. 16652 * @return The view that has the given id in the hierarchy or null 16653 */ 16654 public final View findViewById(int id) { 16655 if (id < 0) { 16656 return null; 16657 } 16658 return findViewTraversal(id); 16659 } 16660 16661 /** 16662 * Finds a view by its unuque and stable accessibility id. 16663 * 16664 * @param accessibilityId The searched accessibility id. 16665 * @return The found view. 16666 */ 16667 final View findViewByAccessibilityId(int accessibilityId) { 16668 if (accessibilityId < 0) { 16669 return null; 16670 } 16671 return findViewByAccessibilityIdTraversal(accessibilityId); 16672 } 16673 16674 /** 16675 * Performs the traversal to find a view by its unuque and stable accessibility id. 16676 * 16677 * <strong>Note:</strong>This method does not stop at the root namespace 16678 * boundary since the user can touch the screen at an arbitrary location 16679 * potentially crossing the root namespace bounday which will send an 16680 * accessibility event to accessibility services and they should be able 16681 * to obtain the event source. Also accessibility ids are guaranteed to be 16682 * unique in the window. 16683 * 16684 * @param accessibilityId The accessibility id. 16685 * @return The found view. 16686 * 16687 * @hide 16688 */ 16689 public View findViewByAccessibilityIdTraversal(int accessibilityId) { 16690 if (getAccessibilityViewId() == accessibilityId) { 16691 return this; 16692 } 16693 return null; 16694 } 16695 16696 /** 16697 * Look for a child view with the given tag. If this view has the given 16698 * tag, return this view. 16699 * 16700 * @param tag The tag to search for, using "tag.equals(getTag())". 16701 * @return The View that has the given tag in the hierarchy or null 16702 */ 16703 public final View findViewWithTag(Object tag) { 16704 if (tag == null) { 16705 return null; 16706 } 16707 return findViewWithTagTraversal(tag); 16708 } 16709 16710 /** 16711 * {@hide} 16712 * Look for a child view that matches the specified predicate. 16713 * If this view matches the predicate, return this view. 16714 * 16715 * @param predicate The predicate to evaluate. 16716 * @return The first view that matches the predicate or null. 16717 */ 16718 public final View findViewByPredicate(Predicate<View> predicate) { 16719 return findViewByPredicateTraversal(predicate, null); 16720 } 16721 16722 /** 16723 * {@hide} 16724 * Look for a child view that matches the specified predicate, 16725 * starting with the specified view and its descendents and then 16726 * recusively searching the ancestors and siblings of that view 16727 * until this view is reached. 16728 * 16729 * This method is useful in cases where the predicate does not match 16730 * a single unique view (perhaps multiple views use the same id) 16731 * and we are trying to find the view that is "closest" in scope to the 16732 * starting view. 16733 * 16734 * @param start The view to start from. 16735 * @param predicate The predicate to evaluate. 16736 * @return The first view that matches the predicate or null. 16737 */ 16738 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 16739 View childToSkip = null; 16740 for (;;) { 16741 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 16742 if (view != null || start == this) { 16743 return view; 16744 } 16745 16746 ViewParent parent = start.getParent(); 16747 if (parent == null || !(parent instanceof View)) { 16748 return null; 16749 } 16750 16751 childToSkip = start; 16752 start = (View) parent; 16753 } 16754 } 16755 16756 /** 16757 * Sets the identifier for this view. The identifier does not have to be 16758 * unique in this view's hierarchy. The identifier should be a positive 16759 * number. 16760 * 16761 * @see #NO_ID 16762 * @see #getId() 16763 * @see #findViewById(int) 16764 * 16765 * @param id a number used to identify the view 16766 * 16767 * @attr ref android.R.styleable#View_id 16768 */ 16769 public void setId(int id) { 16770 mID = id; 16771 if (mID == View.NO_ID && mLabelForId != View.NO_ID) { 16772 mID = generateViewId(); 16773 } 16774 } 16775 16776 /** 16777 * {@hide} 16778 * 16779 * @param isRoot true if the view belongs to the root namespace, false 16780 * otherwise 16781 */ 16782 public void setIsRootNamespace(boolean isRoot) { 16783 if (isRoot) { 16784 mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE; 16785 } else { 16786 mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE; 16787 } 16788 } 16789 16790 /** 16791 * {@hide} 16792 * 16793 * @return true if the view belongs to the root namespace, false otherwise 16794 */ 16795 public boolean isRootNamespace() { 16796 return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0; 16797 } 16798 16799 /** 16800 * Returns this view's identifier. 16801 * 16802 * @return a positive integer used to identify the view or {@link #NO_ID} 16803 * if the view has no ID 16804 * 16805 * @see #setId(int) 16806 * @see #findViewById(int) 16807 * @attr ref android.R.styleable#View_id 16808 */ 16809 @ViewDebug.CapturedViewProperty 16810 public int getId() { 16811 return mID; 16812 } 16813 16814 /** 16815 * Returns this view's tag. 16816 * 16817 * @return the Object stored in this view as a tag, or {@code null} if not 16818 * set 16819 * 16820 * @see #setTag(Object) 16821 * @see #getTag(int) 16822 */ 16823 @ViewDebug.ExportedProperty 16824 public Object getTag() { 16825 return mTag; 16826 } 16827 16828 /** 16829 * Sets the tag associated with this view. A tag can be used to mark 16830 * a view in its hierarchy and does not have to be unique within the 16831 * hierarchy. Tags can also be used to store data within a view without 16832 * resorting to another data structure. 16833 * 16834 * @param tag an Object to tag the view with 16835 * 16836 * @see #getTag() 16837 * @see #setTag(int, Object) 16838 */ 16839 public void setTag(final Object tag) { 16840 mTag = tag; 16841 } 16842 16843 /** 16844 * Returns the tag associated with this view and the specified key. 16845 * 16846 * @param key The key identifying the tag 16847 * 16848 * @return the Object stored in this view as a tag, or {@code null} if not 16849 * set 16850 * 16851 * @see #setTag(int, Object) 16852 * @see #getTag() 16853 */ 16854 public Object getTag(int key) { 16855 if (mKeyedTags != null) return mKeyedTags.get(key); 16856 return null; 16857 } 16858 16859 /** 16860 * Sets a tag associated with this view and a key. A tag can be used 16861 * to mark a view in its hierarchy and does not have to be unique within 16862 * the hierarchy. Tags can also be used to store data within a view 16863 * without resorting to another data structure. 16864 * 16865 * The specified key should be an id declared in the resources of the 16866 * application to ensure it is unique (see the <a 16867 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 16868 * Keys identified as belonging to 16869 * the Android framework or not associated with any package will cause 16870 * an {@link IllegalArgumentException} to be thrown. 16871 * 16872 * @param key The key identifying the tag 16873 * @param tag An Object to tag the view with 16874 * 16875 * @throws IllegalArgumentException If they specified key is not valid 16876 * 16877 * @see #setTag(Object) 16878 * @see #getTag(int) 16879 */ 16880 public void setTag(int key, final Object tag) { 16881 // If the package id is 0x00 or 0x01, it's either an undefined package 16882 // or a framework id 16883 if ((key >>> 24) < 2) { 16884 throw new IllegalArgumentException("The key must be an application-specific " 16885 + "resource id."); 16886 } 16887 16888 setKeyedTag(key, tag); 16889 } 16890 16891 /** 16892 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 16893 * framework id. 16894 * 16895 * @hide 16896 */ 16897 public void setTagInternal(int key, Object tag) { 16898 if ((key >>> 24) != 0x1) { 16899 throw new IllegalArgumentException("The key must be a framework-specific " 16900 + "resource id."); 16901 } 16902 16903 setKeyedTag(key, tag); 16904 } 16905 16906 private void setKeyedTag(int key, Object tag) { 16907 if (mKeyedTags == null) { 16908 mKeyedTags = new SparseArray<Object>(2); 16909 } 16910 16911 mKeyedTags.put(key, tag); 16912 } 16913 16914 /** 16915 * Prints information about this view in the log output, with the tag 16916 * {@link #VIEW_LOG_TAG}. 16917 * 16918 * @hide 16919 */ 16920 public void debug() { 16921 debug(0); 16922 } 16923 16924 /** 16925 * Prints information about this view in the log output, with the tag 16926 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 16927 * indentation defined by the <code>depth</code>. 16928 * 16929 * @param depth the indentation level 16930 * 16931 * @hide 16932 */ 16933 protected void debug(int depth) { 16934 String output = debugIndent(depth - 1); 16935 16936 output += "+ " + this; 16937 int id = getId(); 16938 if (id != -1) { 16939 output += " (id=" + id + ")"; 16940 } 16941 Object tag = getTag(); 16942 if (tag != null) { 16943 output += " (tag=" + tag + ")"; 16944 } 16945 Log.d(VIEW_LOG_TAG, output); 16946 16947 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 16948 output = debugIndent(depth) + " FOCUSED"; 16949 Log.d(VIEW_LOG_TAG, output); 16950 } 16951 16952 output = debugIndent(depth); 16953 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 16954 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 16955 + "} "; 16956 Log.d(VIEW_LOG_TAG, output); 16957 16958 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 16959 || mPaddingBottom != 0) { 16960 output = debugIndent(depth); 16961 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 16962 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 16963 Log.d(VIEW_LOG_TAG, output); 16964 } 16965 16966 output = debugIndent(depth); 16967 output += "mMeasureWidth=" + mMeasuredWidth + 16968 " mMeasureHeight=" + mMeasuredHeight; 16969 Log.d(VIEW_LOG_TAG, output); 16970 16971 output = debugIndent(depth); 16972 if (mLayoutParams == null) { 16973 output += "BAD! no layout params"; 16974 } else { 16975 output = mLayoutParams.debug(output); 16976 } 16977 Log.d(VIEW_LOG_TAG, output); 16978 16979 output = debugIndent(depth); 16980 output += "flags={"; 16981 output += View.printFlags(mViewFlags); 16982 output += "}"; 16983 Log.d(VIEW_LOG_TAG, output); 16984 16985 output = debugIndent(depth); 16986 output += "privateFlags={"; 16987 output += View.printPrivateFlags(mPrivateFlags); 16988 output += "}"; 16989 Log.d(VIEW_LOG_TAG, output); 16990 } 16991 16992 /** 16993 * Creates a string of whitespaces used for indentation. 16994 * 16995 * @param depth the indentation level 16996 * @return a String containing (depth * 2 + 3) * 2 white spaces 16997 * 16998 * @hide 16999 */ 17000 protected static String debugIndent(int depth) { 17001 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 17002 for (int i = 0; i < (depth * 2) + 3; i++) { 17003 spaces.append(' ').append(' '); 17004 } 17005 return spaces.toString(); 17006 } 17007 17008 /** 17009 * <p>Return the offset of the widget's text baseline from the widget's top 17010 * boundary. If this widget does not support baseline alignment, this 17011 * method returns -1. </p> 17012 * 17013 * @return the offset of the baseline within the widget's bounds or -1 17014 * if baseline alignment is not supported 17015 */ 17016 @ViewDebug.ExportedProperty(category = "layout") 17017 public int getBaseline() { 17018 return -1; 17019 } 17020 17021 /** 17022 * Returns whether the view hierarchy is currently undergoing a layout pass. This 17023 * information is useful to avoid situations such as calling {@link #requestLayout()} during 17024 * a layout pass. 17025 * 17026 * @return whether the view hierarchy is currently undergoing a layout pass 17027 */ 17028 public boolean isInLayout() { 17029 ViewRootImpl viewRoot = getViewRootImpl(); 17030 return (viewRoot != null && viewRoot.isInLayout()); 17031 } 17032 17033 /** 17034 * Call this when something has changed which has invalidated the 17035 * layout of this view. This will schedule a layout pass of the view 17036 * tree. This should not be called while the view hierarchy is currently in a layout 17037 * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the 17038 * end of the current layout pass (and then layout will run again) or after the current 17039 * frame is drawn and the next layout occurs. 17040 * 17041 * <p>Subclasses which override this method should call the superclass method to 17042 * handle possible request-during-layout errors correctly.</p> 17043 */ 17044 public void requestLayout() { 17045 if (mMeasureCache != null) mMeasureCache.clear(); 17046 17047 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) { 17048 // Only trigger request-during-layout logic if this is the view requesting it, 17049 // not the views in its parent hierarchy 17050 ViewRootImpl viewRoot = getViewRootImpl(); 17051 if (viewRoot != null && viewRoot.isInLayout()) { 17052 if (!viewRoot.requestLayoutDuringLayout(this)) { 17053 return; 17054 } 17055 } 17056 mAttachInfo.mViewRequestingLayout = this; 17057 } 17058 17059 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 17060 mPrivateFlags |= PFLAG_INVALIDATED; 17061 17062 if (mParent != null && !mParent.isLayoutRequested()) { 17063 mParent.requestLayout(); 17064 } 17065 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) { 17066 mAttachInfo.mViewRequestingLayout = null; 17067 } 17068 } 17069 17070 /** 17071 * Forces this view to be laid out during the next layout pass. 17072 * This method does not call requestLayout() or forceLayout() 17073 * on the parent. 17074 */ 17075 public void forceLayout() { 17076 if (mMeasureCache != null) mMeasureCache.clear(); 17077 17078 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 17079 mPrivateFlags |= PFLAG_INVALIDATED; 17080 } 17081 17082 /** 17083 * <p> 17084 * This is called to find out how big a view should be. The parent 17085 * supplies constraint information in the width and height parameters. 17086 * </p> 17087 * 17088 * <p> 17089 * The actual measurement work of a view is performed in 17090 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 17091 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 17092 * </p> 17093 * 17094 * 17095 * @param widthMeasureSpec Horizontal space requirements as imposed by the 17096 * parent 17097 * @param heightMeasureSpec Vertical space requirements as imposed by the 17098 * parent 17099 * 17100 * @see #onMeasure(int, int) 17101 */ 17102 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 17103 boolean optical = isLayoutModeOptical(this); 17104 if (optical != isLayoutModeOptical(mParent)) { 17105 Insets insets = getOpticalInsets(); 17106 int oWidth = insets.left + insets.right; 17107 int oHeight = insets.top + insets.bottom; 17108 widthMeasureSpec = MeasureSpec.adjust(widthMeasureSpec, optical ? -oWidth : oWidth); 17109 heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight); 17110 } 17111 17112 // Suppress sign extension for the low bytes 17113 long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL; 17114 if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2); 17115 17116 if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT || 17117 widthMeasureSpec != mOldWidthMeasureSpec || 17118 heightMeasureSpec != mOldHeightMeasureSpec) { 17119 17120 // first clears the measured dimension flag 17121 mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET; 17122 17123 resolveRtlPropertiesIfNeeded(); 17124 17125 int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 : 17126 mMeasureCache.indexOfKey(key); 17127 if (cacheIndex < 0 || sIgnoreMeasureCache) { 17128 // measure ourselves, this should set the measured dimension flag back 17129 onMeasure(widthMeasureSpec, heightMeasureSpec); 17130 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 17131 } else { 17132 long value = mMeasureCache.valueAt(cacheIndex); 17133 // Casting a long to int drops the high 32 bits, no mask needed 17134 setMeasuredDimensionRaw((int) (value >> 32), (int) value); 17135 mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 17136 } 17137 17138 // flag not set, setMeasuredDimension() was not invoked, we raise 17139 // an exception to warn the developer 17140 if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) { 17141 throw new IllegalStateException("onMeasure() did not set the" 17142 + " measured dimension by calling" 17143 + " setMeasuredDimension()"); 17144 } 17145 17146 mPrivateFlags |= PFLAG_LAYOUT_REQUIRED; 17147 } 17148 17149 mOldWidthMeasureSpec = widthMeasureSpec; 17150 mOldHeightMeasureSpec = heightMeasureSpec; 17151 17152 mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 | 17153 (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension 17154 } 17155 17156 /** 17157 * <p> 17158 * Measure the view and its content to determine the measured width and the 17159 * measured height. This method is invoked by {@link #measure(int, int)} and 17160 * should be overriden by subclasses to provide accurate and efficient 17161 * measurement of their contents. 17162 * </p> 17163 * 17164 * <p> 17165 * <strong>CONTRACT:</strong> When overriding this method, you 17166 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 17167 * measured width and height of this view. Failure to do so will trigger an 17168 * <code>IllegalStateException</code>, thrown by 17169 * {@link #measure(int, int)}. Calling the superclass' 17170 * {@link #onMeasure(int, int)} is a valid use. 17171 * </p> 17172 * 17173 * <p> 17174 * The base class implementation of measure defaults to the background size, 17175 * unless a larger size is allowed by the MeasureSpec. Subclasses should 17176 * override {@link #onMeasure(int, int)} to provide better measurements of 17177 * their content. 17178 * </p> 17179 * 17180 * <p> 17181 * If this method is overridden, it is the subclass's responsibility to make 17182 * sure the measured height and width are at least the view's minimum height 17183 * and width ({@link #getSuggestedMinimumHeight()} and 17184 * {@link #getSuggestedMinimumWidth()}). 17185 * </p> 17186 * 17187 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 17188 * The requirements are encoded with 17189 * {@link android.view.View.MeasureSpec}. 17190 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 17191 * The requirements are encoded with 17192 * {@link android.view.View.MeasureSpec}. 17193 * 17194 * @see #getMeasuredWidth() 17195 * @see #getMeasuredHeight() 17196 * @see #setMeasuredDimension(int, int) 17197 * @see #getSuggestedMinimumHeight() 17198 * @see #getSuggestedMinimumWidth() 17199 * @see android.view.View.MeasureSpec#getMode(int) 17200 * @see android.view.View.MeasureSpec#getSize(int) 17201 */ 17202 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 17203 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 17204 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 17205 } 17206 17207 /** 17208 * <p>This method must be called by {@link #onMeasure(int, int)} to store the 17209 * measured width and measured height. Failing to do so will trigger an 17210 * exception at measurement time.</p> 17211 * 17212 * @param measuredWidth The measured width of this view. May be a complex 17213 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17214 * {@link #MEASURED_STATE_TOO_SMALL}. 17215 * @param measuredHeight The measured height of this view. May be a complex 17216 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17217 * {@link #MEASURED_STATE_TOO_SMALL}. 17218 */ 17219 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 17220 boolean optical = isLayoutModeOptical(this); 17221 if (optical != isLayoutModeOptical(mParent)) { 17222 Insets insets = getOpticalInsets(); 17223 int opticalWidth = insets.left + insets.right; 17224 int opticalHeight = insets.top + insets.bottom; 17225 17226 measuredWidth += optical ? opticalWidth : -opticalWidth; 17227 measuredHeight += optical ? opticalHeight : -opticalHeight; 17228 } 17229 setMeasuredDimensionRaw(measuredWidth, measuredHeight); 17230 } 17231 17232 /** 17233 * Sets the measured dimension without extra processing for things like optical bounds. 17234 * Useful for reapplying consistent values that have already been cooked with adjustments 17235 * for optical bounds, etc. such as those from the measurement cache. 17236 * 17237 * @param measuredWidth The measured width of this view. May be a complex 17238 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17239 * {@link #MEASURED_STATE_TOO_SMALL}. 17240 * @param measuredHeight The measured height of this view. May be a complex 17241 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17242 * {@link #MEASURED_STATE_TOO_SMALL}. 17243 */ 17244 private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) { 17245 mMeasuredWidth = measuredWidth; 17246 mMeasuredHeight = measuredHeight; 17247 17248 mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET; 17249 } 17250 17251 /** 17252 * Merge two states as returned by {@link #getMeasuredState()}. 17253 * @param curState The current state as returned from a view or the result 17254 * of combining multiple views. 17255 * @param newState The new view state to combine. 17256 * @return Returns a new integer reflecting the combination of the two 17257 * states. 17258 */ 17259 public static int combineMeasuredStates(int curState, int newState) { 17260 return curState | newState; 17261 } 17262 17263 /** 17264 * Version of {@link #resolveSizeAndState(int, int, int)} 17265 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 17266 */ 17267 public static int resolveSize(int size, int measureSpec) { 17268 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 17269 } 17270 17271 /** 17272 * Utility to reconcile a desired size and state, with constraints imposed 17273 * by a MeasureSpec. Will take the desired size, unless a different size 17274 * is imposed by the constraints. The returned value is a compound integer, 17275 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 17276 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting 17277 * size is smaller than the size the view wants to be. 17278 * 17279 * @param size How big the view wants to be 17280 * @param measureSpec Constraints imposed by the parent 17281 * @return Size information bit mask as defined by 17282 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 17283 */ 17284 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 17285 int result = size; 17286 int specMode = MeasureSpec.getMode(measureSpec); 17287 int specSize = MeasureSpec.getSize(measureSpec); 17288 switch (specMode) { 17289 case MeasureSpec.UNSPECIFIED: 17290 result = size; 17291 break; 17292 case MeasureSpec.AT_MOST: 17293 if (specSize < size) { 17294 result = specSize | MEASURED_STATE_TOO_SMALL; 17295 } else { 17296 result = size; 17297 } 17298 break; 17299 case MeasureSpec.EXACTLY: 17300 result = specSize; 17301 break; 17302 } 17303 return result | (childMeasuredState&MEASURED_STATE_MASK); 17304 } 17305 17306 /** 17307 * Utility to return a default size. Uses the supplied size if the 17308 * MeasureSpec imposed no constraints. Will get larger if allowed 17309 * by the MeasureSpec. 17310 * 17311 * @param size Default size for this view 17312 * @param measureSpec Constraints imposed by the parent 17313 * @return The size this view should be. 17314 */ 17315 public static int getDefaultSize(int size, int measureSpec) { 17316 int result = size; 17317 int specMode = MeasureSpec.getMode(measureSpec); 17318 int specSize = MeasureSpec.getSize(measureSpec); 17319 17320 switch (specMode) { 17321 case MeasureSpec.UNSPECIFIED: 17322 result = size; 17323 break; 17324 case MeasureSpec.AT_MOST: 17325 case MeasureSpec.EXACTLY: 17326 result = specSize; 17327 break; 17328 } 17329 return result; 17330 } 17331 17332 /** 17333 * Returns the suggested minimum height that the view should use. This 17334 * returns the maximum of the view's minimum height 17335 * and the background's minimum height 17336 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 17337 * <p> 17338 * When being used in {@link #onMeasure(int, int)}, the caller should still 17339 * ensure the returned height is within the requirements of the parent. 17340 * 17341 * @return The suggested minimum height of the view. 17342 */ 17343 protected int getSuggestedMinimumHeight() { 17344 return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight()); 17345 17346 } 17347 17348 /** 17349 * Returns the suggested minimum width that the view should use. This 17350 * returns the maximum of the view's minimum width) 17351 * and the background's minimum width 17352 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 17353 * <p> 17354 * When being used in {@link #onMeasure(int, int)}, the caller should still 17355 * ensure the returned width is within the requirements of the parent. 17356 * 17357 * @return The suggested minimum width of the view. 17358 */ 17359 protected int getSuggestedMinimumWidth() { 17360 return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); 17361 } 17362 17363 /** 17364 * Returns the minimum height of the view. 17365 * 17366 * @return the minimum height the view will try to be. 17367 * 17368 * @see #setMinimumHeight(int) 17369 * 17370 * @attr ref android.R.styleable#View_minHeight 17371 */ 17372 public int getMinimumHeight() { 17373 return mMinHeight; 17374 } 17375 17376 /** 17377 * Sets the minimum height of the view. It is not guaranteed the view will 17378 * be able to achieve this minimum height (for example, if its parent layout 17379 * constrains it with less available height). 17380 * 17381 * @param minHeight The minimum height the view will try to be. 17382 * 17383 * @see #getMinimumHeight() 17384 * 17385 * @attr ref android.R.styleable#View_minHeight 17386 */ 17387 public void setMinimumHeight(int minHeight) { 17388 mMinHeight = minHeight; 17389 requestLayout(); 17390 } 17391 17392 /** 17393 * Returns the minimum width of the view. 17394 * 17395 * @return the minimum width the view will try to be. 17396 * 17397 * @see #setMinimumWidth(int) 17398 * 17399 * @attr ref android.R.styleable#View_minWidth 17400 */ 17401 public int getMinimumWidth() { 17402 return mMinWidth; 17403 } 17404 17405 /** 17406 * Sets the minimum width of the view. It is not guaranteed the view will 17407 * be able to achieve this minimum width (for example, if its parent layout 17408 * constrains it with less available width). 17409 * 17410 * @param minWidth The minimum width the view will try to be. 17411 * 17412 * @see #getMinimumWidth() 17413 * 17414 * @attr ref android.R.styleable#View_minWidth 17415 */ 17416 public void setMinimumWidth(int minWidth) { 17417 mMinWidth = minWidth; 17418 requestLayout(); 17419 17420 } 17421 17422 /** 17423 * Get the animation currently associated with this view. 17424 * 17425 * @return The animation that is currently playing or 17426 * scheduled to play for this view. 17427 */ 17428 public Animation getAnimation() { 17429 return mCurrentAnimation; 17430 } 17431 17432 /** 17433 * Start the specified animation now. 17434 * 17435 * @param animation the animation to start now 17436 */ 17437 public void startAnimation(Animation animation) { 17438 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 17439 setAnimation(animation); 17440 invalidateParentCaches(); 17441 invalidate(true); 17442 } 17443 17444 /** 17445 * Cancels any animations for this view. 17446 */ 17447 public void clearAnimation() { 17448 if (mCurrentAnimation != null) { 17449 mCurrentAnimation.detach(); 17450 } 17451 mCurrentAnimation = null; 17452 invalidateParentIfNeeded(); 17453 } 17454 17455 /** 17456 * Sets the next animation to play for this view. 17457 * If you want the animation to play immediately, use 17458 * {@link #startAnimation(android.view.animation.Animation)} instead. 17459 * This method provides allows fine-grained 17460 * control over the start time and invalidation, but you 17461 * must make sure that 1) the animation has a start time set, and 17462 * 2) the view's parent (which controls animations on its children) 17463 * will be invalidated when the animation is supposed to 17464 * start. 17465 * 17466 * @param animation The next animation, or null. 17467 */ 17468 public void setAnimation(Animation animation) { 17469 mCurrentAnimation = animation; 17470 17471 if (animation != null) { 17472 // If the screen is off assume the animation start time is now instead of 17473 // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time 17474 // would cause the animation to start when the screen turns back on 17475 if (mAttachInfo != null && !mAttachInfo.mScreenOn && 17476 animation.getStartTime() == Animation.START_ON_FIRST_FRAME) { 17477 animation.setStartTime(AnimationUtils.currentAnimationTimeMillis()); 17478 } 17479 animation.reset(); 17480 } 17481 } 17482 17483 /** 17484 * Invoked by a parent ViewGroup to notify the start of the animation 17485 * currently associated with this view. If you override this method, 17486 * always call super.onAnimationStart(); 17487 * 17488 * @see #setAnimation(android.view.animation.Animation) 17489 * @see #getAnimation() 17490 */ 17491 protected void onAnimationStart() { 17492 mPrivateFlags |= PFLAG_ANIMATION_STARTED; 17493 } 17494 17495 /** 17496 * Invoked by a parent ViewGroup to notify the end of the animation 17497 * currently associated with this view. If you override this method, 17498 * always call super.onAnimationEnd(); 17499 * 17500 * @see #setAnimation(android.view.animation.Animation) 17501 * @see #getAnimation() 17502 */ 17503 protected void onAnimationEnd() { 17504 mPrivateFlags &= ~PFLAG_ANIMATION_STARTED; 17505 } 17506 17507 /** 17508 * Invoked if there is a Transform that involves alpha. Subclass that can 17509 * draw themselves with the specified alpha should return true, and then 17510 * respect that alpha when their onDraw() is called. If this returns false 17511 * then the view may be redirected to draw into an offscreen buffer to 17512 * fulfill the request, which will look fine, but may be slower than if the 17513 * subclass handles it internally. The default implementation returns false. 17514 * 17515 * @param alpha The alpha (0..255) to apply to the view's drawing 17516 * @return true if the view can draw with the specified alpha. 17517 */ 17518 protected boolean onSetAlpha(int alpha) { 17519 return false; 17520 } 17521 17522 /** 17523 * This is used by the RootView to perform an optimization when 17524 * the view hierarchy contains one or several SurfaceView. 17525 * SurfaceView is always considered transparent, but its children are not, 17526 * therefore all View objects remove themselves from the global transparent 17527 * region (passed as a parameter to this function). 17528 * 17529 * @param region The transparent region for this ViewAncestor (window). 17530 * 17531 * @return Returns true if the effective visibility of the view at this 17532 * point is opaque, regardless of the transparent region; returns false 17533 * if it is possible for underlying windows to be seen behind the view. 17534 * 17535 * {@hide} 17536 */ 17537 public boolean gatherTransparentRegion(Region region) { 17538 final AttachInfo attachInfo = mAttachInfo; 17539 if (region != null && attachInfo != null) { 17540 final int pflags = mPrivateFlags; 17541 if ((pflags & PFLAG_SKIP_DRAW) == 0) { 17542 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 17543 // remove it from the transparent region. 17544 final int[] location = attachInfo.mTransparentLocation; 17545 getLocationInWindow(location); 17546 region.op(location[0], location[1], location[0] + mRight - mLeft, 17547 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 17548 } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) { 17549 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 17550 // exists, so we remove the background drawable's non-transparent 17551 // parts from this transparent region. 17552 applyDrawableToTransparentRegion(mBackground, region); 17553 } 17554 } 17555 return true; 17556 } 17557 17558 /** 17559 * Play a sound effect for this view. 17560 * 17561 * <p>The framework will play sound effects for some built in actions, such as 17562 * clicking, but you may wish to play these effects in your widget, 17563 * for instance, for internal navigation. 17564 * 17565 * <p>The sound effect will only be played if sound effects are enabled by the user, and 17566 * {@link #isSoundEffectsEnabled()} is true. 17567 * 17568 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 17569 */ 17570 public void playSoundEffect(int soundConstant) { 17571 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 17572 return; 17573 } 17574 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 17575 } 17576 17577 /** 17578 * BZZZTT!!1! 17579 * 17580 * <p>Provide haptic feedback to the user for this view. 17581 * 17582 * <p>The framework will provide haptic feedback for some built in actions, 17583 * such as long presses, but you may wish to provide feedback for your 17584 * own widget. 17585 * 17586 * <p>The feedback will only be performed if 17587 * {@link #isHapticFeedbackEnabled()} is true. 17588 * 17589 * @param feedbackConstant One of the constants defined in 17590 * {@link HapticFeedbackConstants} 17591 */ 17592 public boolean performHapticFeedback(int feedbackConstant) { 17593 return performHapticFeedback(feedbackConstant, 0); 17594 } 17595 17596 /** 17597 * BZZZTT!!1! 17598 * 17599 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 17600 * 17601 * @param feedbackConstant One of the constants defined in 17602 * {@link HapticFeedbackConstants} 17603 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 17604 */ 17605 public boolean performHapticFeedback(int feedbackConstant, int flags) { 17606 if (mAttachInfo == null) { 17607 return false; 17608 } 17609 //noinspection SimplifiableIfStatement 17610 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 17611 && !isHapticFeedbackEnabled()) { 17612 return false; 17613 } 17614 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 17615 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 17616 } 17617 17618 /** 17619 * Request that the visibility of the status bar or other screen/window 17620 * decorations be changed. 17621 * 17622 * <p>This method is used to put the over device UI into temporary modes 17623 * where the user's attention is focused more on the application content, 17624 * by dimming or hiding surrounding system affordances. This is typically 17625 * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY 17626 * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content 17627 * to be placed behind the action bar (and with these flags other system 17628 * affordances) so that smooth transitions between hiding and showing them 17629 * can be done. 17630 * 17631 * <p>Two representative examples of the use of system UI visibility is 17632 * implementing a content browsing application (like a magazine reader) 17633 * and a video playing application. 17634 * 17635 * <p>The first code shows a typical implementation of a View in a content 17636 * browsing application. In this implementation, the application goes 17637 * into a content-oriented mode by hiding the status bar and action bar, 17638 * and putting the navigation elements into lights out mode. The user can 17639 * then interact with content while in this mode. Such an application should 17640 * provide an easy way for the user to toggle out of the mode (such as to 17641 * check information in the status bar or access notifications). In the 17642 * implementation here, this is done simply by tapping on the content. 17643 * 17644 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java 17645 * content} 17646 * 17647 * <p>This second code sample shows a typical implementation of a View 17648 * in a video playing application. In this situation, while the video is 17649 * playing the application would like to go into a complete full-screen mode, 17650 * to use as much of the display as possible for the video. When in this state 17651 * the user can not interact with the application; the system intercepts 17652 * touching on the screen to pop the UI out of full screen mode. See 17653 * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code. 17654 * 17655 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java 17656 * content} 17657 * 17658 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 17659 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 17660 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 17661 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 17662 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 17663 */ 17664 public void setSystemUiVisibility(int visibility) { 17665 if (visibility != mSystemUiVisibility) { 17666 mSystemUiVisibility = visibility; 17667 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 17668 mParent.recomputeViewAttributes(this); 17669 } 17670 } 17671 } 17672 17673 /** 17674 * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested. 17675 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 17676 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 17677 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 17678 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 17679 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 17680 */ 17681 public int getSystemUiVisibility() { 17682 return mSystemUiVisibility; 17683 } 17684 17685 /** 17686 * Returns the current system UI visibility that is currently set for 17687 * the entire window. This is the combination of the 17688 * {@link #setSystemUiVisibility(int)} values supplied by all of the 17689 * views in the window. 17690 */ 17691 public int getWindowSystemUiVisibility() { 17692 return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0; 17693 } 17694 17695 /** 17696 * Override to find out when the window's requested system UI visibility 17697 * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}. 17698 * This is different from the callbacks received through 17699 * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)} 17700 * in that this is only telling you about the local request of the window, 17701 * not the actual values applied by the system. 17702 */ 17703 public void onWindowSystemUiVisibilityChanged(int visible) { 17704 } 17705 17706 /** 17707 * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down 17708 * the view hierarchy. 17709 */ 17710 public void dispatchWindowSystemUiVisiblityChanged(int visible) { 17711 onWindowSystemUiVisibilityChanged(visible); 17712 } 17713 17714 /** 17715 * Set a listener to receive callbacks when the visibility of the system bar changes. 17716 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 17717 */ 17718 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 17719 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 17720 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 17721 mParent.recomputeViewAttributes(this); 17722 } 17723 } 17724 17725 /** 17726 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 17727 * the view hierarchy. 17728 */ 17729 public void dispatchSystemUiVisibilityChanged(int visibility) { 17730 ListenerInfo li = mListenerInfo; 17731 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 17732 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 17733 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 17734 } 17735 } 17736 17737 boolean updateLocalSystemUiVisibility(int localValue, int localChanges) { 17738 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 17739 if (val != mSystemUiVisibility) { 17740 setSystemUiVisibility(val); 17741 return true; 17742 } 17743 return false; 17744 } 17745 17746 /** @hide */ 17747 public void setDisabledSystemUiVisibility(int flags) { 17748 if (mAttachInfo != null) { 17749 if (mAttachInfo.mDisabledSystemUiVisibility != flags) { 17750 mAttachInfo.mDisabledSystemUiVisibility = flags; 17751 if (mParent != null) { 17752 mParent.recomputeViewAttributes(this); 17753 } 17754 } 17755 } 17756 } 17757 17758 /** 17759 * Creates an image that the system displays during the drag and drop 17760 * operation. This is called a "drag shadow". The default implementation 17761 * for a DragShadowBuilder based on a View returns an image that has exactly the same 17762 * appearance as the given View. The default also positions the center of the drag shadow 17763 * directly under the touch point. If no View is provided (the constructor with no parameters 17764 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 17765 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the 17766 * default is an invisible drag shadow. 17767 * <p> 17768 * You are not required to use the View you provide to the constructor as the basis of the 17769 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 17770 * anything you want as the drag shadow. 17771 * </p> 17772 * <p> 17773 * You pass a DragShadowBuilder object to the system when you start the drag. The system 17774 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 17775 * size and position of the drag shadow. It uses this data to construct a 17776 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 17777 * so that your application can draw the shadow image in the Canvas. 17778 * </p> 17779 * 17780 * <div class="special reference"> 17781 * <h3>Developer Guides</h3> 17782 * <p>For a guide to implementing drag and drop features, read the 17783 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 17784 * </div> 17785 */ 17786 public static class DragShadowBuilder { 17787 private final WeakReference<View> mView; 17788 17789 /** 17790 * Constructs a shadow image builder based on a View. By default, the resulting drag 17791 * shadow will have the same appearance and dimensions as the View, with the touch point 17792 * over the center of the View. 17793 * @param view A View. Any View in scope can be used. 17794 */ 17795 public DragShadowBuilder(View view) { 17796 mView = new WeakReference<View>(view); 17797 } 17798 17799 /** 17800 * Construct a shadow builder object with no associated View. This 17801 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 17802 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 17803 * to supply the drag shadow's dimensions and appearance without 17804 * reference to any View object. If they are not overridden, then the result is an 17805 * invisible drag shadow. 17806 */ 17807 public DragShadowBuilder() { 17808 mView = new WeakReference<View>(null); 17809 } 17810 17811 /** 17812 * Returns the View object that had been passed to the 17813 * {@link #View.DragShadowBuilder(View)} 17814 * constructor. If that View parameter was {@code null} or if the 17815 * {@link #View.DragShadowBuilder()} 17816 * constructor was used to instantiate the builder object, this method will return 17817 * null. 17818 * 17819 * @return The View object associate with this builder object. 17820 */ 17821 @SuppressWarnings({"JavadocReference"}) 17822 final public View getView() { 17823 return mView.get(); 17824 } 17825 17826 /** 17827 * Provides the metrics for the shadow image. These include the dimensions of 17828 * the shadow image, and the point within that shadow that should 17829 * be centered under the touch location while dragging. 17830 * <p> 17831 * The default implementation sets the dimensions of the shadow to be the 17832 * same as the dimensions of the View itself and centers the shadow under 17833 * the touch point. 17834 * </p> 17835 * 17836 * @param shadowSize A {@link android.graphics.Point} containing the width and height 17837 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 17838 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 17839 * image. 17840 * 17841 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 17842 * shadow image that should be underneath the touch point during the drag and drop 17843 * operation. Your application must set {@link android.graphics.Point#x} to the 17844 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 17845 */ 17846 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 17847 final View view = mView.get(); 17848 if (view != null) { 17849 shadowSize.set(view.getWidth(), view.getHeight()); 17850 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 17851 } else { 17852 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 17853 } 17854 } 17855 17856 /** 17857 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 17858 * based on the dimensions it received from the 17859 * {@link #onProvideShadowMetrics(Point, Point)} callback. 17860 * 17861 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 17862 */ 17863 public void onDrawShadow(Canvas canvas) { 17864 final View view = mView.get(); 17865 if (view != null) { 17866 view.draw(canvas); 17867 } else { 17868 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 17869 } 17870 } 17871 } 17872 17873 /** 17874 * Starts a drag and drop operation. When your application calls this method, it passes a 17875 * {@link android.view.View.DragShadowBuilder} object to the system. The 17876 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 17877 * to get metrics for the drag shadow, and then calls the object's 17878 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 17879 * <p> 17880 * Once the system has the drag shadow, it begins the drag and drop operation by sending 17881 * drag events to all the View objects in your application that are currently visible. It does 17882 * this either by calling the View object's drag listener (an implementation of 17883 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 17884 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 17885 * Both are passed a {@link android.view.DragEvent} object that has a 17886 * {@link android.view.DragEvent#getAction()} value of 17887 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 17888 * </p> 17889 * <p> 17890 * Your application can invoke startDrag() on any attached View object. The View object does not 17891 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to 17892 * be related to the View the user selected for dragging. 17893 * </p> 17894 * @param data A {@link android.content.ClipData} object pointing to the data to be 17895 * transferred by the drag and drop operation. 17896 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 17897 * drag shadow. 17898 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 17899 * drop operation. This Object is put into every DragEvent object sent by the system during the 17900 * current drag. 17901 * <p> 17902 * myLocalState is a lightweight mechanism for the sending information from the dragged View 17903 * to the target Views. For example, it can contain flags that differentiate between a 17904 * a copy operation and a move operation. 17905 * </p> 17906 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 17907 * so the parameter should be set to 0. 17908 * @return {@code true} if the method completes successfully, or 17909 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 17910 * do a drag, and so no drag operation is in progress. 17911 */ 17912 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 17913 Object myLocalState, int flags) { 17914 if (ViewDebug.DEBUG_DRAG) { 17915 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 17916 } 17917 boolean okay = false; 17918 17919 Point shadowSize = new Point(); 17920 Point shadowTouchPoint = new Point(); 17921 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 17922 17923 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 17924 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 17925 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 17926 } 17927 17928 if (ViewDebug.DEBUG_DRAG) { 17929 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 17930 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 17931 } 17932 Surface surface = new Surface(); 17933 try { 17934 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 17935 flags, shadowSize.x, shadowSize.y, surface); 17936 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 17937 + " surface=" + surface); 17938 if (token != null) { 17939 Canvas canvas = surface.lockCanvas(null); 17940 try { 17941 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 17942 shadowBuilder.onDrawShadow(canvas); 17943 } finally { 17944 surface.unlockCanvasAndPost(canvas); 17945 } 17946 17947 final ViewRootImpl root = getViewRootImpl(); 17948 17949 // Cache the local state object for delivery with DragEvents 17950 root.setLocalDragState(myLocalState); 17951 17952 // repurpose 'shadowSize' for the last touch point 17953 root.getLastTouchPoint(shadowSize); 17954 17955 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 17956 shadowSize.x, shadowSize.y, 17957 shadowTouchPoint.x, shadowTouchPoint.y, data); 17958 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 17959 17960 // Off and running! Release our local surface instance; the drag 17961 // shadow surface is now managed by the system process. 17962 surface.release(); 17963 } 17964 } catch (Exception e) { 17965 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 17966 surface.destroy(); 17967 } 17968 17969 return okay; 17970 } 17971 17972 /** 17973 * Handles drag events sent by the system following a call to 17974 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}. 17975 *<p> 17976 * When the system calls this method, it passes a 17977 * {@link android.view.DragEvent} object. A call to 17978 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 17979 * in DragEvent. The method uses these to determine what is happening in the drag and drop 17980 * operation. 17981 * @param event The {@link android.view.DragEvent} sent by the system. 17982 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 17983 * in DragEvent, indicating the type of drag event represented by this object. 17984 * @return {@code true} if the method was successful, otherwise {@code false}. 17985 * <p> 17986 * The method should return {@code true} in response to an action type of 17987 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 17988 * operation. 17989 * </p> 17990 * <p> 17991 * The method should also return {@code true} in response to an action type of 17992 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 17993 * {@code false} if it didn't. 17994 * </p> 17995 */ 17996 public boolean onDragEvent(DragEvent event) { 17997 return false; 17998 } 17999 18000 /** 18001 * Detects if this View is enabled and has a drag event listener. 18002 * If both are true, then it calls the drag event listener with the 18003 * {@link android.view.DragEvent} it received. If the drag event listener returns 18004 * {@code true}, then dispatchDragEvent() returns {@code true}. 18005 * <p> 18006 * For all other cases, the method calls the 18007 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 18008 * method and returns its result. 18009 * </p> 18010 * <p> 18011 * This ensures that a drag event is always consumed, even if the View does not have a drag 18012 * event listener. However, if the View has a listener and the listener returns true, then 18013 * onDragEvent() is not called. 18014 * </p> 18015 */ 18016 public boolean dispatchDragEvent(DragEvent event) { 18017 ListenerInfo li = mListenerInfo; 18018 //noinspection SimplifiableIfStatement 18019 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 18020 && li.mOnDragListener.onDrag(this, event)) { 18021 return true; 18022 } 18023 return onDragEvent(event); 18024 } 18025 18026 boolean canAcceptDrag() { 18027 return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0; 18028 } 18029 18030 /** 18031 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 18032 * it is ever exposed at all. 18033 * @hide 18034 */ 18035 public void onCloseSystemDialogs(String reason) { 18036 } 18037 18038 /** 18039 * Given a Drawable whose bounds have been set to draw into this view, 18040 * update a Region being computed for 18041 * {@link #gatherTransparentRegion(android.graphics.Region)} so 18042 * that any non-transparent parts of the Drawable are removed from the 18043 * given transparent region. 18044 * 18045 * @param dr The Drawable whose transparency is to be applied to the region. 18046 * @param region A Region holding the current transparency information, 18047 * where any parts of the region that are set are considered to be 18048 * transparent. On return, this region will be modified to have the 18049 * transparency information reduced by the corresponding parts of the 18050 * Drawable that are not transparent. 18051 * {@hide} 18052 */ 18053 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 18054 if (DBG) { 18055 Log.i("View", "Getting transparent region for: " + this); 18056 } 18057 final Region r = dr.getTransparentRegion(); 18058 final Rect db = dr.getBounds(); 18059 final AttachInfo attachInfo = mAttachInfo; 18060 if (r != null && attachInfo != null) { 18061 final int w = getRight()-getLeft(); 18062 final int h = getBottom()-getTop(); 18063 if (db.left > 0) { 18064 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 18065 r.op(0, 0, db.left, h, Region.Op.UNION); 18066 } 18067 if (db.right < w) { 18068 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 18069 r.op(db.right, 0, w, h, Region.Op.UNION); 18070 } 18071 if (db.top > 0) { 18072 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 18073 r.op(0, 0, w, db.top, Region.Op.UNION); 18074 } 18075 if (db.bottom < h) { 18076 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 18077 r.op(0, db.bottom, w, h, Region.Op.UNION); 18078 } 18079 final int[] location = attachInfo.mTransparentLocation; 18080 getLocationInWindow(location); 18081 r.translate(location[0], location[1]); 18082 region.op(r, Region.Op.INTERSECT); 18083 } else { 18084 region.op(db, Region.Op.DIFFERENCE); 18085 } 18086 } 18087 18088 private void checkForLongClick(int delayOffset) { 18089 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 18090 mHasPerformedLongPress = false; 18091 18092 if (mPendingCheckForLongPress == null) { 18093 mPendingCheckForLongPress = new CheckForLongPress(); 18094 } 18095 mPendingCheckForLongPress.rememberWindowAttachCount(); 18096 postDelayed(mPendingCheckForLongPress, 18097 ViewConfiguration.getLongPressTimeout() - delayOffset); 18098 } 18099 } 18100 18101 /** 18102 * Inflate a view from an XML resource. This convenience method wraps the {@link 18103 * LayoutInflater} class, which provides a full range of options for view inflation. 18104 * 18105 * @param context The Context object for your activity or application. 18106 * @param resource The resource ID to inflate 18107 * @param root A view group that will be the parent. Used to properly inflate the 18108 * layout_* parameters. 18109 * @see LayoutInflater 18110 */ 18111 public static View inflate(Context context, int resource, ViewGroup root) { 18112 LayoutInflater factory = LayoutInflater.from(context); 18113 return factory.inflate(resource, root); 18114 } 18115 18116 /** 18117 * Scroll the view with standard behavior for scrolling beyond the normal 18118 * content boundaries. Views that call this method should override 18119 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 18120 * results of an over-scroll operation. 18121 * 18122 * Views can use this method to handle any touch or fling-based scrolling. 18123 * 18124 * @param deltaX Change in X in pixels 18125 * @param deltaY Change in Y in pixels 18126 * @param scrollX Current X scroll value in pixels before applying deltaX 18127 * @param scrollY Current Y scroll value in pixels before applying deltaY 18128 * @param scrollRangeX Maximum content scroll range along the X axis 18129 * @param scrollRangeY Maximum content scroll range along the Y axis 18130 * @param maxOverScrollX Number of pixels to overscroll by in either direction 18131 * along the X axis. 18132 * @param maxOverScrollY Number of pixels to overscroll by in either direction 18133 * along the Y axis. 18134 * @param isTouchEvent true if this scroll operation is the result of a touch event. 18135 * @return true if scrolling was clamped to an over-scroll boundary along either 18136 * axis, false otherwise. 18137 */ 18138 @SuppressWarnings({"UnusedParameters"}) 18139 protected boolean overScrollBy(int deltaX, int deltaY, 18140 int scrollX, int scrollY, 18141 int scrollRangeX, int scrollRangeY, 18142 int maxOverScrollX, int maxOverScrollY, 18143 boolean isTouchEvent) { 18144 final int overScrollMode = mOverScrollMode; 18145 final boolean canScrollHorizontal = 18146 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 18147 final boolean canScrollVertical = 18148 computeVerticalScrollRange() > computeVerticalScrollExtent(); 18149 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 18150 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 18151 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 18152 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 18153 18154 int newScrollX = scrollX + deltaX; 18155 if (!overScrollHorizontal) { 18156 maxOverScrollX = 0; 18157 } 18158 18159 int newScrollY = scrollY + deltaY; 18160 if (!overScrollVertical) { 18161 maxOverScrollY = 0; 18162 } 18163 18164 // Clamp values if at the limits and record 18165 final int left = -maxOverScrollX; 18166 final int right = maxOverScrollX + scrollRangeX; 18167 final int top = -maxOverScrollY; 18168 final int bottom = maxOverScrollY + scrollRangeY; 18169 18170 boolean clampedX = false; 18171 if (newScrollX > right) { 18172 newScrollX = right; 18173 clampedX = true; 18174 } else if (newScrollX < left) { 18175 newScrollX = left; 18176 clampedX = true; 18177 } 18178 18179 boolean clampedY = false; 18180 if (newScrollY > bottom) { 18181 newScrollY = bottom; 18182 clampedY = true; 18183 } else if (newScrollY < top) { 18184 newScrollY = top; 18185 clampedY = true; 18186 } 18187 18188 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 18189 18190 return clampedX || clampedY; 18191 } 18192 18193 /** 18194 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 18195 * respond to the results of an over-scroll operation. 18196 * 18197 * @param scrollX New X scroll value in pixels 18198 * @param scrollY New Y scroll value in pixels 18199 * @param clampedX True if scrollX was clamped to an over-scroll boundary 18200 * @param clampedY True if scrollY was clamped to an over-scroll boundary 18201 */ 18202 protected void onOverScrolled(int scrollX, int scrollY, 18203 boolean clampedX, boolean clampedY) { 18204 // Intentionally empty. 18205 } 18206 18207 /** 18208 * Returns the over-scroll mode for this view. The result will be 18209 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 18210 * (allow over-scrolling only if the view content is larger than the container), 18211 * or {@link #OVER_SCROLL_NEVER}. 18212 * 18213 * @return This view's over-scroll mode. 18214 */ 18215 public int getOverScrollMode() { 18216 return mOverScrollMode; 18217 } 18218 18219 /** 18220 * Set the over-scroll mode for this view. Valid over-scroll modes are 18221 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 18222 * (allow over-scrolling only if the view content is larger than the container), 18223 * or {@link #OVER_SCROLL_NEVER}. 18224 * 18225 * Setting the over-scroll mode of a view will have an effect only if the 18226 * view is capable of scrolling. 18227 * 18228 * @param overScrollMode The new over-scroll mode for this view. 18229 */ 18230 public void setOverScrollMode(int overScrollMode) { 18231 if (overScrollMode != OVER_SCROLL_ALWAYS && 18232 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 18233 overScrollMode != OVER_SCROLL_NEVER) { 18234 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 18235 } 18236 mOverScrollMode = overScrollMode; 18237 } 18238 18239 /** 18240 * Gets a scale factor that determines the distance the view should scroll 18241 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 18242 * @return The vertical scroll scale factor. 18243 * @hide 18244 */ 18245 protected float getVerticalScrollFactor() { 18246 if (mVerticalScrollFactor == 0) { 18247 TypedValue outValue = new TypedValue(); 18248 if (!mContext.getTheme().resolveAttribute( 18249 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 18250 throw new IllegalStateException( 18251 "Expected theme to define listPreferredItemHeight."); 18252 } 18253 mVerticalScrollFactor = outValue.getDimension( 18254 mContext.getResources().getDisplayMetrics()); 18255 } 18256 return mVerticalScrollFactor; 18257 } 18258 18259 /** 18260 * Gets a scale factor that determines the distance the view should scroll 18261 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 18262 * @return The horizontal scroll scale factor. 18263 * @hide 18264 */ 18265 protected float getHorizontalScrollFactor() { 18266 // TODO: Should use something else. 18267 return getVerticalScrollFactor(); 18268 } 18269 18270 /** 18271 * Return the value specifying the text direction or policy that was set with 18272 * {@link #setTextDirection(int)}. 18273 * 18274 * @return the defined text direction. It can be one of: 18275 * 18276 * {@link #TEXT_DIRECTION_INHERIT}, 18277 * {@link #TEXT_DIRECTION_FIRST_STRONG} 18278 * {@link #TEXT_DIRECTION_ANY_RTL}, 18279 * {@link #TEXT_DIRECTION_LTR}, 18280 * {@link #TEXT_DIRECTION_RTL}, 18281 * {@link #TEXT_DIRECTION_LOCALE} 18282 * 18283 * @attr ref android.R.styleable#View_textDirection 18284 * 18285 * @hide 18286 */ 18287 @ViewDebug.ExportedProperty(category = "text", mapping = { 18288 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 18289 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 18290 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 18291 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 18292 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 18293 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 18294 }) 18295 public int getRawTextDirection() { 18296 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 18297 } 18298 18299 /** 18300 * Set the text direction. 18301 * 18302 * @param textDirection the direction to set. Should be one of: 18303 * 18304 * {@link #TEXT_DIRECTION_INHERIT}, 18305 * {@link #TEXT_DIRECTION_FIRST_STRONG} 18306 * {@link #TEXT_DIRECTION_ANY_RTL}, 18307 * {@link #TEXT_DIRECTION_LTR}, 18308 * {@link #TEXT_DIRECTION_RTL}, 18309 * {@link #TEXT_DIRECTION_LOCALE} 18310 * 18311 * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution 18312 * proceeds up the parent chain of the view to get the value. If there is no parent, then it will 18313 * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}. 18314 * 18315 * @attr ref android.R.styleable#View_textDirection 18316 */ 18317 public void setTextDirection(int textDirection) { 18318 if (getRawTextDirection() != textDirection) { 18319 // Reset the current text direction and the resolved one 18320 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 18321 resetResolvedTextDirection(); 18322 // Set the new text direction 18323 mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK); 18324 // Do resolution 18325 resolveTextDirection(); 18326 // Notify change 18327 onRtlPropertiesChanged(getLayoutDirection()); 18328 // Refresh 18329 requestLayout(); 18330 invalidate(true); 18331 } 18332 } 18333 18334 /** 18335 * Return the resolved text direction. 18336 * 18337 * @return the resolved text direction. Returns one of: 18338 * 18339 * {@link #TEXT_DIRECTION_FIRST_STRONG} 18340 * {@link #TEXT_DIRECTION_ANY_RTL}, 18341 * {@link #TEXT_DIRECTION_LTR}, 18342 * {@link #TEXT_DIRECTION_RTL}, 18343 * {@link #TEXT_DIRECTION_LOCALE} 18344 * 18345 * @attr ref android.R.styleable#View_textDirection 18346 */ 18347 @ViewDebug.ExportedProperty(category = "text", mapping = { 18348 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 18349 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 18350 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 18351 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 18352 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 18353 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 18354 }) 18355 public int getTextDirection() { 18356 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 18357 } 18358 18359 /** 18360 * Resolve the text direction. 18361 * 18362 * @return true if resolution has been done, false otherwise. 18363 * 18364 * @hide 18365 */ 18366 public boolean resolveTextDirection() { 18367 // Reset any previous text direction resolution 18368 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 18369 18370 if (hasRtlSupport()) { 18371 // Set resolved text direction flag depending on text direction flag 18372 final int textDirection = getRawTextDirection(); 18373 switch(textDirection) { 18374 case TEXT_DIRECTION_INHERIT: 18375 if (!canResolveTextDirection()) { 18376 // We cannot do the resolution if there is no parent, so use the default one 18377 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18378 // Resolution will need to happen again later 18379 return false; 18380 } 18381 18382 // Parent has not yet resolved, so we still return the default 18383 try { 18384 if (!mParent.isTextDirectionResolved()) { 18385 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18386 // Resolution will need to happen again later 18387 return false; 18388 } 18389 } catch (AbstractMethodError e) { 18390 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18391 " does not fully implement ViewParent", e); 18392 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED | 18393 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18394 return true; 18395 } 18396 18397 // Set current resolved direction to the same value as the parent's one 18398 int parentResolvedDirection; 18399 try { 18400 parentResolvedDirection = mParent.getTextDirection(); 18401 } catch (AbstractMethodError e) { 18402 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18403 " does not fully implement ViewParent", e); 18404 parentResolvedDirection = TEXT_DIRECTION_LTR; 18405 } 18406 switch (parentResolvedDirection) { 18407 case TEXT_DIRECTION_FIRST_STRONG: 18408 case TEXT_DIRECTION_ANY_RTL: 18409 case TEXT_DIRECTION_LTR: 18410 case TEXT_DIRECTION_RTL: 18411 case TEXT_DIRECTION_LOCALE: 18412 mPrivateFlags2 |= 18413 (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 18414 break; 18415 default: 18416 // Default resolved direction is "first strong" heuristic 18417 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18418 } 18419 break; 18420 case TEXT_DIRECTION_FIRST_STRONG: 18421 case TEXT_DIRECTION_ANY_RTL: 18422 case TEXT_DIRECTION_LTR: 18423 case TEXT_DIRECTION_RTL: 18424 case TEXT_DIRECTION_LOCALE: 18425 // Resolved direction is the same as text direction 18426 mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 18427 break; 18428 default: 18429 // Default resolved direction is "first strong" heuristic 18430 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18431 } 18432 } else { 18433 // Default resolved direction is "first strong" heuristic 18434 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18435 } 18436 18437 // Set to resolved 18438 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED; 18439 return true; 18440 } 18441 18442 /** 18443 * Check if text direction resolution can be done. 18444 * 18445 * @return true if text direction resolution can be done otherwise return false. 18446 */ 18447 public boolean canResolveTextDirection() { 18448 switch (getRawTextDirection()) { 18449 case TEXT_DIRECTION_INHERIT: 18450 if (mParent != null) { 18451 try { 18452 return mParent.canResolveTextDirection(); 18453 } catch (AbstractMethodError e) { 18454 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18455 " does not fully implement ViewParent", e); 18456 } 18457 } 18458 return false; 18459 18460 default: 18461 return true; 18462 } 18463 } 18464 18465 /** 18466 * Reset resolved text direction. Text direction will be resolved during a call to 18467 * {@link #onMeasure(int, int)}. 18468 * 18469 * @hide 18470 */ 18471 public void resetResolvedTextDirection() { 18472 // Reset any previous text direction resolution 18473 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 18474 // Set to default value 18475 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18476 } 18477 18478 /** 18479 * @return true if text direction is inherited. 18480 * 18481 * @hide 18482 */ 18483 public boolean isTextDirectionInherited() { 18484 return (getRawTextDirection() == TEXT_DIRECTION_INHERIT); 18485 } 18486 18487 /** 18488 * @return true if text direction is resolved. 18489 */ 18490 public boolean isTextDirectionResolved() { 18491 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED; 18492 } 18493 18494 /** 18495 * Return the value specifying the text alignment or policy that was set with 18496 * {@link #setTextAlignment(int)}. 18497 * 18498 * @return the defined text alignment. It can be one of: 18499 * 18500 * {@link #TEXT_ALIGNMENT_INHERIT}, 18501 * {@link #TEXT_ALIGNMENT_GRAVITY}, 18502 * {@link #TEXT_ALIGNMENT_CENTER}, 18503 * {@link #TEXT_ALIGNMENT_TEXT_START}, 18504 * {@link #TEXT_ALIGNMENT_TEXT_END}, 18505 * {@link #TEXT_ALIGNMENT_VIEW_START}, 18506 * {@link #TEXT_ALIGNMENT_VIEW_END} 18507 * 18508 * @attr ref android.R.styleable#View_textAlignment 18509 * 18510 * @hide 18511 */ 18512 @ViewDebug.ExportedProperty(category = "text", mapping = { 18513 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 18514 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 18515 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 18516 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 18517 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 18518 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 18519 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 18520 }) 18521 @TextAlignment 18522 public int getRawTextAlignment() { 18523 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 18524 } 18525 18526 /** 18527 * Set the text alignment. 18528 * 18529 * @param textAlignment The text alignment to set. Should be one of 18530 * 18531 * {@link #TEXT_ALIGNMENT_INHERIT}, 18532 * {@link #TEXT_ALIGNMENT_GRAVITY}, 18533 * {@link #TEXT_ALIGNMENT_CENTER}, 18534 * {@link #TEXT_ALIGNMENT_TEXT_START}, 18535 * {@link #TEXT_ALIGNMENT_TEXT_END}, 18536 * {@link #TEXT_ALIGNMENT_VIEW_START}, 18537 * {@link #TEXT_ALIGNMENT_VIEW_END} 18538 * 18539 * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution 18540 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 18541 * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}. 18542 * 18543 * @attr ref android.R.styleable#View_textAlignment 18544 */ 18545 public void setTextAlignment(@TextAlignment int textAlignment) { 18546 if (textAlignment != getRawTextAlignment()) { 18547 // Reset the current and resolved text alignment 18548 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 18549 resetResolvedTextAlignment(); 18550 // Set the new text alignment 18551 mPrivateFlags2 |= 18552 ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK); 18553 // Do resolution 18554 resolveTextAlignment(); 18555 // Notify change 18556 onRtlPropertiesChanged(getLayoutDirection()); 18557 // Refresh 18558 requestLayout(); 18559 invalidate(true); 18560 } 18561 } 18562 18563 /** 18564 * Return the resolved text alignment. 18565 * 18566 * @return the resolved text alignment. Returns one of: 18567 * 18568 * {@link #TEXT_ALIGNMENT_GRAVITY}, 18569 * {@link #TEXT_ALIGNMENT_CENTER}, 18570 * {@link #TEXT_ALIGNMENT_TEXT_START}, 18571 * {@link #TEXT_ALIGNMENT_TEXT_END}, 18572 * {@link #TEXT_ALIGNMENT_VIEW_START}, 18573 * {@link #TEXT_ALIGNMENT_VIEW_END} 18574 * 18575 * @attr ref android.R.styleable#View_textAlignment 18576 */ 18577 @ViewDebug.ExportedProperty(category = "text", mapping = { 18578 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 18579 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 18580 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 18581 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 18582 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 18583 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 18584 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 18585 }) 18586 @TextAlignment 18587 public int getTextAlignment() { 18588 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >> 18589 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 18590 } 18591 18592 /** 18593 * Resolve the text alignment. 18594 * 18595 * @return true if resolution has been done, false otherwise. 18596 * 18597 * @hide 18598 */ 18599 public boolean resolveTextAlignment() { 18600 // Reset any previous text alignment resolution 18601 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 18602 18603 if (hasRtlSupport()) { 18604 // Set resolved text alignment flag depending on text alignment flag 18605 final int textAlignment = getRawTextAlignment(); 18606 switch (textAlignment) { 18607 case TEXT_ALIGNMENT_INHERIT: 18608 // Check if we can resolve the text alignment 18609 if (!canResolveTextAlignment()) { 18610 // We cannot do the resolution if there is no parent so use the default 18611 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18612 // Resolution will need to happen again later 18613 return false; 18614 } 18615 18616 // Parent has not yet resolved, so we still return the default 18617 try { 18618 if (!mParent.isTextAlignmentResolved()) { 18619 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18620 // Resolution will need to happen again later 18621 return false; 18622 } 18623 } catch (AbstractMethodError e) { 18624 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18625 " does not fully implement ViewParent", e); 18626 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED | 18627 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18628 return true; 18629 } 18630 18631 int parentResolvedTextAlignment; 18632 try { 18633 parentResolvedTextAlignment = mParent.getTextAlignment(); 18634 } catch (AbstractMethodError e) { 18635 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18636 " does not fully implement ViewParent", e); 18637 parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY; 18638 } 18639 switch (parentResolvedTextAlignment) { 18640 case TEXT_ALIGNMENT_GRAVITY: 18641 case TEXT_ALIGNMENT_TEXT_START: 18642 case TEXT_ALIGNMENT_TEXT_END: 18643 case TEXT_ALIGNMENT_CENTER: 18644 case TEXT_ALIGNMENT_VIEW_START: 18645 case TEXT_ALIGNMENT_VIEW_END: 18646 // Resolved text alignment is the same as the parent resolved 18647 // text alignment 18648 mPrivateFlags2 |= 18649 (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 18650 break; 18651 default: 18652 // Use default resolved text alignment 18653 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18654 } 18655 break; 18656 case TEXT_ALIGNMENT_GRAVITY: 18657 case TEXT_ALIGNMENT_TEXT_START: 18658 case TEXT_ALIGNMENT_TEXT_END: 18659 case TEXT_ALIGNMENT_CENTER: 18660 case TEXT_ALIGNMENT_VIEW_START: 18661 case TEXT_ALIGNMENT_VIEW_END: 18662 // Resolved text alignment is the same as text alignment 18663 mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 18664 break; 18665 default: 18666 // Use default resolved text alignment 18667 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18668 } 18669 } else { 18670 // Use default resolved text alignment 18671 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18672 } 18673 18674 // Set the resolved 18675 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED; 18676 return true; 18677 } 18678 18679 /** 18680 * Check if text alignment resolution can be done. 18681 * 18682 * @return true if text alignment resolution can be done otherwise return false. 18683 */ 18684 public boolean canResolveTextAlignment() { 18685 switch (getRawTextAlignment()) { 18686 case TEXT_DIRECTION_INHERIT: 18687 if (mParent != null) { 18688 try { 18689 return mParent.canResolveTextAlignment(); 18690 } catch (AbstractMethodError e) { 18691 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18692 " does not fully implement ViewParent", e); 18693 } 18694 } 18695 return false; 18696 18697 default: 18698 return true; 18699 } 18700 } 18701 18702 /** 18703 * Reset resolved text alignment. Text alignment will be resolved during a call to 18704 * {@link #onMeasure(int, int)}. 18705 * 18706 * @hide 18707 */ 18708 public void resetResolvedTextAlignment() { 18709 // Reset any previous text alignment resolution 18710 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 18711 // Set to default 18712 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18713 } 18714 18715 /** 18716 * @return true if text alignment is inherited. 18717 * 18718 * @hide 18719 */ 18720 public boolean isTextAlignmentInherited() { 18721 return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT); 18722 } 18723 18724 /** 18725 * @return true if text alignment is resolved. 18726 */ 18727 public boolean isTextAlignmentResolved() { 18728 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED; 18729 } 18730 18731 /** 18732 * Generate a value suitable for use in {@link #setId(int)}. 18733 * This value will not collide with ID values generated at build time by aapt for R.id. 18734 * 18735 * @return a generated ID value 18736 */ 18737 public static int generateViewId() { 18738 for (;;) { 18739 final int result = sNextGeneratedId.get(); 18740 // aapt-generated IDs have the high byte nonzero; clamp to the range under that. 18741 int newValue = result + 1; 18742 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. 18743 if (sNextGeneratedId.compareAndSet(result, newValue)) { 18744 return result; 18745 } 18746 } 18747 } 18748 18749 /** 18750 * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions. 18751 * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and 18752 * a normal View or a ViewGroup with 18753 * {@link android.view.ViewGroup#isTransitionGroup()} true. 18754 * @hide 18755 */ 18756 public void captureTransitioningViews(List<View> transitioningViews) { 18757 if (getVisibility() == View.VISIBLE) { 18758 transitioningViews.add(this); 18759 } 18760 } 18761 18762 /** 18763 * Adds all Views that have {@link #getSharedElementName()} non-null to sharedElements. 18764 * @param sharedElements Will contain all Views in the hierarchy having a shared element name. 18765 * @hide 18766 */ 18767 public void findSharedElements(Map<String, View> sharedElements) { 18768 if (getVisibility() == VISIBLE) { 18769 String sharedElementName = getSharedElementName(); 18770 if (sharedElementName != null) { 18771 sharedElements.put(sharedElementName, this); 18772 } 18773 } 18774 } 18775 18776 // 18777 // Properties 18778 // 18779 /** 18780 * A Property wrapper around the <code>alpha</code> functionality handled by the 18781 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 18782 */ 18783 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 18784 @Override 18785 public void setValue(View object, float value) { 18786 object.setAlpha(value); 18787 } 18788 18789 @Override 18790 public Float get(View object) { 18791 return object.getAlpha(); 18792 } 18793 }; 18794 18795 /** 18796 * A Property wrapper around the <code>translationX</code> functionality handled by the 18797 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 18798 */ 18799 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 18800 @Override 18801 public void setValue(View object, float value) { 18802 object.setTranslationX(value); 18803 } 18804 18805 @Override 18806 public Float get(View object) { 18807 return object.getTranslationX(); 18808 } 18809 }; 18810 18811 /** 18812 * A Property wrapper around the <code>translationY</code> functionality handled by the 18813 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 18814 */ 18815 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 18816 @Override 18817 public void setValue(View object, float value) { 18818 object.setTranslationY(value); 18819 } 18820 18821 @Override 18822 public Float get(View object) { 18823 return object.getTranslationY(); 18824 } 18825 }; 18826 18827 /** 18828 * A Property wrapper around the <code>translationZ</code> functionality handled by the 18829 * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods. 18830 */ 18831 public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") { 18832 @Override 18833 public void setValue(View object, float value) { 18834 object.setTranslationZ(value); 18835 } 18836 18837 @Override 18838 public Float get(View object) { 18839 return object.getTranslationZ(); 18840 } 18841 }; 18842 18843 /** 18844 * A Property wrapper around the <code>x</code> functionality handled by the 18845 * {@link View#setX(float)} and {@link View#getX()} methods. 18846 */ 18847 public static final Property<View, Float> X = new FloatProperty<View>("x") { 18848 @Override 18849 public void setValue(View object, float value) { 18850 object.setX(value); 18851 } 18852 18853 @Override 18854 public Float get(View object) { 18855 return object.getX(); 18856 } 18857 }; 18858 18859 /** 18860 * A Property wrapper around the <code>y</code> functionality handled by the 18861 * {@link View#setY(float)} and {@link View#getY()} methods. 18862 */ 18863 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 18864 @Override 18865 public void setValue(View object, float value) { 18866 object.setY(value); 18867 } 18868 18869 @Override 18870 public Float get(View object) { 18871 return object.getY(); 18872 } 18873 }; 18874 18875 /** 18876 * A Property wrapper around the <code>rotation</code> functionality handled by the 18877 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 18878 */ 18879 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 18880 @Override 18881 public void setValue(View object, float value) { 18882 object.setRotation(value); 18883 } 18884 18885 @Override 18886 public Float get(View object) { 18887 return object.getRotation(); 18888 } 18889 }; 18890 18891 /** 18892 * A Property wrapper around the <code>rotationX</code> functionality handled by the 18893 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 18894 */ 18895 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 18896 @Override 18897 public void setValue(View object, float value) { 18898 object.setRotationX(value); 18899 } 18900 18901 @Override 18902 public Float get(View object) { 18903 return object.getRotationX(); 18904 } 18905 }; 18906 18907 /** 18908 * A Property wrapper around the <code>rotationY</code> functionality handled by the 18909 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 18910 */ 18911 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 18912 @Override 18913 public void setValue(View object, float value) { 18914 object.setRotationY(value); 18915 } 18916 18917 @Override 18918 public Float get(View object) { 18919 return object.getRotationY(); 18920 } 18921 }; 18922 18923 /** 18924 * A Property wrapper around the <code>scaleX</code> functionality handled by the 18925 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 18926 */ 18927 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 18928 @Override 18929 public void setValue(View object, float value) { 18930 object.setScaleX(value); 18931 } 18932 18933 @Override 18934 public Float get(View object) { 18935 return object.getScaleX(); 18936 } 18937 }; 18938 18939 /** 18940 * A Property wrapper around the <code>scaleY</code> functionality handled by the 18941 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 18942 */ 18943 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 18944 @Override 18945 public void setValue(View object, float value) { 18946 object.setScaleY(value); 18947 } 18948 18949 @Override 18950 public Float get(View object) { 18951 return object.getScaleY(); 18952 } 18953 }; 18954 18955 /** 18956 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 18957 * Each MeasureSpec represents a requirement for either the width or the height. 18958 * A MeasureSpec is comprised of a size and a mode. There are three possible 18959 * modes: 18960 * <dl> 18961 * <dt>UNSPECIFIED</dt> 18962 * <dd> 18963 * The parent has not imposed any constraint on the child. It can be whatever size 18964 * it wants. 18965 * </dd> 18966 * 18967 * <dt>EXACTLY</dt> 18968 * <dd> 18969 * The parent has determined an exact size for the child. The child is going to be 18970 * given those bounds regardless of how big it wants to be. 18971 * </dd> 18972 * 18973 * <dt>AT_MOST</dt> 18974 * <dd> 18975 * The child can be as large as it wants up to the specified size. 18976 * </dd> 18977 * </dl> 18978 * 18979 * MeasureSpecs are implemented as ints to reduce object allocation. This class 18980 * is provided to pack and unpack the <size, mode> tuple into the int. 18981 */ 18982 public static class MeasureSpec { 18983 private static final int MODE_SHIFT = 30; 18984 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 18985 18986 /** 18987 * Measure specification mode: The parent has not imposed any constraint 18988 * on the child. It can be whatever size it wants. 18989 */ 18990 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 18991 18992 /** 18993 * Measure specification mode: The parent has determined an exact size 18994 * for the child. The child is going to be given those bounds regardless 18995 * of how big it wants to be. 18996 */ 18997 public static final int EXACTLY = 1 << MODE_SHIFT; 18998 18999 /** 19000 * Measure specification mode: The child can be as large as it wants up 19001 * to the specified size. 19002 */ 19003 public static final int AT_MOST = 2 << MODE_SHIFT; 19004 19005 /** 19006 * Creates a measure specification based on the supplied size and mode. 19007 * 19008 * The mode must always be one of the following: 19009 * <ul> 19010 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 19011 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 19012 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 19013 * </ul> 19014 * 19015 * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's 19016 * implementation was such that the order of arguments did not matter 19017 * and overflow in either value could impact the resulting MeasureSpec. 19018 * {@link android.widget.RelativeLayout} was affected by this bug. 19019 * Apps targeting API levels greater than 17 will get the fixed, more strict 19020 * behavior.</p> 19021 * 19022 * @param size the size of the measure specification 19023 * @param mode the mode of the measure specification 19024 * @return the measure specification based on size and mode 19025 */ 19026 public static int makeMeasureSpec(int size, int mode) { 19027 if (sUseBrokenMakeMeasureSpec) { 19028 return size + mode; 19029 } else { 19030 return (size & ~MODE_MASK) | (mode & MODE_MASK); 19031 } 19032 } 19033 19034 /** 19035 * Extracts the mode from the supplied measure specification. 19036 * 19037 * @param measureSpec the measure specification to extract the mode from 19038 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 19039 * {@link android.view.View.MeasureSpec#AT_MOST} or 19040 * {@link android.view.View.MeasureSpec#EXACTLY} 19041 */ 19042 public static int getMode(int measureSpec) { 19043 return (measureSpec & MODE_MASK); 19044 } 19045 19046 /** 19047 * Extracts the size from the supplied measure specification. 19048 * 19049 * @param measureSpec the measure specification to extract the size from 19050 * @return the size in pixels defined in the supplied measure specification 19051 */ 19052 public static int getSize(int measureSpec) { 19053 return (measureSpec & ~MODE_MASK); 19054 } 19055 19056 static int adjust(int measureSpec, int delta) { 19057 final int mode = getMode(measureSpec); 19058 if (mode == UNSPECIFIED) { 19059 // No need to adjust size for UNSPECIFIED mode. 19060 return makeMeasureSpec(0, UNSPECIFIED); 19061 } 19062 int size = getSize(measureSpec) + delta; 19063 if (size < 0) { 19064 Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size + 19065 ") spec: " + toString(measureSpec) + " delta: " + delta); 19066 size = 0; 19067 } 19068 return makeMeasureSpec(size, mode); 19069 } 19070 19071 /** 19072 * Returns a String representation of the specified measure 19073 * specification. 19074 * 19075 * @param measureSpec the measure specification to convert to a String 19076 * @return a String with the following format: "MeasureSpec: MODE SIZE" 19077 */ 19078 public static String toString(int measureSpec) { 19079 int mode = getMode(measureSpec); 19080 int size = getSize(measureSpec); 19081 19082 StringBuilder sb = new StringBuilder("MeasureSpec: "); 19083 19084 if (mode == UNSPECIFIED) 19085 sb.append("UNSPECIFIED "); 19086 else if (mode == EXACTLY) 19087 sb.append("EXACTLY "); 19088 else if (mode == AT_MOST) 19089 sb.append("AT_MOST "); 19090 else 19091 sb.append(mode).append(" "); 19092 19093 sb.append(size); 19094 return sb.toString(); 19095 } 19096 } 19097 19098 private final class CheckForLongPress implements Runnable { 19099 private int mOriginalWindowAttachCount; 19100 19101 @Override 19102 public void run() { 19103 if (isPressed() && (mParent != null) 19104 && mOriginalWindowAttachCount == mWindowAttachCount) { 19105 if (performLongClick()) { 19106 mHasPerformedLongPress = true; 19107 } 19108 } 19109 } 19110 19111 public void rememberWindowAttachCount() { 19112 mOriginalWindowAttachCount = mWindowAttachCount; 19113 } 19114 } 19115 19116 private final class CheckForTap implements Runnable { 19117 public float x; 19118 public float y; 19119 19120 @Override 19121 public void run() { 19122 mPrivateFlags &= ~PFLAG_PREPRESSED; 19123 setHotspot(R.attr.state_pressed, x, y); 19124 setPressed(true); 19125 checkForLongClick(ViewConfiguration.getTapTimeout()); 19126 } 19127 } 19128 19129 private final class PerformClick implements Runnable { 19130 @Override 19131 public void run() { 19132 performClick(); 19133 } 19134 } 19135 19136 /** @hide */ 19137 public void hackTurnOffWindowResizeAnim(boolean off) { 19138 mAttachInfo.mTurnOffWindowResizeAnim = off; 19139 } 19140 19141 /** 19142 * This method returns a ViewPropertyAnimator object, which can be used to animate 19143 * specific properties on this View. 19144 * 19145 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 19146 */ 19147 public ViewPropertyAnimator animate() { 19148 if (mAnimator == null) { 19149 mAnimator = new ViewPropertyAnimator(this); 19150 } 19151 return mAnimator; 19152 } 19153 19154 /** 19155 * Specifies that the shared name of the View to be shared with another Activity. 19156 * When transitioning between Activities, the name links a UI element in the starting 19157 * Activity to UI element in the called Activity. Names should be unique in the 19158 * View hierarchy. 19159 * 19160 * @param sharedElementName The cross-Activity View identifier. The called Activity will use 19161 * the name to match the location with a View in its layout. 19162 * @see android.app.ActivityOptions#makeSceneTransitionAnimation(android.os.Bundle) 19163 */ 19164 public void setSharedElementName(String sharedElementName) { 19165 setTagInternal(com.android.internal.R.id.shared_element_name, sharedElementName); 19166 } 19167 19168 /** 19169 * Returns the shared name of the View to be shared with another Activity. 19170 * When transitioning between Activities, the name links a UI element in the starting 19171 * Activity to UI element in the called Activity. Names should be unique in the 19172 * View hierarchy. 19173 * 19174 * <p>This returns null if the View is not a shared element or the name if it is.</p> 19175 * 19176 * @return The name used for this View for cross-Activity transitions or null if 19177 * this View has not been identified as shared. 19178 */ 19179 public String getSharedElementName() { 19180 return (String) getTag(com.android.internal.R.id.shared_element_name); 19181 } 19182 19183 /** 19184 * Interface definition for a callback to be invoked when a hardware key event is 19185 * dispatched to this view. The callback will be invoked before the key event is 19186 * given to the view. This is only useful for hardware keyboards; a software input 19187 * method has no obligation to trigger this listener. 19188 */ 19189 public interface OnKeyListener { 19190 /** 19191 * Called when a hardware key is dispatched to a view. This allows listeners to 19192 * get a chance to respond before the target view. 19193 * <p>Key presses in software keyboards will generally NOT trigger this method, 19194 * although some may elect to do so in some situations. Do not assume a 19195 * software input method has to be key-based; even if it is, it may use key presses 19196 * in a different way than you expect, so there is no way to reliably catch soft 19197 * input key presses. 19198 * 19199 * @param v The view the key has been dispatched to. 19200 * @param keyCode The code for the physical key that was pressed 19201 * @param event The KeyEvent object containing full information about 19202 * the event. 19203 * @return True if the listener has consumed the event, false otherwise. 19204 */ 19205 boolean onKey(View v, int keyCode, KeyEvent event); 19206 } 19207 19208 /** 19209 * Interface definition for a callback to be invoked when a touch event is 19210 * dispatched to this view. The callback will be invoked before the touch 19211 * event is given to the view. 19212 */ 19213 public interface OnTouchListener { 19214 /** 19215 * Called when a touch event is dispatched to a view. This allows listeners to 19216 * get a chance to respond before the target view. 19217 * 19218 * @param v The view the touch event has been dispatched to. 19219 * @param event The MotionEvent object containing full information about 19220 * the event. 19221 * @return True if the listener has consumed the event, false otherwise. 19222 */ 19223 boolean onTouch(View v, MotionEvent event); 19224 } 19225 19226 /** 19227 * Interface definition for a callback to be invoked when a hover event is 19228 * dispatched to this view. The callback will be invoked before the hover 19229 * event is given to the view. 19230 */ 19231 public interface OnHoverListener { 19232 /** 19233 * Called when a hover event is dispatched to a view. This allows listeners to 19234 * get a chance to respond before the target view. 19235 * 19236 * @param v The view the hover event has been dispatched to. 19237 * @param event The MotionEvent object containing full information about 19238 * the event. 19239 * @return True if the listener has consumed the event, false otherwise. 19240 */ 19241 boolean onHover(View v, MotionEvent event); 19242 } 19243 19244 /** 19245 * Interface definition for a callback to be invoked when a generic motion event is 19246 * dispatched to this view. The callback will be invoked before the generic motion 19247 * event is given to the view. 19248 */ 19249 public interface OnGenericMotionListener { 19250 /** 19251 * Called when a generic motion event is dispatched to a view. This allows listeners to 19252 * get a chance to respond before the target view. 19253 * 19254 * @param v The view the generic motion event has been dispatched to. 19255 * @param event The MotionEvent object containing full information about 19256 * the event. 19257 * @return True if the listener has consumed the event, false otherwise. 19258 */ 19259 boolean onGenericMotion(View v, MotionEvent event); 19260 } 19261 19262 /** 19263 * Interface definition for a callback to be invoked when a view has been clicked and held. 19264 */ 19265 public interface OnLongClickListener { 19266 /** 19267 * Called when a view has been clicked and held. 19268 * 19269 * @param v The view that was clicked and held. 19270 * 19271 * @return true if the callback consumed the long click, false otherwise. 19272 */ 19273 boolean onLongClick(View v); 19274 } 19275 19276 /** 19277 * Interface definition for a callback to be invoked when a drag is being dispatched 19278 * to this view. The callback will be invoked before the hosting view's own 19279 * onDrag(event) method. If the listener wants to fall back to the hosting view's 19280 * onDrag(event) behavior, it should return 'false' from this callback. 19281 * 19282 * <div class="special reference"> 19283 * <h3>Developer Guides</h3> 19284 * <p>For a guide to implementing drag and drop features, read the 19285 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 19286 * </div> 19287 */ 19288 public interface OnDragListener { 19289 /** 19290 * Called when a drag event is dispatched to a view. This allows listeners 19291 * to get a chance to override base View behavior. 19292 * 19293 * @param v The View that received the drag event. 19294 * @param event The {@link android.view.DragEvent} object for the drag event. 19295 * @return {@code true} if the drag event was handled successfully, or {@code false} 19296 * if the drag event was not handled. Note that {@code false} will trigger the View 19297 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 19298 */ 19299 boolean onDrag(View v, DragEvent event); 19300 } 19301 19302 /** 19303 * Interface definition for a callback to be invoked when the focus state of 19304 * a view changed. 19305 */ 19306 public interface OnFocusChangeListener { 19307 /** 19308 * Called when the focus state of a view has changed. 19309 * 19310 * @param v The view whose state has changed. 19311 * @param hasFocus The new focus state of v. 19312 */ 19313 void onFocusChange(View v, boolean hasFocus); 19314 } 19315 19316 /** 19317 * Interface definition for a callback to be invoked when a view is clicked. 19318 */ 19319 public interface OnClickListener { 19320 /** 19321 * Called when a view has been clicked. 19322 * 19323 * @param v The view that was clicked. 19324 */ 19325 void onClick(View v); 19326 } 19327 19328 /** 19329 * Interface definition for a callback to be invoked when the context menu 19330 * for this view is being built. 19331 */ 19332 public interface OnCreateContextMenuListener { 19333 /** 19334 * Called when the context menu for this view is being built. It is not 19335 * safe to hold onto the menu after this method returns. 19336 * 19337 * @param menu The context menu that is being built 19338 * @param v The view for which the context menu is being built 19339 * @param menuInfo Extra information about the item for which the 19340 * context menu should be shown. This information will vary 19341 * depending on the class of v. 19342 */ 19343 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 19344 } 19345 19346 /** 19347 * Interface definition for a callback to be invoked when the status bar changes 19348 * visibility. This reports <strong>global</strong> changes to the system UI 19349 * state, not what the application is requesting. 19350 * 19351 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 19352 */ 19353 public interface OnSystemUiVisibilityChangeListener { 19354 /** 19355 * Called when the status bar changes visibility because of a call to 19356 * {@link View#setSystemUiVisibility(int)}. 19357 * 19358 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 19359 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}. 19360 * This tells you the <strong>global</strong> state of these UI visibility 19361 * flags, not what your app is currently applying. 19362 */ 19363 public void onSystemUiVisibilityChange(int visibility); 19364 } 19365 19366 /** 19367 * Interface definition for a callback to be invoked when this view is attached 19368 * or detached from its window. 19369 */ 19370 public interface OnAttachStateChangeListener { 19371 /** 19372 * Called when the view is attached to a window. 19373 * @param v The view that was attached 19374 */ 19375 public void onViewAttachedToWindow(View v); 19376 /** 19377 * Called when the view is detached from a window. 19378 * @param v The view that was detached 19379 */ 19380 public void onViewDetachedFromWindow(View v); 19381 } 19382 19383 /** 19384 * Listener for applying window insets on a view in a custom way. 19385 * 19386 * <p>Apps may choose to implement this interface if they want to apply custom policy 19387 * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener 19388 * is set, its 19389 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 19390 * method will be called instead of the View's own 19391 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener 19392 * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply 19393 * the View's normal behavior as part of its own.</p> 19394 */ 19395 public interface OnApplyWindowInsetsListener { 19396 /** 19397 * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set} 19398 * on a View, this listener method will be called instead of the view's own 19399 * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 19400 * 19401 * @param v The view applying window insets 19402 * @param insets The insets to apply 19403 * @return The insets supplied, minus any insets that were consumed 19404 */ 19405 public WindowInsets onApplyWindowInsets(View v, WindowInsets insets); 19406 } 19407 19408 private final class UnsetPressedState implements Runnable { 19409 @Override 19410 public void run() { 19411 clearHotspot(R.attr.state_pressed); 19412 setPressed(false); 19413 } 19414 } 19415 19416 /** 19417 * Base class for derived classes that want to save and restore their own 19418 * state in {@link android.view.View#onSaveInstanceState()}. 19419 */ 19420 public static class BaseSavedState extends AbsSavedState { 19421 /** 19422 * Constructor used when reading from a parcel. Reads the state of the superclass. 19423 * 19424 * @param source 19425 */ 19426 public BaseSavedState(Parcel source) { 19427 super(source); 19428 } 19429 19430 /** 19431 * Constructor called by derived classes when creating their SavedState objects 19432 * 19433 * @param superState The state of the superclass of this view 19434 */ 19435 public BaseSavedState(Parcelable superState) { 19436 super(superState); 19437 } 19438 19439 public static final Parcelable.Creator<BaseSavedState> CREATOR = 19440 new Parcelable.Creator<BaseSavedState>() { 19441 public BaseSavedState createFromParcel(Parcel in) { 19442 return new BaseSavedState(in); 19443 } 19444 19445 public BaseSavedState[] newArray(int size) { 19446 return new BaseSavedState[size]; 19447 } 19448 }; 19449 } 19450 19451 /** 19452 * A set of information given to a view when it is attached to its parent 19453 * window. 19454 */ 19455 static class AttachInfo { 19456 interface Callbacks { 19457 void playSoundEffect(int effectId); 19458 boolean performHapticFeedback(int effectId, boolean always); 19459 } 19460 19461 /** 19462 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 19463 * to a Handler. This class contains the target (View) to invalidate and 19464 * the coordinates of the dirty rectangle. 19465 * 19466 * For performance purposes, this class also implements a pool of up to 19467 * POOL_LIMIT objects that get reused. This reduces memory allocations 19468 * whenever possible. 19469 */ 19470 static class InvalidateInfo { 19471 private static final int POOL_LIMIT = 10; 19472 19473 private static final SynchronizedPool<InvalidateInfo> sPool = 19474 new SynchronizedPool<InvalidateInfo>(POOL_LIMIT); 19475 19476 View target; 19477 19478 int left; 19479 int top; 19480 int right; 19481 int bottom; 19482 19483 public static InvalidateInfo obtain() { 19484 InvalidateInfo instance = sPool.acquire(); 19485 return (instance != null) ? instance : new InvalidateInfo(); 19486 } 19487 19488 public void recycle() { 19489 target = null; 19490 sPool.release(this); 19491 } 19492 } 19493 19494 final IWindowSession mSession; 19495 19496 final IWindow mWindow; 19497 19498 final IBinder mWindowToken; 19499 19500 final Display mDisplay; 19501 19502 final Callbacks mRootCallbacks; 19503 19504 IWindowId mIWindowId; 19505 WindowId mWindowId; 19506 19507 /** 19508 * The top view of the hierarchy. 19509 */ 19510 View mRootView; 19511 19512 IBinder mPanelParentWindowToken; 19513 19514 boolean mHardwareAccelerated; 19515 boolean mHardwareAccelerationRequested; 19516 HardwareRenderer mHardwareRenderer; 19517 19518 boolean mScreenOn; 19519 19520 /** 19521 * Scale factor used by the compatibility mode 19522 */ 19523 float mApplicationScale; 19524 19525 /** 19526 * Indicates whether the application is in compatibility mode 19527 */ 19528 boolean mScalingRequired; 19529 19530 /** 19531 * If set, ViewRootImpl doesn't use its lame animation for when the window resizes. 19532 */ 19533 boolean mTurnOffWindowResizeAnim; 19534 19535 /** 19536 * Left position of this view's window 19537 */ 19538 int mWindowLeft; 19539 19540 /** 19541 * Top position of this view's window 19542 */ 19543 int mWindowTop; 19544 19545 /** 19546 * Indicates whether views need to use 32-bit drawing caches 19547 */ 19548 boolean mUse32BitDrawingCache; 19549 19550 /** 19551 * For windows that are full-screen but using insets to layout inside 19552 * of the screen areas, these are the current insets to appear inside 19553 * the overscan area of the display. 19554 */ 19555 final Rect mOverscanInsets = new Rect(); 19556 19557 /** 19558 * For windows that are full-screen but using insets to layout inside 19559 * of the screen decorations, these are the current insets for the 19560 * content of the window. 19561 */ 19562 final Rect mContentInsets = new Rect(); 19563 19564 /** 19565 * For windows that are full-screen but using insets to layout inside 19566 * of the screen decorations, these are the current insets for the 19567 * actual visible parts of the window. 19568 */ 19569 final Rect mVisibleInsets = new Rect(); 19570 19571 /** 19572 * The internal insets given by this window. This value is 19573 * supplied by the client (through 19574 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 19575 * be given to the window manager when changed to be used in laying 19576 * out windows behind it. 19577 */ 19578 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 19579 = new ViewTreeObserver.InternalInsetsInfo(); 19580 19581 /** 19582 * Set to true when mGivenInternalInsets is non-empty. 19583 */ 19584 boolean mHasNonEmptyGivenInternalInsets; 19585 19586 /** 19587 * All views in the window's hierarchy that serve as scroll containers, 19588 * used to determine if the window can be resized or must be panned 19589 * to adjust for a soft input area. 19590 */ 19591 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 19592 19593 final KeyEvent.DispatcherState mKeyDispatchState 19594 = new KeyEvent.DispatcherState(); 19595 19596 /** 19597 * Indicates whether the view's window currently has the focus. 19598 */ 19599 boolean mHasWindowFocus; 19600 19601 /** 19602 * The current visibility of the window. 19603 */ 19604 int mWindowVisibility; 19605 19606 /** 19607 * Indicates the time at which drawing started to occur. 19608 */ 19609 long mDrawingTime; 19610 19611 /** 19612 * Indicates whether or not ignoring the DIRTY_MASK flags. 19613 */ 19614 boolean mIgnoreDirtyState; 19615 19616 /** 19617 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 19618 * to avoid clearing that flag prematurely. 19619 */ 19620 boolean mSetIgnoreDirtyState = false; 19621 19622 /** 19623 * Indicates whether the view's window is currently in touch mode. 19624 */ 19625 boolean mInTouchMode; 19626 19627 /** 19628 * Indicates that ViewAncestor should trigger a global layout change 19629 * the next time it performs a traversal 19630 */ 19631 boolean mRecomputeGlobalAttributes; 19632 19633 /** 19634 * Always report new attributes at next traversal. 19635 */ 19636 boolean mForceReportNewAttributes; 19637 19638 /** 19639 * Set during a traveral if any views want to keep the screen on. 19640 */ 19641 boolean mKeepScreenOn; 19642 19643 /** 19644 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 19645 */ 19646 int mSystemUiVisibility; 19647 19648 /** 19649 * Hack to force certain system UI visibility flags to be cleared. 19650 */ 19651 int mDisabledSystemUiVisibility; 19652 19653 /** 19654 * Last global system UI visibility reported by the window manager. 19655 */ 19656 int mGlobalSystemUiVisibility; 19657 19658 /** 19659 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 19660 * attached. 19661 */ 19662 boolean mHasSystemUiListeners; 19663 19664 /** 19665 * Set if the window has requested to extend into the overscan region 19666 * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN. 19667 */ 19668 boolean mOverscanRequested; 19669 19670 /** 19671 * Set if the visibility of any views has changed. 19672 */ 19673 boolean mViewVisibilityChanged; 19674 19675 /** 19676 * Set to true if a view has been scrolled. 19677 */ 19678 boolean mViewScrollChanged; 19679 19680 /** 19681 * Global to the view hierarchy used as a temporary for dealing with 19682 * x/y points in the transparent region computations. 19683 */ 19684 final int[] mTransparentLocation = new int[2]; 19685 19686 /** 19687 * Global to the view hierarchy used as a temporary for dealing with 19688 * x/y points in the ViewGroup.invalidateChild implementation. 19689 */ 19690 final int[] mInvalidateChildLocation = new int[2]; 19691 19692 19693 /** 19694 * Global to the view hierarchy used as a temporary for dealing with 19695 * x/y location when view is transformed. 19696 */ 19697 final float[] mTmpTransformLocation = new float[2]; 19698 19699 /** 19700 * The view tree observer used to dispatch global events like 19701 * layout, pre-draw, touch mode change, etc. 19702 */ 19703 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 19704 19705 /** 19706 * A Canvas used by the view hierarchy to perform bitmap caching. 19707 */ 19708 Canvas mCanvas; 19709 19710 /** 19711 * The view root impl. 19712 */ 19713 final ViewRootImpl mViewRootImpl; 19714 19715 /** 19716 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 19717 * handler can be used to pump events in the UI events queue. 19718 */ 19719 final Handler mHandler; 19720 19721 /** 19722 * Temporary for use in computing invalidate rectangles while 19723 * calling up the hierarchy. 19724 */ 19725 final Rect mTmpInvalRect = new Rect(); 19726 19727 /** 19728 * Temporary for use in computing hit areas with transformed views 19729 */ 19730 final RectF mTmpTransformRect = new RectF(); 19731 19732 /** 19733 * Temporary for use in transforming invalidation rect 19734 */ 19735 final Matrix mTmpMatrix = new Matrix(); 19736 19737 /** 19738 * Temporary for use in transforming invalidation rect 19739 */ 19740 final Transformation mTmpTransformation = new Transformation(); 19741 19742 /** 19743 * Temporary list for use in collecting focusable descendents of a view. 19744 */ 19745 final ArrayList<View> mTempArrayList = new ArrayList<View>(24); 19746 19747 /** 19748 * The id of the window for accessibility purposes. 19749 */ 19750 int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 19751 19752 /** 19753 * Flags related to accessibility processing. 19754 * 19755 * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS 19756 * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS 19757 */ 19758 int mAccessibilityFetchFlags; 19759 19760 /** 19761 * The drawable for highlighting accessibility focus. 19762 */ 19763 Drawable mAccessibilityFocusDrawable; 19764 19765 /** 19766 * Show where the margins, bounds and layout bounds are for each view. 19767 */ 19768 boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false); 19769 19770 /** 19771 * Point used to compute visible regions. 19772 */ 19773 final Point mPoint = new Point(); 19774 19775 /** 19776 * Used to track which View originated a requestLayout() call, used when 19777 * requestLayout() is called during layout. 19778 */ 19779 View mViewRequestingLayout; 19780 19781 /** 19782 * Creates a new set of attachment information with the specified 19783 * events handler and thread. 19784 * 19785 * @param handler the events handler the view must use 19786 */ 19787 AttachInfo(IWindowSession session, IWindow window, Display display, 19788 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) { 19789 mSession = session; 19790 mWindow = window; 19791 mWindowToken = window.asBinder(); 19792 mDisplay = display; 19793 mViewRootImpl = viewRootImpl; 19794 mHandler = handler; 19795 mRootCallbacks = effectPlayer; 19796 } 19797 } 19798 19799 /** 19800 * <p>ScrollabilityCache holds various fields used by a View when scrolling 19801 * is supported. This avoids keeping too many unused fields in most 19802 * instances of View.</p> 19803 */ 19804 private static class ScrollabilityCache implements Runnable { 19805 19806 /** 19807 * Scrollbars are not visible 19808 */ 19809 public static final int OFF = 0; 19810 19811 /** 19812 * Scrollbars are visible 19813 */ 19814 public static final int ON = 1; 19815 19816 /** 19817 * Scrollbars are fading away 19818 */ 19819 public static final int FADING = 2; 19820 19821 public boolean fadeScrollBars; 19822 19823 public int fadingEdgeLength; 19824 public int scrollBarDefaultDelayBeforeFade; 19825 public int scrollBarFadeDuration; 19826 19827 public int scrollBarSize; 19828 public ScrollBarDrawable scrollBar; 19829 public float[] interpolatorValues; 19830 public View host; 19831 19832 public final Paint paint; 19833 public final Matrix matrix; 19834 public Shader shader; 19835 19836 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 19837 19838 private static final float[] OPAQUE = { 255 }; 19839 private static final float[] TRANSPARENT = { 0.0f }; 19840 19841 /** 19842 * When fading should start. This time moves into the future every time 19843 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 19844 */ 19845 public long fadeStartTime; 19846 19847 19848 /** 19849 * The current state of the scrollbars: ON, OFF, or FADING 19850 */ 19851 public int state = OFF; 19852 19853 private int mLastColor; 19854 19855 public ScrollabilityCache(ViewConfiguration configuration, View host) { 19856 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 19857 scrollBarSize = configuration.getScaledScrollBarSize(); 19858 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 19859 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 19860 19861 paint = new Paint(); 19862 matrix = new Matrix(); 19863 // use use a height of 1, and then wack the matrix each time we 19864 // actually use it. 19865 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 19866 paint.setShader(shader); 19867 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 19868 19869 this.host = host; 19870 } 19871 19872 public void setFadeColor(int color) { 19873 if (color != mLastColor) { 19874 mLastColor = color; 19875 19876 if (color != 0) { 19877 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 19878 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 19879 paint.setShader(shader); 19880 // Restore the default transfer mode (src_over) 19881 paint.setXfermode(null); 19882 } else { 19883 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 19884 paint.setShader(shader); 19885 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 19886 } 19887 } 19888 } 19889 19890 public void run() { 19891 long now = AnimationUtils.currentAnimationTimeMillis(); 19892 if (now >= fadeStartTime) { 19893 19894 // the animation fades the scrollbars out by changing 19895 // the opacity (alpha) from fully opaque to fully 19896 // transparent 19897 int nextFrame = (int) now; 19898 int framesCount = 0; 19899 19900 Interpolator interpolator = scrollBarInterpolator; 19901 19902 // Start opaque 19903 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 19904 19905 // End transparent 19906 nextFrame += scrollBarFadeDuration; 19907 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 19908 19909 state = FADING; 19910 19911 // Kick off the fade animation 19912 host.invalidate(true); 19913 } 19914 } 19915 } 19916 19917 /** 19918 * Resuable callback for sending 19919 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 19920 */ 19921 private class SendViewScrolledAccessibilityEvent implements Runnable { 19922 public volatile boolean mIsPending; 19923 19924 public void run() { 19925 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 19926 mIsPending = false; 19927 } 19928 } 19929 19930 /** 19931 * <p> 19932 * This class represents a delegate that can be registered in a {@link View} 19933 * to enhance accessibility support via composition rather via inheritance. 19934 * It is specifically targeted to widget developers that extend basic View 19935 * classes i.e. classes in package android.view, that would like their 19936 * applications to be backwards compatible. 19937 * </p> 19938 * <div class="special reference"> 19939 * <h3>Developer Guides</h3> 19940 * <p>For more information about making applications accessible, read the 19941 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a> 19942 * developer guide.</p> 19943 * </div> 19944 * <p> 19945 * A scenario in which a developer would like to use an accessibility delegate 19946 * is overriding a method introduced in a later API version then the minimal API 19947 * version supported by the application. For example, the method 19948 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 19949 * in API version 4 when the accessibility APIs were first introduced. If a 19950 * developer would like his application to run on API version 4 devices (assuming 19951 * all other APIs used by the application are version 4 or lower) and take advantage 19952 * of this method, instead of overriding the method which would break the application's 19953 * backwards compatibility, he can override the corresponding method in this 19954 * delegate and register the delegate in the target View if the API version of 19955 * the system is high enough i.e. the API version is same or higher to the API 19956 * version that introduced 19957 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 19958 * </p> 19959 * <p> 19960 * Here is an example implementation: 19961 * </p> 19962 * <code><pre><p> 19963 * if (Build.VERSION.SDK_INT >= 14) { 19964 * // If the API version is equal of higher than the version in 19965 * // which onInitializeAccessibilityNodeInfo was introduced we 19966 * // register a delegate with a customized implementation. 19967 * View view = findViewById(R.id.view_id); 19968 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 19969 * public void onInitializeAccessibilityNodeInfo(View host, 19970 * AccessibilityNodeInfo info) { 19971 * // Let the default implementation populate the info. 19972 * super.onInitializeAccessibilityNodeInfo(host, info); 19973 * // Set some other information. 19974 * info.setEnabled(host.isEnabled()); 19975 * } 19976 * }); 19977 * } 19978 * </code></pre></p> 19979 * <p> 19980 * This delegate contains methods that correspond to the accessibility methods 19981 * in View. If a delegate has been specified the implementation in View hands 19982 * off handling to the corresponding method in this delegate. The default 19983 * implementation the delegate methods behaves exactly as the corresponding 19984 * method in View for the case of no accessibility delegate been set. Hence, 19985 * to customize the behavior of a View method, clients can override only the 19986 * corresponding delegate method without altering the behavior of the rest 19987 * accessibility related methods of the host view. 19988 * </p> 19989 */ 19990 public static class AccessibilityDelegate { 19991 19992 /** 19993 * Sends an accessibility event of the given type. If accessibility is not 19994 * enabled this method has no effect. 19995 * <p> 19996 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 19997 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 19998 * been set. 19999 * </p> 20000 * 20001 * @param host The View hosting the delegate. 20002 * @param eventType The type of the event to send. 20003 * 20004 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 20005 */ 20006 public void sendAccessibilityEvent(View host, int eventType) { 20007 host.sendAccessibilityEventInternal(eventType); 20008 } 20009 20010 /** 20011 * Performs the specified accessibility action on the view. For 20012 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 20013 * <p> 20014 * The default implementation behaves as 20015 * {@link View#performAccessibilityAction(int, Bundle) 20016 * View#performAccessibilityAction(int, Bundle)} for the case of 20017 * no accessibility delegate been set. 20018 * </p> 20019 * 20020 * @param action The action to perform. 20021 * @return Whether the action was performed. 20022 * 20023 * @see View#performAccessibilityAction(int, Bundle) 20024 * View#performAccessibilityAction(int, Bundle) 20025 */ 20026 public boolean performAccessibilityAction(View host, int action, Bundle args) { 20027 return host.performAccessibilityActionInternal(action, args); 20028 } 20029 20030 /** 20031 * Sends an accessibility event. This method behaves exactly as 20032 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 20033 * empty {@link AccessibilityEvent} and does not perform a check whether 20034 * accessibility is enabled. 20035 * <p> 20036 * The default implementation behaves as 20037 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20038 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 20039 * the case of no accessibility delegate been set. 20040 * </p> 20041 * 20042 * @param host The View hosting the delegate. 20043 * @param event The event to send. 20044 * 20045 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20046 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20047 */ 20048 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 20049 host.sendAccessibilityEventUncheckedInternal(event); 20050 } 20051 20052 /** 20053 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 20054 * to its children for adding their text content to the event. 20055 * <p> 20056 * The default implementation behaves as 20057 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20058 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 20059 * the case of no accessibility delegate been set. 20060 * </p> 20061 * 20062 * @param host The View hosting the delegate. 20063 * @param event The event. 20064 * @return True if the event population was completed. 20065 * 20066 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20067 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20068 */ 20069 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 20070 return host.dispatchPopulateAccessibilityEventInternal(event); 20071 } 20072 20073 /** 20074 * Gives a chance to the host View to populate the accessibility event with its 20075 * text content. 20076 * <p> 20077 * The default implementation behaves as 20078 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 20079 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 20080 * the case of no accessibility delegate been set. 20081 * </p> 20082 * 20083 * @param host The View hosting the delegate. 20084 * @param event The accessibility event which to populate. 20085 * 20086 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 20087 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 20088 */ 20089 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 20090 host.onPopulateAccessibilityEventInternal(event); 20091 } 20092 20093 /** 20094 * Initializes an {@link AccessibilityEvent} with information about the 20095 * the host View which is the event source. 20096 * <p> 20097 * The default implementation behaves as 20098 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 20099 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 20100 * the case of no accessibility delegate been set. 20101 * </p> 20102 * 20103 * @param host The View hosting the delegate. 20104 * @param event The event to initialize. 20105 * 20106 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 20107 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 20108 */ 20109 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 20110 host.onInitializeAccessibilityEventInternal(event); 20111 } 20112 20113 /** 20114 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 20115 * <p> 20116 * The default implementation behaves as 20117 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20118 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 20119 * the case of no accessibility delegate been set. 20120 * </p> 20121 * 20122 * @param host The View hosting the delegate. 20123 * @param info The instance to initialize. 20124 * 20125 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20126 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20127 */ 20128 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 20129 host.onInitializeAccessibilityNodeInfoInternal(info); 20130 } 20131 20132 /** 20133 * Called when a child of the host View has requested sending an 20134 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 20135 * to augment the event. 20136 * <p> 20137 * The default implementation behaves as 20138 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20139 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 20140 * the case of no accessibility delegate been set. 20141 * </p> 20142 * 20143 * @param host The View hosting the delegate. 20144 * @param child The child which requests sending the event. 20145 * @param event The event to be sent. 20146 * @return True if the event should be sent 20147 * 20148 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20149 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20150 */ 20151 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 20152 AccessibilityEvent event) { 20153 return host.onRequestSendAccessibilityEventInternal(child, event); 20154 } 20155 20156 /** 20157 * Gets the provider for managing a virtual view hierarchy rooted at this View 20158 * and reported to {@link android.accessibilityservice.AccessibilityService}s 20159 * that explore the window content. 20160 * <p> 20161 * The default implementation behaves as 20162 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 20163 * the case of no accessibility delegate been set. 20164 * </p> 20165 * 20166 * @return The provider. 20167 * 20168 * @see AccessibilityNodeProvider 20169 */ 20170 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 20171 return null; 20172 } 20173 20174 /** 20175 * Returns an {@link AccessibilityNodeInfo} representing the host view from the 20176 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 20177 * This method is responsible for obtaining an accessibility node info from a 20178 * pool of reusable instances and calling 20179 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host 20180 * view to initialize the former. 20181 * <p> 20182 * <strong>Note:</strong> The client is responsible for recycling the obtained 20183 * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object 20184 * creation. 20185 * </p> 20186 * <p> 20187 * The default implementation behaves as 20188 * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for 20189 * the case of no accessibility delegate been set. 20190 * </p> 20191 * @return A populated {@link AccessibilityNodeInfo}. 20192 * 20193 * @see AccessibilityNodeInfo 20194 * 20195 * @hide 20196 */ 20197 public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) { 20198 return host.createAccessibilityNodeInfoInternal(); 20199 } 20200 } 20201 20202 private class MatchIdPredicate implements Predicate<View> { 20203 public int mId; 20204 20205 @Override 20206 public boolean apply(View view) { 20207 return (view.mID == mId); 20208 } 20209 } 20210 20211 private class MatchLabelForPredicate implements Predicate<View> { 20212 private int mLabeledId; 20213 20214 @Override 20215 public boolean apply(View view) { 20216 return (view.mLabelForId == mLabeledId); 20217 } 20218 } 20219 20220 private class SendViewStateChangedAccessibilityEvent implements Runnable { 20221 private int mChangeTypes = 0; 20222 private boolean mPosted; 20223 private boolean mPostedWithDelay; 20224 private long mLastEventTimeMillis; 20225 20226 @Override 20227 public void run() { 20228 mPosted = false; 20229 mPostedWithDelay = false; 20230 mLastEventTimeMillis = SystemClock.uptimeMillis(); 20231 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 20232 final AccessibilityEvent event = AccessibilityEvent.obtain(); 20233 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 20234 event.setContentChangeTypes(mChangeTypes); 20235 sendAccessibilityEventUnchecked(event); 20236 } 20237 mChangeTypes = 0; 20238 } 20239 20240 public void runOrPost(int changeType) { 20241 mChangeTypes |= changeType; 20242 20243 // If this is a live region or the child of a live region, collect 20244 // all events from this frame and send them on the next frame. 20245 if (inLiveRegion()) { 20246 // If we're already posted with a delay, remove that. 20247 if (mPostedWithDelay) { 20248 removeCallbacks(this); 20249 mPostedWithDelay = false; 20250 } 20251 // Only post if we're not already posted. 20252 if (!mPosted) { 20253 post(this); 20254 mPosted = true; 20255 } 20256 return; 20257 } 20258 20259 if (mPosted) { 20260 return; 20261 } 20262 final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis; 20263 final long minEventIntevalMillis = 20264 ViewConfiguration.getSendRecurringAccessibilityEventsInterval(); 20265 if (timeSinceLastMillis >= minEventIntevalMillis) { 20266 removeCallbacks(this); 20267 run(); 20268 } else { 20269 postDelayed(this, minEventIntevalMillis - timeSinceLastMillis); 20270 mPosted = true; 20271 mPostedWithDelay = true; 20272 } 20273 } 20274 } 20275 20276 private boolean inLiveRegion() { 20277 if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) { 20278 return true; 20279 } 20280 20281 ViewParent parent = getParent(); 20282 while (parent instanceof View) { 20283 if (((View) parent).getAccessibilityLiveRegion() 20284 != View.ACCESSIBILITY_LIVE_REGION_NONE) { 20285 return true; 20286 } 20287 parent = parent.getParent(); 20288 } 20289 20290 return false; 20291 } 20292 20293 /** 20294 * Dump all private flags in readable format, useful for documentation and 20295 * sanity checking. 20296 */ 20297 private static void dumpFlags() { 20298 final HashMap<String, String> found = Maps.newHashMap(); 20299 try { 20300 for (Field field : View.class.getDeclaredFields()) { 20301 final int modifiers = field.getModifiers(); 20302 if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { 20303 if (field.getType().equals(int.class)) { 20304 final int value = field.getInt(null); 20305 dumpFlag(found, field.getName(), value); 20306 } else if (field.getType().equals(int[].class)) { 20307 final int[] values = (int[]) field.get(null); 20308 for (int i = 0; i < values.length; i++) { 20309 dumpFlag(found, field.getName() + "[" + i + "]", values[i]); 20310 } 20311 } 20312 } 20313 } 20314 } catch (IllegalAccessException e) { 20315 throw new RuntimeException(e); 20316 } 20317 20318 final ArrayList<String> keys = Lists.newArrayList(); 20319 keys.addAll(found.keySet()); 20320 Collections.sort(keys); 20321 for (String key : keys) { 20322 Log.d(VIEW_LOG_TAG, found.get(key)); 20323 } 20324 } 20325 20326 private static void dumpFlag(HashMap<String, String> found, String name, int value) { 20327 // Sort flags by prefix, then by bits, always keeping unique keys 20328 final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' '); 20329 final int prefix = name.indexOf('_'); 20330 final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name; 20331 final String output = bits + " " + name; 20332 found.put(key, output); 20333 } 20334} 20335